jquery each json variable bug - php

I have a strange bug. When I try to run my code:
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
});
alert(firstJson);
The alert I get is: "undefined".
Why did I get this instead of getting 9?
What am I missing here?
(the each loop runs without issue and there are values in the JSON)
At the end, 9 changes to some other value.
Thanks

Async functions my friend. Your alert is being called before your .getJSON request has been finished. You'll need to use a callback function to get the correct alert.

Because when you call alert(firstJson) the asynchronous $.getJSON call has not yet completed, so firstJson has no value associated with it. If you move your alert into the $.each function or after the $.each, and at the end of $.getJSON, it will have a value.

The variable doesnt have a value when alert is called. You'll have to wait getJSON is over, using done().
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
}).done(function() {
alert(firstJson);
});
References:
done()
$.getJSON

Related

Json parsing the right way when you have a single value on it

I have a jquery function that sends some data to a method and receives a simple json from the php (the json returns the data sent through get).
$("#filter").submit(function() {
$.ajax({
data:$("form").serialize(),
type: $(this).attr("get"),
url:"get.php",
success: function(response){
$("#rez").html(response);
}
});
return false;
});
This is the json I get
{"list1":["bike","car","bus"],"list2":["1 seat","4 seas","10 seats"],"list3":["cheap","medium","expensive"],"list4":["green energy","bio","petrol"]}
I tried to iterate through it like this:
$.each(response, function(index, val)
{
alert(response[index]);
});
Also, tried this:
alert(val);
How can I iterate through it and make a simple alert?
The goal is to append each item to the "#rez" paragraph. But for now, I just want to iterate through the json and can't figure it out.
ALSO!
I have another json like this:["first val","second val"] how do I iterate this? Tried the above methods and none worked.
Before you start to loop you have to parse the JSON string into an Object and in this case you can do it using something like this:
var obj = JSON && JSON.parse(response) || $.parseJSON(response);
$.each(obj, function(index, val) {
// ...
});
If you don't provide the data type like dataType:"json" in your ajax params object then you have to explicitly parse the string to an object. Read more abour $.parseJSON here.
I had similar issues and used this:
for (var key in someObject) {
if (someObject.hasOwnProperty(key)) {
var something = someObject[key];
console.log(something)
}
}
Basically using "for"-loop here.

Using $.each in AJAX Success Callback

I have the following console.log(data):
[{"optionPropertyID":"287","optionID":"106","optionBedrooms":"2","optionSleeps":"1","optionDescription":"1"},{"optionPropertyID":"287","optionID":"105","optionBedrooms":"2","optionSleeps":"1","optionDescription":"1"}]
I am trying to use this data in a $.each function inside my AJAX success callback but it continually errors out on me:
success:function(data){
alert(data);
console.log(data);
$.each(data, function(){
alert("ID: " + this.optionID);
});
},
I receive the following error:
Uncaught TypeError: Cannot use 'in' operator ...
In doing some research on the error I need to use $.getJSON ? But I am using an $.ajax call to get this data in the first place ... little confused ..
I just want to iterate through this returned data and create fields for each piece of data.
input type="text" value="'+this.optionID+'"
Im just trying to alert the data back currently to ensure it is looping through.
You need to add the option:
dataType: "json",
to the $.ajax call. This tells it to parse the JSON automatically.
Alternatively, the server script could use
header("Content-type: application/json");
Because it is raw text. data in callback is always raw text when received.
You must make Object from it to use with $.each. You can do this with jQuery.parseJSON()
success:function(data){
var dataObject = $.parseJSON(data);
$.each(dataObject, function(){
alert("ID: " + this.optionID);
});
},
if your returning an object in other way around please try below code. this works for me. hopes this help.
success : function (data) {
$.each(data, function( index, value ) {
var sampleId = value.optionPropertyID;
...
});
}

Ajax jQuery post troubles

I am having trouble with a bit of code that uses the ajax $.post function to send a name to a php file which then does some stuff with it. I believe the issue to be in the ajax code, because I have found that the posted value never makes it to the $_POST array (i.e. the $_POST array is not set). However, I do not think that there are any syntactical mistakes on either end, so I am confused as to why it does not work.
Here's the jQuery.
if ($(e.target).hasClass('shootNames')) {
var shootName = $(e.target).attr('id');
var par = $('#' + shootName).parent().attr("id");
$.post("displayImages.php", {shoot: shootName}); //the information I would like to send
$('#' + par).load("displayImages.php").off('click', $('#' + par));
}//end if hasClass
And the relevant bit of php.
if (isset($_POST['shoot'])) {
$shootname = $_POST['shoot'][0]; //pick out just the first member of the $_POST array
$filepath = "images/u/$foo/$shootname";
$f->FilesAsImages($filepath);
}//end if
Thanks for any help.
You're hitting displayImages.php once in your $.post call and there it should return your image, but you don't have a success handler in there, so it does nothing with the result. You're then hitting displayImages.php again with .load and not passing it anything, so it does nothing as expected. Adding a success handler to your $.post call and doing the work in there, will do what you want.
See the $.post documentation for more: http://api.jquery.com/jquery.post/
Sample code:
if ($(e.target).hasClass('shootNames')) {
var shootName = $(e.target).attr('id');
var par = $('#' + shootName).parent().attr("id");
$.post("displayImages.php", {
shoot: shootName
}, function(data, textStatus, jqXHR) {
// this is the success function and the 3 arguments it gives you, remove the 2nd/3rd if you don't use them
$('#' + par).html(data).off('click', $('#' + par));
});
}
Try change from this
$.post("displayImages.php", {shoot: shootName}); //the information I would like to send
to this
$.post("displayImages.php", {'shoot[]': shootName}); //the information I would like to send
Source :
http://api.jquery.com/jquery.post/

Pass a variable from a get query in javascript

I am trying to pass the value of a parameter outside a $.get jQuery in javascript. I read that I should somehow do that in synchronous mode but I couldn't find a solution.
Here is my code:
var flag;
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
flag=data;
});
document.write(flag);
where I get undefined as a result.
Thanks!
write it inside the callback function
try this
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
//this is the callback function and runs when get gets completed
flag=data;
document.write(flag);
});

Get Session value based on ajax success

I have a PHP page that uses a jQuery ajax call.
After I execute my AJAX and return a value on success, I need to use this value to pull an item from a PHP array, stored in session and update my SPAN with the new set.
Here's what I've got so far. I tested and I do return correct data value. I guess my syntax in jQuery is off, because my original span fades out, but nothing comes back.
JS:
$.ajax({
...
},
success: function(data){
var nextItem = <?php echo $_SESSION['items'][data]->desc; ?>
$('.x').fadeOut();
$('.x').attr(id, data);
$('.x').text(nextItem).fadeIn();
});
HTML:
<span id="'.$_SESSION['items'][0]->id.'" class="x">'.$_SESSION['items'][0]->desc.'</span>
You should return the session variable in the AJAX call. Execute the PHP code to get the session variable on the URL your AJAX call is hitting. The response of the AJAX call (in this case the 'data' variable in your success function) will be the result of:
<?php echo $_SESSION['items'][data]->desc; ?>
So no PHP code will be in your JS.
If you need to return multiple values, then you might consider using JSON. Your AJAX processing page might be like:
$result = array('id' => $id, 'session' => $_SESSION['items'][$id]->desc);
echo json_encode($result);
Your JS might look like this:
$("#getJSON").click(function() {
$.ajax({
...
success: function(data) {
$obj = $.parseJSON(data);
console.log($obj[0].id, $obj[0].session);
}
});
});​

Categories