Okay, i want to process another javascript request foreach value returned inside a JSON response from a jQuery Request, Here's the current code i'm using for this request
function waitForEvents(){
$.ajax({
type: "GET",
url: "/functions/ajax.php?func=feed&old_msg_id="+old_msg_id,
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){
var json = jQuery.parseJSON(data);
**//Foreach json repsonse['msg_id'] call another function**
setTimeout('waitForEvents()',"1000");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("Error:" + textStatus + " (" + errorThrown + ")");
setTimeout('waitForEvents()',"15000");
},
});
};
for each json response variable ['msg_id'] i want to call another javascript function but don't know how to process the array using a foreach in javascript, any idea how ?
As you're already using jQuery, you can use the $.each function:
http://api.jquery.com/jQuery.each/
$.each(json.msg_id, function (index, value) {
// Do something with value here, e.g.
alert('Value ' + index + ' is ' value);
})
use a simple for loop, likely faster than for each
function myfunction(id){
alert("myid:"+id):
}
var i=0;
for (i=0; i< json.length;i++){
var thisId = json[i].msg_id;
myfunction(thisId);
}
simpler:
function myfunction(id){
alert("myid:"+id):
}
var i=0;
for (i=0; i< json.length;i++){
myfunction(json[i].msg_id);
}
since you asked:
function checkArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
var myId = element.msg_id;
};
json.forEach(checkArrayElements);
and discussion in case older browsers where not implimented: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach so you can do that
Related
I have this function
function actInfo(fund) {
var acct = $('.account');
$.ajax({
url: "account.php",
type: 'get',
dataType: 'json',
data: {fund: fund}
}).done(function (response) {
var len = response.length;
acct.empty();
for (var i = 0; i < len; i++) {
var acctNum = response[i]['ID'];
var acctName = response[i]['NAME'];
acct.append("<option value='" + acctNum + "'>" + acctNum + ' -- ' + acctName + "</option>");
}
acct.prepend("<option value=''>- Select An Account -</option>").val('');
}).fail(function (jqXHR, textStatus, error) {
console.log("actInfo: " + error);
});
}
I call this function in another ajax call because I need to send the function variable that I get from the server. In the same ajax call that I use to call actInfo(fund) I am also trying to select a value. Here is the main ajax call.
function getPoInfo(trnum) {
$.ajax({
url: "edit.php",
data: {trnum: trnum},
type: "GET",
cache: false,
dataType: "json"
}).done(function (poInfo) {
$('#fund').val(poInfo[0]['TRANFUND']);
actInfo(poInfo[0]['TRANFUND']);
$('#account1').val(poInfo[0]['TRANACCOUNT'].trim());
}).fail(function (jqXHR, textStatus, error) {
console.log("getPoInfo(tran_num): " + error);
});
}
The actInfo(fund) function works fine. It builds my dropdown menu. But I don't know how to select a value. I am assuming I am trying to select a value before the dropdown is loading. I don't understand callbacks or promises, and I tried .bind and tried to append .done and .load but I can't get a value selected. How do I do tell when the dropdown menu is finished loading and then select a value?
Since actInfo() method contains an asynchronous operation (basically the <select> element is only built after you have received and parsed the returned JSON response). Therefore, what you want is to:
create a new deferred object, i.e. var deferred = new $.Deferred()
return its immutable promise at the end, i.e. return deferred.promise().
The new deferred object should be resolved (deferred.resolve()) or rejected (deferred.reject()) based on the outcome of the inner AJAX request.
If we take all these points into account, your code can be easily be refactored as follow (I have added comments where I have added the suggested changes):
function actInfo(fund) {
var acct = $('.account');
// Create new deferred object
var deferred = new $.Deferred();
// Perform AJAX call as usual
$.ajax({
// Truncated for brevity
// ...
}).done(function (response) {
var len = response.length;
acct.empty();
for (var i = 0; i < len; i++) {
var acctNum = response[i]['ID'];
var acctName = response[i]['NAME'];
acct.append("<option value='" + acctNum + "'>" + acctNum + ' -- ' + acctName + "</option>");
}
acct.prepend("<option value=''>- Select An Account -</option>").val('');
// Now that the DOM has been built, we can resolve the promise and return it!
deferred.resolve();
}).fail(function (jqXHR, textStatus, error) {
console.log("actInfo: " + error);
// If we encounter an error, we pass it on!
deferred.reject(error);
});
// Return immutable promise
return deferred.promise();
}
Then, in your getPoInfo() method, simply check for the resolution of the returned promise from actInfo():
function getPoInfo(trnum) {
$.ajax({
// Truncated for brevity
// ...
}).done(function (poInfo) {
$('#fund').val(poInfo[0]['TRANFUND']);
// actInfo returns a promise!
var actInfoPromise = actInfo(poInfo[0]['TRANFUND']);
// Wait for the promise to resolve using $.when
$.when(actInfoPromise)
.then(function() {
// If successful, we select the correct <option>
$('#account1').val(poInfo[0]['TRANACCOUNT'].trim());
}, function(error) {
// If failed, we log the error message that has been passed on
console.log(error);
});
}).fail(function (jqXHR, textStatus, error) {
console.log("getPoInfo(tran_num): " + error);
});
}
I have doubt regarding the execution order for a jquery function i created for my project. The function is given below.
$('#s_cust').change(function(event) {
var custId = $("select#s_cust").val();
$.get('ContactAjax', {
custId: custId
}, function(jsonResponse) {
alert("jsonresp: " + jsonResponse);
cconjson = jsonResponse;
var select = $('#s_ccon');
$(select).find('option').remove();
$('<option>').text("Select").appendTo(select);
$.each(jsonResponse, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
if (cconjson != null) {
for (var j = 1; j <= i; j++) {
var select1 = $('#s_ccon' + j);
$(select1).find('option').remove();
alert("test");
$('<option>').text("Select").appendTo(select1);
$.each(cconjson, function(key, value) {
alert("key: " + key + " value:" + value);
$('<option>').val(key).text(value).appendTo(select1);
});
}
}
});
"'#s_ccon' + j" is given because I'm dynamically generating a text box based on the click of a button.
The problem that I have got while using this function is that, after refresh of the form page I change the value in my select list, s_cust, it goes into the ajax call retrieves my data and populate the s_ccon correctly. When I change value of s_cust again it executes the if loop first, then goes back and does the ajax function get, I understood this beacause the first alert that comes after the second change is alert("test"), then the alert("key: " + key + " value:" + value), after this alert("jsonresp: " + jsonResponse).
I don't know why this happens, please tell me the mistake I have made here.
Since Ajax is asynchronous java script does not wait for the ajax request to come back to solve this problem as mention in the question above I had to put the condition evaluation regarding ajax inside the json response function itself, so finally my code looks like this.
$('#s_cust').change(function(event) {
var custId = $("select#s_cust").val();
$.get('ContactAjax', {
custId: custId
}, function(jsonResponse) {
alert("jsonresp: " + jsonResponse);
cconjson = jsonResponse;
var select = $('#s_ccon');
$(select).find('option').remove();
$('<option>').text("Select").appendTo(select);
$.each(jsonResponse, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
if (cconjson != null) {
for (var j = 1; j <= i; j++) {
var select1 = $('#s_ccon' + j);
$(select1).find('option').remove();
alert("test");
$('<option>').text("Select").appendTo(select1);
$.each(cconjson, function(key, value) {
alert("key: " + key + " value:" + value);
$('<option>').val(key).text(value).appendTo(select1);
});
}
}
});
});
According to the documentaion of jQuery, $.get is an asynchronous function. It is equivalent to
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
So you cannot predict the order of execution.
If you want it to happen in a synchronous manner, use $.ajax directly and turn off async.
$.ajax({
url: url,
data: data,
async: false,
success: success,
dataType: dataType
});
Also agree, that it is recommended to place all the code inside the success callback and follow the async process.
I'm having trouble with filtering the returned data from an Ajax JSON call. Right now, it returns:
{"results":[{"text":"RoboChat: What is it like to feel?","username":"RoboChat","createdAt":"2014-06-04T20:01:15.268Z","updatedAt":"2014-06-04T20:01:15.268Z","objectId":"wG2cs1OnVY"},
I'm trying to get it to return only the "text" object, like this:
"RoboChat:What is it like to feel?"
Here is my code:
function fetch () {
$.ajax({
url:"https://api.parse.com/1/classes/chats",
type : 'GET',
dataType : 'JSON',
data : JSON.stringify({
}),
success:function(data) {
$('.messages').append("<li>" + (JSON.stringify(data)) + "</li>")
}
});
};
I've tried passing a filter to JSON.stringify, but with no success, I'm not even sure if that's the way to approach filtering the data. Any help would be much appreciated.Thanks!
You can't really change what a request returns, but you can of course use the resulting value in any way you want. Since the response contains multiple objects with text properties, you have to iterate them and extract the text:
success: function(data) {
var results = data.results;
results.forEach(function (result) {
$('.messages').append("<li>" + result.text + "</li>");
});
}
The returned JSON has a results property which is an array, you can iterate through the array and read the text property of each element:
$.each(data.results, function(index, element) {
console.log(element.text);
});
For creating a li element for each array's element, you can use the $.map utility function:
var li = $.map(data.results, function(element) {
return '<li>' + element.text + '</li>';
});
$('.messages').append(li);
try for, the data has an array named results, from wich you have to select the first like following:
success: function(data) {
var results = JSON.parse(data).results;
results.forEach(function (result) {
$('.messages').append("<li>" + data.results[0].text + "</li>");
});
}
I'm a newbie, and I apologize for this.
I am writing a script that will make a GET request. The result is a JSON array and the best deal would be to have it put automatically in a CSV/TXT file.
$.ajax({
type: "GET",
url: BASE_URL,
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
station = JSON.parse(jimmi);
}
var ar_len = jimmi.length
for (i=0; i < ar_len;) {
$("#results").html(
"Station: " + jimmi[i].name + "<br />")
i++
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
My problems:
* I get displayed only the last element of the array, and I can't figure out why.
* I would need to make this call automatically each 5 seconds
* The JSON results should be written into a CSV/TXT file.
Can someone help me?
BTW, the URL is https://its.navizon.com/api/v1/sites/1001/stations/ and you can log using demo#navizon.com - no password (read only)
Your problem is that you're changing the contents of #results for each element of jimmi by changing the entire inner HTML. So in the end, only the last element gets displayed. You need to use append instead. To make the call every 5 seconds, use the setTimeout method. Something this like:
function makeCall() {
$.ajax({
type: "GET",
url: BASE_URL,
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
jimmi = JSON.parse(jimmi);
}
for (i=0; i < jimmi.length; i++) {
$("#results").append("Station: " + jimmi[i].name + "<br />");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
window.setTimeout(makeCall, 5000);
}
makeCall();
Note: The line station = JSON.parse(jimmi); is not useful because the variable station is never used. I changed it to something that made more sense.
On the server side do I have 2 hashes I encode into JSON strings like so
my $j = JSON->new;
$j = $j->utf8;
my $data;
$data->{users} = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
On the client side I have
$(document).ready(function(){
$('form').live('submit', function(){
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
},
success: function(result){
if (result.error) {
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
var users = result.users;
var owners = result.owners;
...
users contains
{"ss":"Sandra Schlichting","fn":"Full name"}
but it is not an array. When I use $.each() it takes on character at a time.
Problem
How do I turn it into an array, so I can use
function makeTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
which should produce
Initials Full Name
ss Sandra Schlichting
fn Full name
You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.
There is also $.parseJSON() method to parse string to json if you want to go that way.
You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.
Edit: Here's an example: http://jsfiddle.net/pedrocorreia/s5UrZ/2/
You can use the JSON parser created by douglas crockford:
https://github.com/douglascrockford/JSON-js
include the json2.js in your page, the you can do:
var object = JSON.parse(string);
Then you can use it as an array.
you can use for in statement
var index = 0;
for(user in users){
result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}