parse json sent by php using jquery - php

my question may be the duplicate of many questions but i have tried all my options but couldn't get to parse the json that i receive via an Ajax request
hi,
so im getting this json response as a result of Ajax call
{
"audi": [
"100",
"200",
"80",
"90",
"a3",
"a4",
"a6",
"a8"
]
}
this is the json i am receiving following is my one of the attempted options
var obj = JSON.parse(html);
alert("json decoded");
for(var yahoo in obj)
{
alert(obj[yahoo]); // this line gives me 100,200,80,90,...
}
any help is much appreciated ...
EDIT:
here is my ajax call
$.ajax({
url: "makemodel.php",
type: "POST",
data: {data:data},
cache: false,
async:false,
dataType:'json',
success: function (html) {
alert("success");
var obj = JSON.parse(html);
alert("json decoded");
for(var yahoo in obj)
{
alert(obj[yahoo]);
}
}//ajax success ends
});//ajax ends

If you set the dataType option of jQuery's ajax call to "json", jQuery will automatically parse the JSON code. The first argument to your success callback is already the parsed object then.
success: function (data) {
var s = 0;
for (var i = 0;i < data['audi'].length;i++) {
s += parseInt(data['audi'][i]);
}
alert("Sum of all audi prices: " + s);
}

You can also get your json data using getJSON, following is the example.
var price = 0;
$.getJSON("make_model.php", {data: data}, function(response){
$.each(response, function(key, value){
price += value['price'];
});
});
alert(price);

Maybe, this code can help you, too:
var obj = jQuery.ajax({
url: url,
async: false,
dataType: 'json'
}).responseText;
for(var yahoo in obj){
alert(obj[yahoo]);
}

Related

PHP to jQuery - catching the json

Here's what I want to do. User submits form (a single text input) and send to PHP. PHP returns this;
{"status":"true","custid":"00001","custname":"John"}
I know that it is in JSON format, but I don't know how to catch and use the value so I can us the returned values.
$(function(){
$('#icnumber-form').submit(function(){
var icno = $('#icnumber').val();
var purl = 'php/create_process.php'
$.ajax({
type : 'POST',
url : purl,
cache : false,
data : icno,
dataType: 'json',
success : function(response){
var json = $.parseJSON(response);
alert(json.message);
},
beforeSend:function(){
$('.cust-exist-view').show();
}
});
return false;
})
});
Since you set the dataType to json, the response comes back as an already parsed object, so you don't try to parse it yourself.
success : function(response){
alert(response.status);
},
You don't need to use var json = $.parseJSON(response); because jQuery automatically parse the JSON string to object . Just use it as a javascript object to access the json properties. I create a simple demo from your code. View it in jsfiddle
JS Code:
$(function () {
$('#icnumber-form').submit(function () {
//var icno = $('#icnumber').val();
var purl = '/echo/json/'
$.ajax({
type: 'POST',
url: purl,
cache: false,
data: {
json: '{"status":"true","custid":"00001","custname":"John"}',
delay: 1
},
dataType: 'json',
success: function (response) {
alert( "status:" + response.status
+ "\ncustname:"+response.custname
+ "\ncustid:"+ response.custid);
},
beforeSend: function () {
// $('.cust-exist-view').show();
}
});
return false;
})
});
SO you just need to view this part to see how to use json return :
success: function (response) {
alert( "status:" + response.status //access status
+ "\ncustname:"+response.custname //access custname
+ "\ncustid:"+ response.custid); // access custid
},

Getting JSON in PHP from jQuery .ajax()

I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: sendData,
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
Here is how I just test if the data is even being passed to PHP, it always returns back null.
<?php
$nData = json_decode($_POST['nData']);
echo json_encode($nData);
?>
What am I doing wrong?
You are sending the data as raw JSON to PHP, not as POST parameter.
There are two alternatives. The first one leaves your PHP intact:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: {
nData: sendData
},
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.
<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);
This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers.
Tell your post request that you are sending json object
contentType: "application/json"

Jquery Ajax and json

I am sending a value to mysql query throught ajax. I get output from query as array. I used echo json_encode($var);
If my array size is more than 1, my success function is not getting called. I could see the response and status code 200 in fire bug.
How should I retrieve the value in my success function ?
success: function(data){
ob = jQuery.parseJSON(data);
}
Update
my Json response from firebug
{"uid":"4",
"name":"ram\u00fcrmeg\u00f6zl\u00fcer",
"pic_big":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-prn1\/4149__3333_n.jpg"}
$.ajax({
type: "POST",
url: "x.php",
dataType: 'json',
data: y,
success: function(data){
}
})
Try the below and see if you get any alert.
if(!$.isEmptyObject(data))
{
alert (data);
var len = data.length;
for (var i = 0; i< len; i++) {
var var1 = [data[i].uid];
var var2 = [data[i].name];
var var3 = [data[i].pic_big];
}
else{alert('No data')}
Your response is already an Object, no need to parseJSON it. Just do this for getting the values:
console.log(data.uid);
console.log(data.name);
console.log(data.pic_big);
Or whatever you wanna do with those values.
You can try:
$.ajax({
type: "POST",
url: "x.php",
dataType: 'json',
data: y,
success: function(data){
$.each(data, function() {
var uid = this.uid; // etc
}
// this works alone if your response is wrapped in [ ], if not:
if(!data.length) {
var uid = data.uid;
} else { // above $.each code
}
}
jsFiddle of this here: http://jsfiddle.net/Y73xe/

Json eval not able to parse data

I have a php program where I just test some sample data. I am getting error as missing ] after element list. How can I read this?
$dataDetailsList = array();
array_push($dataDetailsList, array('a' =>'1','b' =>'2','c' =>'3','d' =>'4','e' =>'5'));
echo json_encode(array("DataDetailsList"=>$dataDetailsList));
Then in my jQuery processor I am doing like this.
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = eval(" (" + data + ") ");
},
cache: false
});
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = data;
},
cache: false,
dataType: 'json' //data type that it will return
});
}
Don't use eval is evil.
Instead of this use:
JSON.parse(data); // not supported in IE7 and below
I think you need to try
dataType: 'json'
That is,
$.ajax({
url: 'live-server-data.php',
dataType: 'json',
success: function(data) {
var jsonData = data;
console.log(jsonData);
$.each(jsonData.DataDetailsList, function(key, val) {
var key = Object.keys(val)[0],
value = val[key];
console.log(key); // output: a, b, c ...
console.log(value); // output: 1, 2, 3,...
// alternative
for(var key in val) {
console.log(key);
console.log(val[key]);
}
});
},
cache: false
})
You should just set the dataType to json and jQuery will do the trick for you..
$.ajax({
url: 'live-server-data.php',
dataType: 'json', //Added dataType json
success: function(data) {
//Now data is a javascript object (JSON)
},
cache: false
});

Ajax Response Json Print result in table or div array

I have an ajax call to a php file that encodes the array into a json array/object. What I am trying to do is to print the json response into a table format or an array of
div's. I am stuck on how to handle the response on ajax success. Here is my ajax..
<script>
$(document).ready(function(){
$("#adapter").keyup(function()
{
var adapter = $(this).val();
var dataString = 'searchword='+ adapter +'&format=json' ;
if(adapter=='' || adapter < 2 )
{
$("#display3").hide('');
}
else
{
$.ajax({
type: "POST",
url: "ajax/phpfile",
data: dataString,
cache: false,
success: function(data)
{
var myObj = data;
///NOT how to print the result and decode in html or php///
}
});
}return false;
});
});
</script>
Here is the json response back from the server. I can alert the whole json response, so I know it is working on the ajax side...
{"Result":[{"ptos":{"PTOMasterID":"1","PTOMasterPart":"828B-U6805-L1CX","PTOSeriesUniqueID":"22","PTOPrice":"2715.78","PTOSeries":"82","PTOMounting":"8B","PTOTransmission":"U68","PTOSpeed":"05","PTOShifter":"L","PTOAssemblyID":"1","PTOShaftID":"C","PTOSpecialFeature":"X","PTODate":"2011-11-30 17:28:10"}},{"ptos":{"PTOMasterID":"2","PTOMasterPart":"828B-U6805-L3CX","PTOSeriesUniqueID":"22","PTOPrice":"2715.78","PTOSeries":"82","PTOMounting":"8B","PTOTransmission":"U68","PTOSpeed":"05","PTOShifter":"L","PTOAssemblyID":"3","PTOShaftID":"C","PTOSpecialFeature":"X","PTODate":"2011-11-30 17:28:10"}]}
$(document).ready(function(){
$("#adapter").keyup(function()
{
var adapter = $(this).val();
var dataString = 'searchword='+ adapter +'&format=json' ;
if(adapter=='' || adapter < 2 )
{
$("#display3").hide('');
}
else
{
$.ajax({
type: "POST",
dataType: "json", //set this to json
url: "ajax/phpfile",
data: dataString,
cache: false,
success: function(data)
{
var myObj = data;
///NOT how to print the result and decode in html or php///
console.log(myObj); //to see the object
}
});
}return false;
});
});
Alternatively you could use JSON2.js like so
JSON.parse(text, reviver)
JSON 2 GITHUB
You need to declare a dataType: "JSON" if you're going to return JSON data from an ajax call. Then it's just var pto_id = data.ptos.PTOMasterID and you can do a $(object).html(pto_id); to put in the value. Hope that answers the questions you were looking for.
Interesting question-- I found this online. It should be able to iterate over all the objects and all the properties of the objects.
http://www.openjs.com/scripts/others/dump_function_php_print_r.php

Categories