Passing php string as json to be received by jquery - javascript

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.

As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});

Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.

As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".

Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array

Related

How to loop each JSON value after is retrieving its data through AJAX

var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/

Using jquery to parse items from a JSON response

I am using PHP and Ajax to parse some JSON. The PHP is creating the array like this.
$myObj->pid = $_POST["parentid"];
$myObj->comp = $comp;
$myObj->colour = $statuscolour;
$myJSON = json_encode($myObj);
header('Content-Type: application/json');
echo $myJSON;
I use the following jquery code
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var response = jQuery.parseJSON(JSON.stringify(msg));
console.log(response);
pid = response[0].pid;
console.log('id = ' + pid);
});
I can see the output from the first console.log as
Object {pid: "p1", comp: 20, colour: "red"}
However I cannot extract the individual variables, it gives the message
Uncaught TypeError: Cannot read property 'pid'
How can I extract the variable?
You've made this more complicated than it needs to be. msg is already an object, which you then convert to a string and back to an object with stringify and parseJSON. And then you try to use it like an array, when it is an object.
Try this:
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var pid = msg.pid;
console.log('id = ' + pid);
});
You are returning an object, not an array.
Also it makes no sense to stringify the data object and parse that string back to object again
Try
var pid = msg.pid;
console.log('id = ' + pid);
First of all, it can't imagine why it would be neccessary to first stringify, then parse the JSON response.
Second, you are trying to access response[0] as if it were an array, which it isn't. You can simply use
response.pid;
To access the object key.
As you don't need to stringify then parse the response, you can just access msg directly, so it all comes down to
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
console.log(msg.pid);
});

Ajax array only returns 1 value?

I am new to PHP and Ajax so please bear with me. I've searched around and found some answers but still am having trouble. I have an array of check box input values. If a user checks an item it is added to my array list. An example would be:
listOfPrograms = [chrome, firefox, sqlworkbench]
I want to send this array list to a PHP script on my server. My current Ajax script is as follows:
function ajaxPostToPhp(listOfPorgrams)
{
$.ajax
({
url: 'script.php',
type: 'post',
data: ("listOfPrograms" : listOfPrograms), // I believe this is where my issues lies as I do not know exactly that this is doing. I have read the PHP documentation. I tried converting to JSON and kept getting a 500 error.
success: function(data)
{
console.log(data);
}
});
}
My PHP script is as folllows:
$myArray = $_Request['listOfPrograms'];
echo $myArray;
This returns only 1 item from the array. I tried setting myArray = [] but I get an undefined index.
Thanks for your help! Sorry for such a noob question.
You need to fix a few things:
1- Javascript array:
var listOfPrograms = ['chrome', 'firefox', 'sqlworkbench'];
2- Ajax Data:
function ajaxPostToPhp(listOfPrograms)
{
myListData = {};
myListData['Programs'] = listOfPrograms;
$.ajax({
url: 'script.php',
type: 'post',
data: myListData,
success: function(data)
{
console.log(data);
}
});
}
3- Php Code:
$myArray = $_POST['Programs'];
var_dump($myArray);
You are passing an array as post parameter but they can only be strings. You should convert the array to a JSON string first. An easy function for that purpose is JSON.stringify()
var listOfPrograms = ["chrome", "firefox", "sqlworkbench"]
// I guess you need strings here
function ajaxPostToPhp(listOfPorgrams) {
$.ajax ({
url: 'script.php',
type: 'post',
// Convert listOfPrograms to a string first
data: ("listOfPrograms" : JSON.stringify(listOfPrograms)),
success: function(data) {
console.log(data);
}
});
}
jquery will kindly turn array values in ajax post data to an array for you. the issue is that in php you can't just echo an array. as a commenter stated, your php file needs to look like
$myArray = $_Request['listOfPrograms'];
echo json_encode($myArray);
also you should consider using $_POST over $_REQUEST

Removing Some Characters In A JSON Response

I have a JSON response as the follwoing, but my problem is there are some characters that is not related to the JSON response I want. So I have pass that JSON response to a JavaScript variable and look into the JSON string. That is at the bottom.
-----------JSON Response------------
{
"readyState":4,
"responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"query\":{\"start-date\":\"2014-10-01\",\"end-date\":\"2014-10-23\",\"ids\":\"ga:76546294\",\"dimensions\":\"ga:userType\",\"metrics\":[\"ga:users\"],\"start-index\":1,\"max-results\":10},\"itemsPerPage\":10,\"totalResults\":2,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"profileInfo\":{\"profileId\":\"76546294\",\"accountId\":\"289147\",\"webPropertyId\":\"UA-289147-1\",\"internalWebPropertyId\":\"456104\",\"profileName\":\"US - Institutional Investors - NP Microsite\",\"tableId\":\"ga:76546294\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:userType\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:users\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:users\":\"1110\"},\"rows\":[[\"New Visitor\",\"826\"],[\"Returning Visitor\",\"284\"]]}</string>",
"status":200,
"statusText":"OK"
}
-----------End of JSON ------------
I want to remove these characters from the beginning of the string:
`{"readyState":4,"responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>`
And I want to remove these character from the end of the string:
`</string>","status":200,"statusText":"OK"}`
So I want to remove these characters. I think a set of JavaScript String functions to be used. But I don't know how to mix them and use.
Could someone help me to solve this matter?
Thanks and regards,
Chiranthaka
UPDATE
I have used the follwoing AJAX function to send and get the JSON response back.
function setJsonSer() {
formData = {
'Email': 'clientlink#site.com',
'Password': 'password1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(JSON.stringify(data));
Load(data);
}
});
}
UPDATE 02
function setJsonSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
dataType: 'json',
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(jsonResult);
Load(data);
}
});
}
I looked at your code:
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(jsonResult);
Load(data);
}
So you want to stringify your customized result, but your result is not well parsed JSON*? If yes then:
complete: function(data) {
var responseText = data.responseText;
var responseJson = JSON.parse(responseText.match(/[{].*.[}]/));
// you can skip `JSON.parse` if you dont want to leave it as `String` type
alert(JSON.stringify(responseJson)); //or just `responseJson` if you skip `JSON.parse`
Load(JSON.stringify(responseJson));
}
This can solve your problem for a while. But I think the problem is in your backend which did not serve well parsed JSON data. My recommendation is fixing your backend system first.
*Not well parsed JSON because your result some kind of including XML type of string under JSON object.
You have to parse JSON to get stuff which is inside it (You have
done this)
You have to parse the XML to get text which is inside the XML
Here's sample code for XML parsing:
http://www.w3schools.com/xml/tryit.asp?filename=tryxml_parsertest2

split JSON data from PHP to three arrays in JavaScript

I am passing values from PHP Script to JS using JSON encode.
$arr=array('X'=>$X,'Y'=>$Y,'par'=>$par);
echo json_encode($arr);
Which produces
{"X": ["-0.9537121038646844","-0.9537121038646844","-0.9537121038646844","0.9537121038646843",""],
"Y": ["-0.9537121038646844","-0.7799936811949519","-0.5533396521383813","-0.37962122946864896",null],
"par": ["0.009811016749950838","0.005007306592216437","5.058030686503405E-4","9.451402320405391E-4",null]}
In the javascript, I used the following command
{
$.post("plot.php",param,function(data){dataType:"json";console.log(data);Var X1=data.X;});
}
But I am not able to obtain the values of X alone. I tried few suggestions from similar threads, but none of them did the trick.I need the three arrays, X,Y and Par to be used in JS.
Try this:
$.post("plot.php", param, function(data) {
console.log(data);
var X1 = data.X;
},
"json"
);
You can also use $.ajax (which is the function $.post internally calls):
{
$.ajax({
type: "POST",
url: "plot.php",
dataType: "json",
data: param,
success: function(data) {
console.log(data);
var X1=data.X;
}
});
}
If you are using php you have to specify at the last parameter of post fn that is json type:
$.post("plot.php",param, function(data){
console.log(data);
var X1=data.X;
},'json');

Categories