I am trying to decode JSON in php I sended using an ajax call in javascript (jquery).
The javascript code:
var editSchedule_data = {
'action' : 'editSchedule',
'eventid' : $('#eventid').val(),
'pixels_per_minute' :$('#pixels_per_minute').val(),
artists: {
artist: []
}
}
$('.artist').each(function(index) {
var id=$(this).attr('id');
id=id.split('_');
editSchedule_data.artists.artist.push({
'artistid' : id[0],
'stageid' : id[1],
'left' : $(this).offset().left-$('.artists').offset().left,
'width' : $(this).width()
});
});
$.ajax({
type : "POST",
url : "callback.php",
data : editSchedule_data,
dataType : "json",
async : true,
success : function(json) {
if(json.success) {
showSucces(json.message);
}
else{
showError(json.message);
}
},
error: function(error){
alert("An error occurred: "+error.message);
}
});
The php-code:
$clean = sanitize($_POST);
echo(json_encode($clean['artists']),
json_last_error());
echo(json_decode($clean['artists']),
json_last_error());
My output:
encode:
{"artist":[{"artistid":"4","stageid":"3","left":"360","width":"240"},{"artistid":"3","stageid":"4","left":"120","width":"240"},{"artistid":"1","stageid":"5","left":"120","width":"180"},{"artistid":"2","stageid":"5","left":"300","width":"120"},{"artistid":"5","stageid":"6","left":"480","width":"120"}]}
0
decode:
0
Can someone tell me how to get the decode function to work?
Why are you trying to use json_decode there? You already have the data as array in $_POST.That's why json_decode fails and retuns NULL...it expects a properly formated string and you are passing it an array.
If the dataType : "json" parameter confuses you, it specifies the type of the data you are expecting back from the server not the type of the data you are sending.
You shoud simply process the data from $_POST, create your response , apply json_encode on it and echo the resulted string.
json_decode($clean['artists']); is giving you an object, that's why echoing it doesn't show anything. Try print_r() to see what's inside the object:
// Will show you the whole PHP object
print_r( json_decode( $clean['artists'] ) );
it is much better if you will use this. when fetching data from the database
$.getJSON("callback.php",function(json){
$('#div to update').html(json[0].databasefield); // 0 if query is only 1 result
}); // when there are many of them use for loop
on your php you should encode it using json_encode(array values);
Related
I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?
I am trying to do an ajax request to my php, but for some unknown reason it seems to fail as i don't get to the success part where I have a console.log
Can anyone please give me some hint what might be wron with this, I am stuck for too long now??
Here is how my jQuery looks :
getPending();
function getPending(){
var usernameLS = localStorage.getItem('userNameLS');
var userTypeLS = localStorage.getItem('isAdminLS');
if (userTypeLS!=1) {
console.log("inside");//i am getting here
$.ajax({
type: "POST",
dataType: 'json',
url: 'get-pending.php',
data: {
data: usernameLS //this is a string, "user2" for instance
},
success: function(data) {
console.log("Thanks!!!",data);//i never got here
},
failure: function() {
console.log("Error!");
alert(' Fail');
}
});
}
And here is my php :
<?php
$string = file_get_contents("appointments.json");
$usernameAjax = $_POST['data'];
var_dump($usernameAjax);
$json_a = json_decode($string, true);
$isPending;
foreach ($json_a as &$json_r) {
if ($usernameAjax==$json_r['userName'] && $json_r['status'] = "Pending") {
$isPending = 1;
}
else{
$isPending = 0;
}
}
var_dump($isPending);
echo $isPending; //i tried with a hardcodede 1 or 0 zero. Didn't work.
?>
Seems like your output is not correct JSON format, so client-side cant understand what was recieved.
First - remove var_dump, it breaks json format anyway;
Second - jou just output 1 or 0 - that is not correct json too; use json_encode to format reply properly;
Third - php files often contains trailing symbols after ?>, that are appends to output too and could break output format. Dont close php with ?> at all; additionally you could use die($output) instead of echo($output) to avoid any output after your data was written
Im working on some AJAX login function, making a request via PHP.
I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.
I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames
Is the data a JSON Object by itself?
Thanks!
The code below was used before and has been verified to work.
function retrieveVersion(){
var URL = RSlink + "/updates";
$.ajax({
headers : {
"Content-Type" : "application/json; charset=UTF-8",
"sessionid" : result
},
type : "GET",
url : vURL,
statusCode : {
0 : function() {
hideLoadingMsg();
showError(networkError, false);
},
200 : function(data) {
currentVersion = String(data.version);
updatesArray=data.updates;
});
}
}
});
Suppose you have a php file for handling ajax calls. It should be available by this url - vURL.
In this file you need to create an array.
Something like this:
$data = array('data' => array('version' => yourversion, 'updates' => yourupdates));
Then you need to convert this object into json string. You can do this using json_encode() function
echo json_encode($data);
One thing to keep in mind: You need to echo your data and only. If somewhere in your file you will have some other echo-es, the result string returning to your ajax-funtion might be broken.
I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);
I have array in json, but I want to print it in php. I get in post this :
[{"cartData":{"id":"dragged_567737","left":"255px","top":"71px"}},{"cartData":{"id":"dragged_757836","left":"43px","top":"73px"}}]
but when I use print_r($_POST) in my php file, it print me the empty array.
there is my js code:
jQuery('#save_project_data').click( function() {
var array=[];
var numItems = $('.icart').length;
$(".icart").each(function(index) {
var cart_id = $(this).attr("id");
var cart_left = $(this).css("left");
var cart_top = $(this).css("top");
var cartData = {
"id" : cart_id,
"left" : cart_left,
"top" : cart_top
};
queryStr = { "cartData" : cartData };
array.push(queryStr);
});
var postData = JSON.stringify(array);
$.ajax({
url : "modules/cart_projects/saveData.php",
type : "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data : postData,//{ 'data': '{"name":"chris"}' }
traditional: true,
success: function(){
alert("OK");
}
});
return false;
});
PHP has native support for decoding JSON with json_decode();
$data = json_decode($_POST['myJson']);
print_r($data);
The PHP $_POST array is interpreted from key value pairs, so you need to change your ajax call like below, because your code is sending the post data with no key.
data : { myJson : postData },//{ 'data': '{"name":"chris"}' }
If you change the data structure like above, you need to also remove your application/json; charset=utf-8 content type.
From the Manual:
Takes a JSON encoded string and converts it into a PHP variable.
If you're sending raw JSON-strings to PHP, $_POST will not be populated (as it needs a standard urlencoded string as submitted by POST requests to decode). You can solve this by either using postData as an object: {'json': json}, so that you get the value in $_POST['json'], or by reading the raw response:
$json_string = file_get_contents('php://input');
$struct = json_decode($json_string, true);
Try to use json_decode() function.
According to jQuery.ajax() documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
To be safe, you might be better off using the jQuery.post() method.
Finally, I suggest to give the data property an object. That way you can set an identifier for your post data.
Javascript
{
url: 'modules/cart_projects/saveData.php',
data: {
mydata: postData
}
}
PHP
$_POST['mydata'];
If you need to decode the JSON:
json_decode($_POST['mydata']);