Bhups Bhups - 19 days ago 6
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.

index.php

<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>

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


javascript -- main.js

var objArray = []; //Array of questions

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

$.ajax({
type:'post',
url: 'upload.php',
data: { jsonData : jsonArray},
success: function(data){
console.log("success!");
}
});

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


upload.php

<?php

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);
}

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

$conn->close();

}else {echo "unsecure connection";}
?>


objArray looks like this:

[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]


upload.php outputs "data not received"

Answer

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
    e.preventDefault();

    // 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.

Comments