Bhups Bhups - 1 year ago 50
jQuery Question

cannot receive js array posted with ajax

I am trying to send form data and js array to mysql database. I am having problem with receiving js array into my php. I receive data from form but not the array. I can't find the problem.


<!doctype html>
<html lang="en">
<link rel="stylesheet" href=""><!--bootstrap-->
<script src=""></script><!--jquery-->
<script src=""></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>

<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>

javascript -- main.js

var objArray = []; //Array of questions

function upload(){
var jsonArray = JSON.stringify(objArray);

url: 'upload.php',
data: { jsonData : jsonArray},
success: function(data){

} else {
console.log("no data javascript!");



if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){

$servername = "......";
$username = "......";
$password = "......";
$dbname = ".....";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

$json = $_POST['jsonData'];
var_dump(json_decode($json, true));
echo "<script type=\"text/javascript\">
console.log('received data');
} else {
echo "data not received";


}else {echo "unsecure connection";}

objArray looks like this:


upload.php outputs "data not received"

Answer Source

Your output indicates what the problem is: You get to the part where you echo data not received but you are not sending a submit key: $_POST['submit'] is not set when called through ajax.

So you are submitting your form the "normal" way and not through ajax.

This is caused by the fact that you are not cancelling the default submit action of your button.

The best way to solve that (in my opinion...), is to remove the inline javascript - the click handler - and replace your function with:

$("form").on('submit', function(e) {
    // Cancel the default form submit

    // The rest of your function
    var jsonArray = JSON.stringify(objArray);

Note that I am catching the form submit event. You could also replace that with the button click event but that might not work correctly when a visitor uses the enter key in a form field.