Stumped by JQuery $.each behavior - php

I have a php file which when called returns a simple non associative array of string values. When I request the array using the jQuery get routine I get the array I expect, but when I try to iterate it , instead of getting the two string values, the $.each command iterates every char. I don't understand what I'm getting wrong.
My code:
<div name ="test_spot" id ="test_spot" width="200" height="400">Test</div>
<script type="text/javascript">
function getOutput(){
$.get( "data.php", function( data ) {
// This call verifies the the array is what I would expect.
// ["one","two"]. Then I comment this out and run the code below.
//$( "#test_spot" ).html( data);
$.each(data, function(index, value){
// This outputs each char instead of each string each on its own line in the div.
// [
// "
// o
// n
// e etc
$('#test_spot').append($('<p>').text(value));
});
});
}
</script>
<button onClick="getOutput()" style="height: 60px; width:100px;" >Test</button>
Thanks for the help.

You are expecting an object but are getting back a JSON string. When you pass that to .each it iterates over the characters in the string.
Try specifying the dataType as json like this:
$.get( "data.php", function( data ) {
$.each(data, function(index, value){
$('#test_spot').append($('<p>').text(value));
});
}, "json" );
Or, like charlietfl points out, simply use
$.getJSON( "data. php", function( data ) {
$.each(data, function(index, value){
$('#test_spot').append($('<p>').text(value));
});
});
If that still doesnt work, Id look at the output and make sure that it is valid JSON.

Related

How can I get information from MySQL with Ajax?

So i am trying to learn Ajax with jQuery, to retrieve some information. At the moment, I have problem to get the information. My code is very simple at the moment, just because I want to learn how it works. This is my HTML code.
<h2>Hello world</h2>
<p id="response"></p>
My jQuery code:
$(function(){
$('h2').on('click', function() {
$.ajax({
url: "ajax.php",
type: "get",
datatype: "json",
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
error: function(data){
console.log("tjohejsan");
}
})
});
});
So when I click on h2 it should retrieve data. What I want is to make a call from my database to get information about the users.
So my php code looks like this:
$sql = "SELECT * FROM moment2";
$result = mysqli_query($db,$sql) or die("Fel vid SQL-fråga");
$array = array();
while($row = $result->fetch_assoc())
{
$array[] = $row;
}
echo json_encode($array);
At this point, this is where it fails. I don't know really where the problem is. Because I want an associative array.
I would appreciate it if you could assist me, because as I mentioned, I don't really know how to solve it from here.
Thanks in advance!
EDIT: I realised I had a typo while writing this. changing data['name'] to key['name']
You have issue in the jquery each function. Replace the success function as
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
It is because jquery each function has key and value as argument, so only replace "data" by "key" in your this line: $("#response").html(data['name'])
There are a couple places that you are going to run into trouble with this. Here is a JSFiddle for you to reference with my tips below:
https://jsfiddle.net/MrProvolone/zgw9ymv3/2/
There are a few things to consider...
1). Your returned data needs to be converted using parseJSON(), which is a built in jQuery function. This will convert your JSON string into a JavaScript object.
2). When you are looping through your object, you need to include the number (i) that you are trying to access
3). Because we are making a new object variable, we don't need the "key" designator in your $.each() function call... so it becomes $.each(data, function(i){}); instead of $.each(data, function(i, key){});
3). When you are trying to write out your html, you must grab what is already in the container, then add your new html to it, and finally write it all back out to the container.
Here is a step by step:
Instead of:
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
}
We need to add the parsing (and remove the "key" variable per #3 above) so it becomes this:
success: function(data){
var parsed = jQuery.parseJSON(data);
$.each(data, function(i){
$("#response").html(key['name']);
});
}
Now we have a new variable to work off of (parsed) so we need to change both the $.each line, and the .html() line to make sure it uses that new variable....
So this:
$.each(data, function(i, key){
$("#response").html(key['name']);
});
Becomes this:
$.each(parsed, function(i){
$("#response").html(parsed['name']);
});
But that still won't work. We are looping through the object, so when we try to access a value, we have to specify which element in the object we are trying to get to. So anywhere in your loop that looks like this:
parsed['keyname']
becomes this:
parsed[i]['keyname']
So now we have:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
At this point you should be getting some html in your container. However, you will notice that you are only getting the value of the last row of your data. That is because you are overwriting ALL of your html in the container in each loop, instead of adding to what is already there. We need to make a new variable to fix this. So this:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
Becomes this:
$.each(parsed, function(i){
var oldhtml = $("#response").html();
$("#response").html(oldhtml + '<br>' + parsed[i]['name']);
});
Now you will see each result, with a html line break between each one.
Hope this helps!
In your js, on the success callback, you are using the wrong data, and not appending the data retrieved to the html Tag
Here is an essai
success: function(data){
if(typeof data != "object"){
data = JSON.parse(data);
}
$.each(data, function(i, key){
$("#response").append(key['name'])
});
}

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

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

I'm trying to send a Get request by ajax and output json data that is returned by server in html.
But, I got this error.
Uncaught TypeError: Cannot use 'in' operator to search for '324' in
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
This is my code that sends a Get request to php file by ajax.
When I use $.each method, it get the error that I showed in the above.
parentCat.on('change', function(e){
parentCatId = $(this).val();
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
}
)
})
This is my PHP code that returns query result in json format.
public function actionAjax(){
$parentCatId=$_GET['parentCatId'];
$catData = Category::getTargetCategoryData($parentCatId);
echo CJSON::encode($catData);
Yii::app()->end();
}
json data outputted by this php is like this.
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
How can this problem be fixed?
You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
},
'json'
);
You can also use $.parseJSON(data) that will explicit convert a string thats come from a PHP script to a real JSON array.
If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.
I fixed a similar error by adding the json dataType like so:
$.ajax({
type: "POST",
url: "someUrl",
dataType: "json",
data: {
varname1 : "varvalue1",
varname2 : "varvalue2"
},
success: function (data) {
$.each(data, function (varname, varvalue){
...
});
}
});
And in my controller I had to use double quotes around any strings like so (note: they have to be escaped in java):
#RequestMapping(value = "/someUrl", method=RequestMethod.POST)
#ResponseBody
public String getJsonData(#RequestBody String parameters) {
// parameters = varname1=varvalue1&varname2=varvalue2
String exampleData = "{\"somename1\":\"somevalue1\",\"somename2\":\"somevalue2\"}";
return exampleData;
}
So, you could try using double quotes around your numbers if they are being used as strings (and remove that last comma):
[{"id":"50","name":"SEO"},{"id":"22","name":"LPO"}]
Use getJSON
$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
});
Detail look here http://api.jquery.com/jQuery.getJSON/
In my case, I forgot to tell the type controller that the response is a JSON object.
response.setContentType("application/json");

json jquery issue

i am using this to get informations from ajax jquery in json formate but it give me error
like this 0 =[object object]
$.getJSON("ajax_files/getSingleRow.php?id="+id+"&type="+type, function(json){
$.each(json, function(key, val) {
//$("#"+key).val(val);
alert(key+'='+val);
});
});
here is my josn string
[{"id":"1","ref":"RH-R-1","name":"","description_demo":"this is desc test"}]
Thanks all...here is how my json develops
while($rw = $oAppl->row($res))
{
$return[]=array('id'=>$rw['id'],
'ref'=>$rw['ref'],
'name'=>$rw['name'],
'description_demo'=>$rw['description_demo']);
}
header('Content-type: application/json');
echo json_encode($return);
The JSON text consists of an array containing an object.
When you loop over it, you get the first key of the array (0) and then the string serialisation of the object ([Object object]). Then it stops because there is only one entry in the array.
This is not an error. It is expected behaviour given the data you are inputting.
Possibly you want to loop over the object instead, in which case:
var ob = json[0];
$.each(ob, function(key, val) {
That isn't an error, strictly, it's an object. It might contain an error, who knows. But the thing itself is a thing waiting to be accessed (i.e., the value of val) and there's nothing inherently erroneous with it.
Try accessing the members, output the id, name, etc, instead of just dumping the thing in an alert.
Try this:
$.getJSON("ajax_files/getSingleRow.php?id=" + id + "&type=" + type, function (json) {
$.each(json, function (key, val) {
// This will only give you the 'ref' value
alert(key + '=' + val.ref);
// To loop through all the values
$.each(val, function (key2, data) {
alert(key2 + ": " + data);
});
});
});
DEMO HERE
Your JSON string is wrapped inside an array. [ {} ] Leave the "[" and "]" out.
Read the propery value of your JSON collection item.
$.each(json, function(key, item) {
alert(key+'='+item.id);
alert(key+'='+item.ref);
alert(key+'='+item.description_demo);
});
This should work fine assuming you have no other script errors in your page.
Working sample : http://jsfiddle.net/a4Efx/4/

Categories