I have a javascript that sends an array through AJAX to a server side PHP script.
I am attaching relevant code snippets of my javascript AJAX function below:
$.ajax({
url: "bar2.php",
type: "POST",
data:{data:x},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(xhr, status, error) {
console.log(status);console.log(error);
},
success:function(data){
//do stuff
}
}
);
x is my array which I am sending.
I access this array in my PHP script as shown below:
$data = $_REQUEST['data'];
$len = $data.length;
$x=format_array($data);
function format_array($data){
return "'" . implode("', '", $data) . "'";
}
$myquery = "
select state,count(device_id) as c_num from base_data where state
IN($x)group by state order by c_num DESC limit 10;
";
$query = mysql_query($myquery);
But when I run it I get the error:
Warning: implode(): Invalid arguments passed in **** on line 16
Please help. I have spent an hour on this and am not able to figure it out. Am I sending the data in the correct way?
Any pointers would be appreciated.
You need to convert your array to JSON then send it to PHP (server side):
$.ajax({
url: "bar2.php",
type: "POST",
data: {data: JSON.stringify(x)},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(xhr, status, error) {
console.log(status);console.log(error);
},
success:function(data){
//do stuff
}
});
PHP:
$data = json_decode($_REQUEST['data']);
$len = count($data);
//.....
//.....
Remove contentType: "application/json; charset=utf-8", and you will receive as array of form encoded data (application/x-www-form-urlencoded) which is $.ajax default
Also use count() instead of length in php
Related
i want to send a json data to my php but there is no response when i access it to my php.
this is my ajax request
var project = {project:"A"};
var dataPost = JSON.stringify(project);
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}
});
});
and this is my php where i process the request and return back the data to test
<?php header("Content-Type: application/json; charset=UTF-8");
$objProject = json_decode($_GET["myData"]);
echo json_encode($objProject->project); ?>
i'm new to ajax so please i need your help
you don't need to add the content type on your ajax since you're not actually sending json to the server.
$.ajax({
url: 'fetchDate.php',
data: {myData: project},
type: 'POST',
datatype:'json',
// contentType: "application/json",
success: function(data, status, jqXHR) {
console.log(data,status,jqXHR);
alert(JSON.stringify(data));
}
});
no need to stringify project object,
in your php just encode it to json
<?php header("Content-Type: application/json; charset=UTF-8");
$obj = $_POST['myData'];
echo json_encode($obj); ?>
you should get json string on alert
Please try change
$objProject = json_decode($_GET["myData"]);
to
$objProject = json_decode($_POST["myData"]);
because ajax type : 'POST'
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}
I'm trying to send data to my local DB server but I keep getting 400 Bad request error when I try to send it.
var studentEmail = "ali#gmail.com";
var dataString = '&questionNumber='+ temp + '&answer='+ value + '&email='+ studentEmail;
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(dataString),
processData: false,
contentType: "application/json; charset=utf-8"
});
and this is the php file
<?php
$connection = mysql_connect("127.0.0.1", "root", "root"); // Establishing Connection with Server..
$db = mysql_select_db("db", $connection); // Selecting Database
//Fetching Values from URL
$questionNumber=$_POST['questionNumber'];
$answer=$_POST['answer'];
$email=$_POST['email'];
//Insert query
$query = mysql_query("INSERT INTO answers (questionNumber,studentAnswer,studentEmail) VALUES ($questionNumber,$answer,$email)");
echo "succesfully posted";
mysql_close($connection); // Connection Closed
?>
can anyone see what I'm doing wrong?
Thanks in advance!
JSON.stringify() method is used to turn a javascript object into json string.
So dataString variable must be a javascript object:
var data ={questionNumber:temp ,answer: value ,email:studentEmail};
AJAX
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8"
});
if you change the post to get you have to replace $_POST with $_GET into your php file.
There is an easier way to pass data that will work correctly for both POST and GET requests
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: {questionNumber:temp, answer:value, email: studentEmail},
processData: false,
});
Now jQuery does all the hard work and converts the object full of data to whatever format is required for a POST or GET request
You can send the ajax request this way:
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: ({'questionNumber':temp,'answer':value, 'email':studentEmail }),
processData: false,
contentType: "application/json; charset=utf-8"
});
Also the PHP file needs to return a json string as well.
echo "succesfully posted";
is no valid json answer.
Return something like this:
$arr = array('success' => true, 'answer' => "succesfully posted");
echo json_encode($arr);
See also here: http://php.net/manual/de/function.json-encode.php
You should validate the input data, before inserting into the database.
Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);
I need to send some data stored in IndexedDB to server for some back-end manipulation. The needed data is fetched to a variable payLoad in javascript using JSON.stringify().
payLoad = "[{"synch":0,"id":-1,"name":"Tester","email":"test#example.com","created":"2014-08-20T07:56:44.201Z"}]";
$.ajax({
type: "POST",
url: "process.php",
data: payLoad, // NOTE CHANGE HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert('error');
}
});
Can I parse this JSON data to a PHP class?
This way, you're just sending JSON raw in the body. Try this:
$data = json_decode(file_get_contents('php://input'));
If, on the other hand, you send data with this:
data: { data: payLoad },
Then you can simply do
$data = json_decode($_POST['data']);
I've got a game which refreshes info every 10 seconds from a MySQL database. There will be a JS function which is called each time this happens. I can't get the success function to execute, and I have no idea why. No errors on the console, either.
Javascript:
function refreshStats() {
console.log("number 1");
$.ajax({
url: "refreshData.php",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType : 'json',
data: { },
cache: false,
async: true,
success: function (msg) {
if(msg){
console.log("number 2");
var arr = JSON.parse(msg);
document.getElementById("interface_stats").innerHTML =
"Fatigue: " + arr[0];
}
}
});
}
PHP:
<?php
$username = $_POST['user'];
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","redacted","redacted");
if (!$con)
{
die('SQL error! Aborting: ' . mysql_error($con));
}
$db = mysql_select_db("aftertheend",$con) or die("Database error! Aborting. Inform the admin.");
$query = "SELECT fatigue, food, water, radiation, condition FROM users WHERE username='TheMightyThor'";
$result = mysql_query($query, $con);
$data = mysql_fetch_row($result);
$stats = [
"fatigue" => $data[0],
"food" => $data[1],
"water" => $data[2],
"radiation" => $data[3],
"condition" => $data[4]
];
echo json_encode($stats);
?>
I think your PHP is returning an error, rather than the JSON you are expecting. Since you have dataType: 'json', jQuery attempts to parse the response, but fails. When that happens, jQuery does not call the success callback.
If you can, use Firebug to see what is being returned by the ajax call. Another way would be to temporarily change to dataType: 'html' and then change your success callback to:
success: function(msg) { alert(msg); }
Hopefully when you see the message being returned, it will help identify the problem. One thing you should do though, is add code to handle the cases where the query fails to execute and where no row is fetched from the database. You could add the following code to the PHP file:
$result = mysql_query($query, $con);
if (!$result) {
die('Could not run query: ' . mysql_error($con));
}
if (mysql_num_rows($result) < 1) {
echo 'null';
exit;
}
$data = mysql_fetch_row($result);
There are also a few issues with the Ajax call though:
(1) You are specifying contentType: "application/json; charset=utf-8", but then you are not sending JSON. You should do something like this:
data: JSON.stringify({}),
But if you do this, you cannot get the data on the server using the $_POST function. Therefore, you might want to get rid of the contentType setting instead. See this SO answer for more information.
(2) When you specify dataType: 'json', JQuery will parse the response to an object before calling the success callback, so the msg parameter should already be an object. Therefore, you should not call JSON.parse(msg).
(3) You are returning an associative array from the PHP file. That will be converted to a JavaScript object, not an array.
I think you should try the following:
$.ajax('refreshData.php', {
type: 'post',
dataType: 'json',
data: { },
cache: false,
success: function (data) {
if (data) {
$('#interface_stats').html('Fatigue: ' + data.fatigue);
}
}
});