PHP to jQuery - catching the json - php

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
},

Related

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"

How to get JSON vars from PHP script

I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->​
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)

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

parse json sent by php using jquery

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]);
}

Categories