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;
...
});
}
Related
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'])
});
}
I'm developing an application which does an Ajax call to a PHP script which returns json_encode data.
The data is being returned from PHP as expected. But when trying to parse it in jquery I'm getting a console error:
Uncaught TypeError: Cannot use 'in' operator to search for '1009'
followed by a copy of my data array.
An example of the json encoded data is here:
[
{"u_id":"21747","fname":"Andy","lname":"","email":"foo#bar.com"},
{"u_id":"3748","fname":"John","lname":"","email":"foo#baz.com"},
{"u_id":"451750","fname":"Peter","lname":"","email":"someone#else.com"},
]
The jquery I'm using is as follows. The desired output is for it to display a list of people's email addresses next to a tickbox:
$(function() {
$('#myModal').on('shown.bs.modal', function() {
$(".modal-body").html("Loading...");
$.ajax({
url: "<?= $router->pathFor('/admin/ajax/find-user'); ?>",
data: {
searchInput: $('#searchInput').val()
},
method: "POST",
}).done(function(data) {
//$(".modal-body").html(data);
$.parseJSON(data);
$.each(data, function(key, value){
$(".modal-body").html('<input type="checkbox" id="' + value.u_id + '">' + value.email + "<br>");
});
});
});
});
What's wrong with this, and what does the error mean (I can't see 1009 anywhere in my data, although not sure if that's what it actually means?)
You need to parse your JSON data first:
var parsedData = $.parseJSON(data);
But if your PHP script returns the JSON with the correct Content-Type, you don't need to do that. If you ensure that the PHP script sends Content-Type: application/json, jQuery will automatically parse it before giving it to you. So that's another way to fix the problem.
Not So Sure !!
but can You try with largeJSONobject.data
LIKE
$.each(largeJSONobject.data, function(key, value){
$(".modal-body").html('' + value.email + "");
});
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");
I have an ajax call:
setStatusToActive: function(item){
$.ajax({
type: 'GET',
url: '/Yii/trackstar/index.php?r=contentManagement/sidebars/SetWidgetStatusActive/',
data: {'sid': <?php echo $this->_sidebarId->id ?>, 'widget_type': item.data('type'), 'position': item.data('position')},
success: function(data){
console.log(data);
item.data('id', data);
}
});
},
Now I am trying to figure out how to get the returned value from the php function that is called on the screen/log.
public function actionSetWidgetStatusActive(){
...
return $widgetsUsed->id;
}
After this I want to use the returned number to set the data attribute from an item.
Thanks in advance
EDIT:
The only question I got is how I can get the returned php in the console or on the screen throughout javascript (as said in the title).
You can try this: echo json_encode($widgetsUsed->id); and remove the return function.
Now if you check your console in Firebug, you will be able to see the result of your function. TO display properly in jQuery, you must use jQuery.parseJSON().
I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});
the ones you should always set are url,success and data if needed, please read The Documentation for more information.