Jquery cannot encode json - php

i return this json from my php page but jquery cannot decode it,result is always null.
{
"City": [
{
"CityID": "1",
"CityName": "istanbul"
},
{
"CityID": "2",
"CityName": "Ankara"
}
]
}
Jquery Code:
$.getJSON("handlers/cityhandler.php", function(json){
var result = jQuery.parseJSON(json);
console.log(result[0].City.CityID);
Jquery alternate code:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json, function(i,City){
$("#selectcity").append('<option value="' + City.CityID + '">' + City.CityName + '</option>');
});

console.log(json.City[0].CityID);​

The data is already parsed when you receive it, you don't need to call $.parseJSON. Furthermore, the reason why you are getting a null pointer exception is because result[0] doesn't exist: result is an associative array, not a regular array.
$.getJSON("handlers/cityhandler.php", function(json){
console.log(json.City[0].CityID);
});
Your second attempt isn't right either; if you're trying to loop over the cities you must loop over the inner array:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json.City, function(i, val){
$("#selectcity").append('<option value="' + val.CityID + '">'
+ val.CityName + '</option>');
});
});

Your JSON output is valid JSON, so the issue is not coming from there. Are you sure that this is exactly what the jQuery handler receives?
Side note, result[0] doesn't exist! Your top element is an object and not an array!

Related

encode PHP JSON data in jquery

I am getting JSON encoded data after ajax call to PHP :
[
{
"id":"4",
"name":"Kg",
"vital_sign_list_id":"3",
"created":"2016-03-01 18:52:27",
"modiefied":"2016-03-01 18:52:27"
},
{
"id":"5",
"name":"Pound",
"vital_sign_list_id":"3",
"created":"2016-03-01 18:52:27",
"modiefied":"2016-03-01 18:52:27"
}
]
There are two datas, and I want to decode using loop and use data using jquery. How can I achieve it?
try below code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<script>
json = '[{"id":"4","name":"Kg","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}, {"id":"5","name":"Pound","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}]';
var obj = $.parseJSON( json);
$.each(obj, function(index, val){
alert(val.name);
//you can access other data by using val.id, val.created etc
});
</script>
for more detail have a look at http://api.jquery.com/jquery.parsejson/ and http://api.jquery.com/jquery.each/
You can try this way
var data = [{"id":"4","name":"Kg","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}, {"id":"5","name":"Pound","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}];
for(var i = 0 ; i < data.length; i++){
console.log("ID "+ i +": "+ data[i].id);
console.log("Name "+ i +": "+ data[i].name);
console.log("Vital "+ i +": "+ data[i].vital_sign_list_id);
}
json_encode(jsonArrVar);
use this in your json php file to encode your json data.
and in jquery parse it using json.parse or eval function.

laravel get object data from JSON response giving undefined

i'm using ajax to get data from model by controller every thing is running nice i think and when i check with console.log(response) i get
Object {buyTemps: Object}
and in side the object i found All data inside the array up to now every thing is good
ajax
$(".buy-tr").click(function(e){
var
data = {},
$row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(1)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
data={buyId:$(this).text()};
});
// $(this).find('input:radio').prop('checked', true);
$(".buy-tr").click(function(e){
var
data = {},
$row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(1)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
data={buyId:$(this).text()};
});
$.ajax({
url : "/buy/selectTable",
type : 'GET',
dataType : 'json',
data : data,
success : function(response) {
console.log(response);
$('#buyItem-table tbody').empty();
$.each(response,function(index, v){
$('#buyItem-table tbody').append(
"<tr><td>" + v.buyItemTempId
+ "</td><td>" + v.itemName
+ "</td><td>" + v.itemExpire
+ "</td><td>" + v.buyPrice
+ "</td><td>" + v.buyBox
+ "</td><td>" + v.itemPacking
+ "</td><td>" + v.buyQty
+ "</td></tr>" );
});
},
error : function(response) {
swal("error");
}
at my controller
public function selectItemTable()
{
$buyId = Input::get('buyId');
$buyTemps = DB::table('vbuytemp')->where('buyId',$buyId)->paginate(10);
return Response::json(compact('buyTemps'));
}
the consol.log(v)
Object {total: 1, per_page: 10, current_page: 1, last_page: 1, next_page_url: null…}current_page: 1data: Array[1]0: Objectbarcode: "08815408"buyBox: 30buyId: 2buyItemTempId: 2buyPrice: "2.500"buyQty: 90itemExpire: "2018-01-04"itemId: 2itemName: "Panadol Extra tab"itemPacking: 2minQty: 1roofId: 1sellingForm: 1__proto__: Objectlength: 1__proto__: Array[0]from: 1last_page: 1next_page_url: nullper_page: 10prev_page_url: nullto: 1total: 1__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()
the result all table cell fill with undefined
Your issue is that you are looping through response data at the wrong point. When you call $.each you are actually looping through all of the pagination metadata (total, per_page, etc.). The actual data you want is contained inside the data array. So just loop through that array instead and it should work.
$.each(response.data,function(index, v){
//now v.buyItemTempId and other properties exist
}

Display JSON Data in HTML using Laravel 4

Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"

jQuery/PHP ajaxForm getting JSON encoded results

I got this code for the Form:
jQuery
$('#form').ajaxForm({
beforeSend: function () {
bar.width(0);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentCompleted = percentComplete + '%';
bar.width(percentCompleted)
bar.text(percentCompleted)
console.log(percentCompleted);
///The Console logs properly.
},
complete:
//------------------------------------
//THIS IS WHERE LIES PROBLEM IS
//------------------------------------
function (xhr) {
//How do you convert the xhr to JSON?
//I tried :
var out = JSON.parse(xhr)
// and :
var out2 = $.parseJSON(xhr)
console.log('Completed1: ' + out);
console.log('Completed2: ' + out2);
},
error: function (xhr, desc, err) {
console.log(xhr)
console.debug(xhr);
console.log("Desc: " + desc + "\nErr:" + err);
}
});
The PHP is like:
$OutCollection is an Associative Array()
Firebug Console says:
Cant figure out what's really Wrong.
Any help is highly appreciated.
PHP output / response in firebug
Console.log(xhr) prints
It seems that xhf is a XMLHttpRequest object so the responseText property will have your json.
function (xhr) {
//How do you convert the xhr to JSON?
//I tried :
var out = JSON.parse(xhr.responseText)
// and :
var out2 = $.parseJSON(xhr.responseText)
console.log('Completed1: ', out);
console.log('Completed2: ', out2);
},
Solved the mystery:
Using the hint from #Musa in the comment that suggested to try the console.log(xhr),
I came up with this.
var out=$.parseJSON(xhr.responseText);
$.each(out,function(i,v){
//then:
console.log(out[i]) //to access each piece of the information.
});
However,
Somehow, both parameters of the $.each() are returning the key of the key=value pair. I somehow thought the i should be the index and the v, value of the $.each loop. So that we could do something like: v[i]. using i as an index to access the values stored in the v Array of values.
Even though, it works hackingly however.
I think you dont have that ; after that variable declaration like:
var out= JSON.parse(xhr);
var out2= $.parseJSON(xhr);
The problem here is HTTP header
We need to make the browser think the receiving data is json and then you don't need to parse the returning string to json.
Just need to add this before you echo the json encoded string:
header("Content-type: application/json");

Getting key => value from json array passed from php

I am trying to get an array from PHP and to manipulate it further using jQuery. In my PHP file i do echo json_encode($data) and when i put an alert in my response in jQuery i get:
[
{
"CustomerID": "C43242421",
"UserID": "432421421",
"Customer": "rqewrqwreeqwr",
"Add1": "rqwerqwreqwrqwrqwr",
"Add2": " ",
"Add3": " ",
"Phone": "4131231",
"Fax": "532442141",
"Contact": "reqwrqwrw",
"Email": "gfdgdsg",
"PaymentTerm": null,
"Country": "3231",
"City": "111",
"Zip": " "
}
]
, wich is a valid json array. Now what i try to do further is get the pairs as key => value as i would in an associative array in php.
$.post("templates/test.php",
{data: query,
cond: $(this).text(),
action: 'select'
},
function(res) {
alert(res) //outputs what i pasted above
$.each($.parseJSON(res), function(key, value) {
alert(key + value);
//this outputs: 0[object Object]
});
Removing the $.parseJSON in the above function gives me a invalid 'in' operand e on jquery.min.js(line 3) in Firebug error log.Can you assist me with my troubles?
Try:
var r = $.parseJSON(res);
$.each(r[0], function(key, value) {
alert(key + value);
});
The result of $.parseJSON(res) is an array, containing a single element (an object). When you iterate over that array (using $.each), value represents the entire object that's stored at the current index of the array. You'll need to iterate over that object to output its properties:
$.each($.parseJSON(res)[0], function(key, value) {
alert(key + ' = ' + value);
});
If you have an array with multiple objects inside it, this more general code should output the key-value pairs for all of them:
$.each($.parseJSON(res), function(index, arrayObject) {
$.each(arrayObject, function(key, value) {
alert(key + ' = ' + value);
});
});
res = $.parseJSON(res);
for (var i = 0; l = res.length; i < l; i++) {
data = res[i];
customer = data.Customer;
}
You have there an Array of Objects. You can iterate through the array of objects just like the code above.
You can get some kind of object from json:
function parse_json(res)
{
try{
return eval('(' + response + ')');
}
catch(e){
// invalid json
}
}
Try this:
$.getJSON('your-json-string-file.php', function (data) {
$.each(data, function(key, val) {
alert(key +'=>'+ val)
});
});
Hope this will help you

Categories