First, I realize there are a lot of other similar posts. I have read through many, and I have still not been able to this it to work. That being said.....I have a 2 dimensional javascript object that is created dynamically. I am trying to pass it to PHP so I can save insert it into a MySQL table. It looks like the easiest way to do this is with an Ajax post. Here is my javascript:
var jsonString = JSON.stringify(TableData);
$.ajax({
type: 'POST',
url: 'submit.php',
data: jsonString,
success: function(){
alert("OK");
}
});
I always get the success alert so I don't think the problem is there. Here is my PHP file.
<?php
$servername = "localhost";
$username = "SME";
$password = "mypass";
$db = "p3";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
if (!$conn) {
die("Could not connect to database");
} else echo "hey hey";
$data = json_decode("jsonString");
print $data;
?>
I am not really sure what I am doing wrong. Both of the files are in the same folder so I don't think it's a URL problem. Any help would be appreciated.
3 Answers 3
I see the problem. In order to access the what you're passing on, you need to get it from the $_POST variable which is an array. You can iterate over that array to get what you need and insert it in to your database after doing '$data = json_decode($_POST);`
Notice that your type in AJAX is post this is the same as the form method. It might also help in your ajax if you added `dataType: "json" to your parameters.
$.ajax({
type: 'POST',
url: 'submit.php',
data: jsonString,
dataType: 'json'
success: function(){
alert("OK");
}
14 Comments
var_dump($_POST)? What does that show?var_dump($_POST) shows array(0) { }. I checked the value of my JSON.stringify variable and it has the appropriate values. One odd thing is that when I have my dataType: 'JSON' I don't get my success alert.console.log(jsonString); and it shows my array values and I get my success alert. I am not sure of a way to check if it did indeed go to my submit page other than checking the console there as well or using var_dump().So it looks like in your PHP you're not actually grabbing the posted data.
This is how I would recommend getting the data:
<?php
// Check if the posted value is not empty
if (!empty($_POST('jsonString')) {
$jsonData = json_decode($_POST('jsonString'));
}
?>
Then you can do what you need to do with the $jsonData.
Comments
The main problem was in my PHP code. Here's the answer.
$data = json_decode($_POST['denied'], true);
I was then able to insert into my MySQL table like this:
foreach($data as $user) {
$sql = "INSERT INTO deniedusers (firstname, lastname, username, email, password) values ('".$user['fname']."', '".$user['lname']."', '".$user['uname']."', '".$user['email']."', '".$user['password']."')";
I appreciate everyone's answers. Thanks!
$data = json_decode($_POST);echo / printan array ( at least in a meaningful way) tryprint_r(),var_dump()orvar_export()next time..