I have a problem, my app have an issue when reading more than one value, when there are two it returns zero.
Example:
I get:
male:
{"name":"alexanderbb10","pic":"ico/nopic.png"}
{"name":"admin","pic":"ico/nopic.png"}
$.ajax({
type: "GET",
url: "http://p********************************/explore.php?usr="+******************+"&what="+strUser,
dataType: "json",
data: dataString,
success: function(data)
{
$('#explorediv').append('<div id="pic" data-bb-type="item" data-bb-img="' + data.pic + '" data-bb-title="' + data.name + '">' + data.name + '</div>').show('fast');
}
});
But it only shows one result.
How can i make sure it shows all results?
The server side is php
wrapper two object in an array
{male: [{"name":"alexanderbb10","pic":"ico/nopic.png"}, {"name":"admin","pic":"ico/nopic.png"}]}
var result = JSON.parse(xhr.responseText);
for (var i = 0, len = result.male.length; i < len; ++i) {
// result.male[i];
}
your is an invalid JSON:
male: {"name":"alexanderbb10","pic":"ico/nopic.png"} {"name":"admin","pic":"ico/nopic.png"}
if returned data from the ajax request is an array of object, like
[
{"name":"alexanderbb10","pic":"ico/nopic.png"}
{"name":"admin","pic":"ico/nopic.png"}
]
for show all the element inseide of the data you must cicle all the array element, try to change the success function like this:
function(data) {
for(var k in data){
$('#explorediv').append('<div id="pic" data-bb-type="item" data-bb-img="' + data[k].pic + '" data-bb-title="' + data.name + '">' + data[k].name + '</div>').show('fast');
}
}
Related
This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I am creating a small domain availability checker. For that I will parse the desired domain into a form, and submit that to a PHP file with jQuery AJAX.
However while I am looping through the different TLD's it suddenly gets undefined and I am not able to use the "TLD" for further processing within the loop. As far as I can read, it as something to do with the loop happening first and the requests made after, so I somehow have to freeze the index of my array. But I don't know how to do that.
This is my code:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
};
return false;
});
The printed console.log's looks like this:
This is a classic JavaScript issue. In the success function (a closure), the i is being used. That callback runs in the future, once the AJAX call is done. By that point, the loop has finished, and i has been incremented to 4.
tlds[4] doesn't exist, and that's why you're getting undefined. The callbacks are all using the same i value.
To fix it, you need to create a new function to capture the value of i for each callback.
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
var createCallback = function(i){
return function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
};
}
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: createCallback(i)
});
};
return false;
});
By the time the ajax calls return, the loop has long since ended, and i has run past the end of tlds. Trying to print tlds[i] is bound to fail.
Break the lookup into a separate function, with local variables that will be valid on the ajax callback:
var checkup = function(datastring, domain, tld) {
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tld + " is " + data);
}
});
};
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
checkup(datastring, domain, tlds[i]);
};
You need to enclose the code in your loop in a closure as follows:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
(function() {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
})( i );
}
return false;
});
I have values that come from a dynamically created table from it's selected rows. inside each selected row i want all the td.innerText values that belong to be sent to a C# page, but i don't know how to. I was using JSON but I dont know if i used it properly.
function selectedRows()
{
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
serial = td[1].innerText;
kanbanNumber = td[2].innerText;
customer = td[3].innerText;
description = td[4].innerText;
quantity = td[5].innerText;
}
console.log(serial + ' ' + kanbanNumber + ' ' + customer + ' ' + description + ' ' + quantity);
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "labelSerial=" + serial + "&kanbanNumber=" + kanbanNumber + "&customer="
+ customer + "&description=" + description + "&quantity=" + quantity
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
EDIT: sorry I must have read this too quickly. This should do it. create an array and add the data object to it in the loop.
If you just create a json object using key value pairs you can send that object to your c# controller.
function selectedRows() {
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
var dataArray = new Array();
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
var InfoObject = {
serial: td[1].innerText;
kanbanNumber: td[2].innerText;
customer: td[3].innerText;
description: td[4].innerText;
quantity: td[5].innerText;
};
dataArray.push(InfoObject);
}
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: dataArray
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
I've been trying to get this right for quite some time, I'm trying to append the object from the first ajax call after the second ajax call. But the for loop seems to iterate the changing of the value to the last result before appending the information, having the last post appended every time.
var scribjson =
{
"user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
type: "POST",
url: "getScribbles.php",
data: scrib,
success: function(result)
{
var obj = jQuery.parseJSON(result);
for(var i = 0; i < obj.length; i+=1)
{
var userjson =
{
"user_id" : obj[i].user_id
};
userjs = JSON.stringify(userjson);
var user = {json:userjs};
localStorage.post = obj[i].post;
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
}
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
Since ajax calls It looks like the all success functions of the inner ajax call are being called after the loop has ended, so i will always be the last iterated value.
Try this:
(function(i)
{
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
})(i);
This will create a closure on i, which will give each ajax call its own copy of the current value.
Use an IIFE:
success: (function(i){return function(result) {
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),
etc. Currently your loop generated ajax success handlers contain a direct reference to the counter itself, which (by the time they are called) has reached its final value.
Why won't foo get appended?
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success:
function(response) {
$.each(response, function(index, val) {
$(this).parent().parent().append('foo');
});
}
})
Because inside each, this is set to the current element being iterated over (docs), so normally we define this to be something else before we enter the each loop:
var that = this;
$.each(response, function(index, val) {
var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$(that).parent().parent().append('foo');
});
However, in this circumstance, this in the success callback of an AJAX request is equal to the jqXHR object which launched the request, not the DOM element you're after, so we have to move the var that = this to even further away;
var that = this;
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success: function(response) {
$.each(response, function(index, val) {
var content = '<div class="link-history">' + val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$(that).parent().parent().append('foo');
});
}
})
var $this = $('#Selector').parent().parent();
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success:
function(response) {
$.each(response, function(index, val) {
var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$this.append('foo');
});
}
})
EDIT:
added .parent().parent() to the original selector, so you are not calling this for each loop
Response may not be an array, just a string. Try assigning the response to an element and then using a selector to grab all children in that element before doing an .each()
Your response is not an object of elements, it's most likely a list of strings possibly with your selectors(?) if that's it then use $($(this)).
why instead giving data(value) of database give me the [object Object]?
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
$(".list_name").append('<p>' + data + '</p>');
$('.list_name p a').click( function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
});
results url is:(json_encode()) :
[{"name":"333333"},{"name":"\u0633\u0644"},{"name":"\u0633\u0644\u0627\u0633\u06cc"},{"name":"\u0633\u0644\u0627\u0633\u0633"},{"name":"\u0633\u0644\u0627\u0645"}]
update: full code:
$('.auto_complete').keyup(function () {
var id = '#' + this.id;
var alt = $(id).attr('alt'); var id = $(this).attr('id'); var name = $(this).attr('name');
var url = alt + id + '/' + name;
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
data is not a string, but a JSON object, which is basically a Javascript Object. You access it as you would any JS object/array (looks like your result string is an array)
So you can do something like this: data[1].name
data is a list (It is javascript object).
toString( list ) in javascript gives "object Object"
data[0].name will return "333333"
To make a string from a complex object write your own function.
It looks like your Ajax call is returning an array of structures. Each element in the array is a name-value pair. Given that data is an array, the first element is data[0] so you might do something like:
var firstElem = data[0];
var firstName = firstElem.name;
alert("The first name is: " + firstName);
If you want to add all of the names into your html, you would need to loop through the array, each time appending the current element.
If you wanted to show all names, you could do
var names = "";
for (var i=0; i<data.length; i++) {
var elem = data[i];
names = names + elem.name + ", ";
}
I would rewrite it in the following way
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
}
});