Jquery Ajax and json - php

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/

Related

How to pass array back to PHP using Ajax [duplicate]

Is it possible to work with a response from AJAX request in PHP? I am not really a JS dev so i am polling my hair out with this one.
I have sort of hacked this together:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var child_id = $('#child_id');
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
dataType: 'html',
success: function(html) {
alert(html);
},
});
return false;
});
The function appears to work ok, it gives me an alert with the correct data.
{"payments":[{"id":"19","child_id":"21","club":"Breakfast Club","term":"Half Term 3","amount":"15.00","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:32","updated_at":"2015-02-11 12:16:32","starting_debt":"0","debt_start_date":"2015-01-05"},{"id":"20","child_id":"21","club":"After School Club","term":"Half Term 3","amount":"11.50","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:49","updated_at":"2015-02-11 12:16:49","starting_debt":"0","debt_start_date":"2015-01-05"}]}
I need to be able output this to the user so that it is readable. A lot of guides I find describe replacing data but as it stands there is no data until a child_id is selected.. i then want it show the above data in a readable way.
I have no idea how to start working with the data in my view file(php).
Thanks
[EDIT]updated with working code:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var response = "";
var child_id = $('#child_id').val();
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
success: function(response) {
var json_obj = $.parseJSON(response);
var output = "<ul>";
for (i=0; i < json_obj.payments.length; i++)
{
var payment = json_obj.payments[i];
var date = moment(payment.pdate).format('Do MMM YYYY');
output += "<li>£" + payment.amount + " - " + date + " (" + payment.club + ")</li>";
}
output += "</ul>";
$('.history-section').html(output);
},
dataType: "html"
});
});
Do like this.
var data = $.parseJSON("your_json");
var output= "<ul>";
for (i=0; i < data.payments.length; i++){
output += "<li>" + data.payments[i].id + ", " + data.payments[i].child_id + "</li>";
}
output += "</ul>";
use
dataType: 'json',
instead
dataType: 'html',
and then use each to fetch the record from response in success function
Use $.parseJSON() For Convert Json Format Data To Array
Right code at sucess of ajax..
Like,
var data = $.parseJSON(html);
data in you get array format of responce
You need to use json_encode() in your php file to send the data back as an array
For example;
$myarray = array("data1"=>"value1","data2"=>"value2");
echo json_encode($myarray);
You can then access the data separately in the js file like this;
success: function(html) {
alert(html.data1);
alert(html.data2);
},
You also need to change the dataType to 'json'
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').catcomplete({
delay: 0,
source: function(request, response) {
$.ajax({
url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>',
type: 'POST',
dataType: 'json',
data: 'filter_name=' + encodeURIComponent(request.term),
success: function(data) {
response($.map(data, function(item) {
return {
category: item.attribute_group,
label: item.name,
value: item.attribute_id
}
}));
}
});
},
select: function(event, ui) {
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').attr('value', ui.item.label);
$('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').attr('value', ui.item.value);
return false;
}
});
You Can map your json something like this

In jquery get value from array by key name

I have One Program where i get information contains in array and i want to aceess it with using key.
Is there any Way for this ?
Here are code example :
jQuery("#sl_name").change(function(){
var id = this.value;
jQuery.ajax({
url : 'insert.php',
type:'post',
data:{'action': 'getById','id':id},
success : function(data){
alert(data);
}
});
});
Here variable Data contain array of user i need to access by key value like in php we can get.
If you are return print_r than use json_encode method.
Thanks In Adavance.
don't use alert to debug objects, you will always get [Object object], use console.log instead:
jQuery("#sl_name").change(function () {
var id = this.value;
jQuery.ajax({
url: 'insert.php',
type: 'post',
data: {
'action': 'getById',
'id': id
},
success: function (data) {
console.log(data);
//if data is not yet a json object
data = JSON.parse(data);
//To access by key/prop
console.log(data.username);
//if data is an array:
for (var i = 0; i < data.length; i++) console.log(data[i]);
}
});
});

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