Need fix on stopping page reloading after file uploading

I’m trying to upload files to the server without page refresh. The uploading works but the page reloads after the uploading is done which is not what I wanted. I’m redirecting to an iframe (“myFrame”) to stop the page reloading but it appears this doesn’t work correctly. What did I do wrong?

HTML

<form id="upload" target="myFrame" action="sql/main-pix-upload.php" method="post" enctype="multipart/form-data">
  <input id="main-pix" class="hidden" name="main_pix" type="file" onchange="uploadPix()" accept="image/*"/>
  <label class="gi gi-camera mb-0 text-white" for="main-pix" type="button" title="Change Picture"></label>
</form>

SCRIPT

function uploadPix(){
  var form = document.getElementById('upload');
  form.onsubmit = function(e){
    e.preventDefault()
    var formData = new FormData(this);
    $.ajax({
      url: 'sql/main-pix-upload.php',
      type: 'POST',
      data: formData,
      async: false,
      cache: false,
      contentType: false,
      processData: false
    })
  });
};

PHP

$account = $_SESSION['account'];
$order = $_SESSION['order'];
$id = $_SESSION['id'];

$pathPix = ('../accounts/'.$account.'/'.$order.'/pix/'.$id.'/');
if(!is_dir($pathPix)){
  mkdir($pathPix, 0777, true);
}

$file_name = $_FILES['main_pix']['name'];
$file_size = $_FILES['main_pix']['size'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = "main-pix.png";
$temp = ($_FILES["main_pix"]["tmp_name"]);
$target_file = ($pathPix.$new_name);

if(0 < $_FILES['main_pix']['error']){
  echo 'Error: ' . $_FILES['main_pix']['error'] . '<br>';
}else{
  move_uploaded_file($temp, $target_file);
}


Source: stackoverflow-php

pass array of numbers from ajax to controller

I know this is a popular topic and I’ve tried all of the solutions I could find already out there to no avail. I’ve used all the solutions included for this questions: Pass a List from javascript to controller. I’ve simplified my test to ridiculously simple. I get into the controller but my controller input param is {int[0]}. I confirmed my array data looks good in the JavaScript and ajax call.

Can anyone please tell me what I am missing?

JavaScript Code

var selectedIds = [];
selectedIds.push(565);
selectedIds.push(573);
selectedIds.push(571);
// selectedIds = [565, 573, 571]

$.ajax({
    type: "POST",
    traditional: true,
    dataType: "json",
    data: { "ids": JSON.stringify(selectedIds) },
    //data: { "ids": selectedIds},
    //data: { ids: selectedIds},
    url: "api/services/getbuildingsbyid",
    success: function (result) {
        return result;
    }
});

Controller Code

[HttpPost]
public bool GetBuildingsById(int[] ids)
{
    var lookAtIds = ids;     // {int[0]}
    return true;
}


Source: stackoverflow-javascript

Data is not being deleted Ajax

I am new to coding. I am sorry to keep you busy with this easy question but I could not solve the problem for hours. When I clicked on the sil button, “Are you sure you want to delete it?” When I click on the message, a blank message page comes up and the data is not deleted.

(document).ready(function(){

     var productTable = $('#product_data').bootgrid({
      ajax: true,
      rowSelect: true,
      post: function()
      {
      },
      url: "fetch.php",
      formatters: {
       "commands": function(column, row)
       {
           var link="";
          /*  
            1001 => "siparis_toplubaski"  
            1002 => "siparis_ana" 
            1003 => "siparis_cokluforma"  
            1004 => "siparis_digitalbaski"   
            1005 => "siparis_etiket"  
            1006 => "siparis_matbuu"   
            1007 => "siparis_ofset"
          */


           if(row.formid==1001){
               link="siparis_toplubaski.php?DAID="+row.Id;
           }else if(row.formid==1002){
               link="siparis_ana.php?DAID="+row.Id;
           }else if(row.formid==1003){
               link="siparis_cokluforma.php?DAID="+row.Id;
           }else if(row.formid==1004){
               link="siparis_digitalbaski.php?DAID="+row.Id;
           }else if(row.formid==1005){
               link="siparis_etiket.php?DAID="+row.Id;
           }else if(row.formid==1006){
               link="siparis_matbuu.php?DAID="+row.Id;
           }else if(row.formid==1007){
               link="siparis_ofset.php?DAID="+row.Id;
           }


        return "<a href='"+link+"' type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.Id+"'>D├╝zenle</a>" + 
        "&nbsp; <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.Id+"'>Sil</button>"

       }
      }
     });


     $(document).on("loaded.rs.jquery.bootgrid", function()
     {
       productTable.find(".delete").on("click", function(event)
      {
       if(confirm("Are you sure you want to delete this?"))
       {
        var Id = $(this).data("+row.Id+");
        $.ajax({
         url:"delete.php",
         method:"POST",
         data:{Id:Id},
         success:function(data)
         {
          alert(data);
          $('#product_data').bootgrid('reload');
         }
        })
       }
       else{
        return false;
       }
      });
      });    
     });

This is delete.php

<?php
//delete.php
include("connection.php");
if(isset($_POST["product_id"]))
{
 $query = "DELETE FROM siparis_ana WHERE Id = '".$_POST["id"]."'";
 if(mysqli_query($connection, $query))
 {
  echo 'Data Deleted';
 }
}
?>


Source: stackoverflow-php

Sort a table that is created using document.write() in javascript

I have written the following code that displays a table of 4 columns on ajax success. I wish to sort this table based on the 4 columns. I tried doing it using some readymade .js files available online. but, didn’t succeed. How can I achieve the requirement?

function Success(data)
{
var obj;
obj=JSON.parse(data);
document.write("<html><head><title>Service</title></head><body 
bgcolor=#FFFFFB>");
document.write("
"); document.write("

Details

"); document.write(""); document.write(""); document.write(""); document.write(""); document.write(""); document.write(""); document.write(""); document.write("
"); for(i=0; i"); document.write(""); document.write(""); document.write(""); document.write(""); document.write(""); } document.write("
"); document.write("Name"); document.write(""); document.write("Number1"); document.write(""); document.write("Number2"); document.write(""); document.write("Number3"); document.write("
"); document.write(obj[i]); document.write(""); document.write(obj[i+1]); document.write(""); document.write(obj[i+2]); document.write(""); document.write(obj[i+3]); document.write("
"); document.write("
"); document.write("</body></html>"); } </script>


Source: stackoverflow-javascript

filtering mysql results which are dynamically loaded

I have 3 pages

  • index.php
  • fetch_pages.php
  • script.js

and a list of artists, the get page fetches the results and the script.js asks for more to dynamically load it into index php, but it loads all of the artists.

loading all the artists dynamically took me a long time and I didn’t fully understand all of the code I’ve copied to achieve this, but now as I don’t fully understand it it’s hard to play around with it, but I believe that I’ll learn along the way

what I want to do is instead of loading all the artists to load the results according to user input (if he clicks photographers load photographers, if he enters a search term to look for results LIKE what he searched for)

What I’ve tried is the $_GET method, but it posts the searchterm in the url of index.php, and when I try to use $_GET in fetch_pages.php it doesn’t see the parameter.

my question is how to $_GET the url parameter from index.php to fetch_pages.php

below is my code

index.php

<?php
// including the config file
include('config.php');
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Setch</title>
  https://code.jquery.com/jquery-3.2.1.min.js
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
  <link rel="stylesheet" href="css/style.css" />
</head>
<body>
  

JQuery Ajax 500 (Internal Server Error)

I’m utilizing the jquery library to make an ajax call to a php file. Everything was working fine when the path was relative like this:

url:"fetch_term_grades.php",

But when I change the path like this:

url:"includes/ajax/fetch_term_grades.php",

I’m getting this error from the console:

jquery-2.2.3.min.js:4 POST http://localhost/SchoolMate/includes/ajax/fetch_term_grades.php 500 (Internal Server Error)

enter image description here

This is my ajax code:

$.ajax({
        url:"includes/ajax/fetch_term_grades.php",
        method:"post",
        data:{"term":term},
        dataType:"text",
        success:function(data){
            $("#result").html(data);               
            $('#dataTable').DataTable();
            //$('table').attr('id', 'dataTable');  
        }

      });


Source: stackoverflow-php

pass array values from AJAx to PHP

Hi i am facing some issues. I am trying to insert array in mysql using ajax and php but its not working following is my code:

HTML:

 <input type="text" class="form-control" name="invoice" id="invoice"   placeholder="piece">
 <input type="text" class="form-control" name="pieces[]" id="pieces" placeholder="Qty">

i want to pass fields from ajax to php. I am using following code in ajax.

var inv = $("#invoice").val();
var pieces = $("#pieces").val();

$.ajax({

    type: "POST",
    url: "query.php",
    data: "piece="+pieces+"&inv="+inv,
    success: function(data){

        $("#result").html(data);
    }

});

following is the PHP code.

<?php
$piece = $_POST[piece];
foreach ($piece as $key=>$value)
{
$query = mysql_query(insert into items values ('$value','$_POST[inv]');
}
?>


Source: stackoverflow-php

JS continue after multiple .load()-functions done

I’m having a problem with an asynchronous JS function. Well I have a function which inserts elements one by one. This works. But I would like to continue after all .load()-functions are done.

The way I’ve implemented the Deferred() part is obviously wrong but I have no clue how to achieve this.

Note: I have simplified the code for a better clarity.

var d = new jQuery.Deferred();
var i = index;
function loadView() {
    if(i > -1 && i < array.length) {
        if(!jQuery.contains(document.documentElement, $(selector)[0])) {
            /* do stuff here */
            panel.load(myPHPfile, function() {
                $dom.append($(selector));
                i++;
                if(i < array.length) {
                    loadView();
                    d.resolve();
                }
            });
        }
    }
}
loadView();

jQuery.when(d).then(function() {
    /* when all elements are insert, do something */
});

I am thankful for any help!


Source: stackoverflow-javascript

Post files and input throught ajax formData

I need to post both files and input value throught one ajax call here is the code that am using actually, the upload is actually working but the problem is when i submit the form i get two rows(see pic) image here
because i am posting two ajax calls to the same php page, so if anyone can help to post only one ajajx call with the both values.
HTML

<form  method="post" id="form_upload" enctype="multipart/form-data">
  <input type="file" name="user_upload" id="mydrop" />
  <input type="hidden" id="userID" value="1" /> 
</form>

AJAX

var form_upload = $("#form_upload").serialize();
                     $.ajax({
                    data: form_upload,
                     type: 'POST',
                     url: 'upload.php',
                     success : function(data){
                        alert(data);
                     }
                });
                    var file_data = $('#mydrop').prop('files')[0];
                    var form_data = new FormData();                  
                    form_data.append('file', file_data);
                    $.ajax({
                                url: 'upload.php', 
                                dataType: 'text',
                                cache: false,
                                contentType: false,
                                processData: false,
                                data: form_data,                         
                                type: 'post',
                     });

PHP

<?php
    if(isset($_POST)){

    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "";
    $dbname = "494815";

    try {

        $dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
        $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $targetDir = "users_upload/";
        $temp = explode(".", $_FILES["file"]["name"]);
        $newfilename = round(microtime(true)) . '.' . end($temp);
        $targetFile = $targetDir.$newfilename;
        if move_uploaded_file($_FILES['file']['tmp_name'],$targetFile);
            $user_id = $_POST['user_id'];
            $stmt = $dbcon->prepare("INSERT INTO users_upload (user_id, file_name, file_date) VALUES('$user_id', '".$newfilename."','".date("Y-m-d H:i:s")."')");
            $stmt->execute();
    }
    catch(PDOException $e)
        {
            echo $e->getMessage();
        }

    $conn = null;
    }
?>


Source: stackoverflow-javascript