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
Related
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
},
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"
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/
I do something like this in my PHP AJAX:
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
print json_encode($rows);
My calling JavaScript code is like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
//$("input[type=button]").click(function()
{
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
if(name=='' || problem_blurb == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
How can I transfer the encoded JSON back to the jQuery call, decode it, and output that data? And would it be better to have just looped through the data myself and made the JSON code by concatinating the string together?
Thanks!!
set the dataType:'json' so you dont need to parse the json
$.ajax({
type: "POST",
dataType:'json', <----
url: "/problems/add_problem.php", <---- here you call the php file
data: dataString,
success: function(data) <--- here the data sent by php is receieved
{
// data will contain the decoded json sent by server
// you can do data.property that depends upon how the json is structured
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
add_problem.php
$name=$_POST['problem_name']; // get the name here
$desc=$_POST['problem_blurb']; //get the description here
$rows = array();
//fetch data from DB
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
print json_encode($rows); //json encode it and send back to ajax success handler
//or
//echo json_encode($rows);
jQuery.getJSON and $.ajax have some parameters, that are passed as per need. "data : JSON" expects output to be in json format. And when you need output, you need to pass a variable in success handler. i.e.
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: JSON, `datastring is replaced by JSON datatype`
success: function(data) `data is json object that will contain the jsonencoded output returned from add_problem.php`
{
for(var i in data)
{
console.log(data[i]) `returns the data at i'th index.`
}
}
});
Just do it in your callback function
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: dataString,
success: function( data )
{
foreach( var i in data )
// do something
}
});
It's better to json encode it on the server side because it's easier to work with json on the client side.
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]);
}