How to set values to array when async webservice responce is called - javascript

Friends,
I have declared array in javascipt
var Answer1 = new Array(50);
I want to call webserivce using $ajax & i want to store its response at appropriate index of array.
& want to use that array immediately after all the values are set.
Currently i am doing this by using async:false property of $ajax .
Does anyone know way with asynchrnous way because when i use asynchronous values of array remains undefined.
for(var j=0;j < mycollection.length-1;j++)
{
$.ajax({
type: 'GET',
url: webserviceURL,
dataType: 'json',
error: function(data)
{
//alert(data.error);
},
success: function(data)
{
if(data.error!=null)
{
console.log('data error');
Answer1[j] = data.name;
}
},
complete: function(data)
{
alert('completed:');
},
data: {},
async: false
});

Well you are using the wrong index for Answer1:
Answer1[i] = data.name;
should be:
Answer1[j] = data.name;
But if that still doesn't work, pass j as a parameter to your webservice and get the webservice to return it as part of the response so you know the index to assign to.
Also you are only assigning if data.error is not null? Is that what you want, didn't you want to assign if there is no error (i.e. data.error is null)?

Put whatever code uses the array into a function. Call that function from the success handler for your Ajax call.

Related

jQuery -- nesting ajax calls and using data from each call - wikipedia API

I am having problems in nesting ajax calls with jQuery to wikipedia api.
The HTML is simple, just an input form and a button:
<input id='search-input' type="text" class="form-control">
<button id="search-button" type="button" class="btn btn-primary">Search</button>
<div id ='outputDiv'></div>
THe search button has an event listener that fires a function that grabs data from wikipedia API:
...
searchBtn.addEventListener('click', searchwiki);
...
function searchwiki(){
let searchTermObjects =[]
let term = inputfield.value;
let titleUrl = search_term(term);
createWikiObject(titleUrl).then(function(){
searchTermObjects.forEach(function(elem){
addExtrctToObj(elem)
})
}).then(function(data){
append_result(searchTermObjects)
})
}
function createWikiObject(titleUrl){
return $.ajax({
type: "GET",
url: titleUrl,
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error in searching',ermsg)
},}).then(function(data){
for(let i = 0; i < data[1].length; i ++){
searchTermObjects.push({
'title': data[1][i].replace(/\s+/g, '_'),
'description': data[2][i],
'url': data[3][i],
})
}; // this for loop should push each result as an object to an array named searchtTermObjects, and i am planning to use this array in the next ajax call to add another property named extract to each object in array
}
);
}
function addExtrctToObj(obj){
console.log(obj)
return $.ajax({
type: "GET",
url: get_text(obj['title']),
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error getting text',ermsg)
}
}).then(function (data){
let pageID = Object.keys(data.query.pages);
if(data.query.pages[pageID].hasOwnProperty('extract')){
obj['extract'] = data.query.pages[pageID].extract;
}
// this function adds the extracted text for each article ,
// the searchTermObjects now looks something like:
/ [{'title':...,'url':...,'description':...,'extract':..},{...}]
})
};
function append_result(termsObjectsArray){
// this function should loop through the searchtermobjects and append leading text for each object in the array to the Output div under the button
for (let i = 0; i < termsObjectsArray.length; i++){
let newDiv = document.createElement('div');
HOWEVER, Object.keys(termsObjectsArray[i]) returns only three keys at this time, and doesn't see the extract key'
console.log(Object.keys(termsObjectsArray[i]))
newDiv.classList.add('wiki-result');
newDiv.innerHTML = termsObjectsArray[i]["extract"];
HERE is where i get error -- the inerHtml of newDiv has value UNDEFINED
outputDiv.appendChild(newDiv);
}
}
// the api calls are formed with these functions:
let base_url = "https://en.wikipedia.org/w/api.php";
function search_term(term) {
let request_url = base_url + "?action=opensearch&search=" + term + "&format=json&callback=?";
return request_url;
}
function get_text(term){
let request_url = base_url + "?action=query&prop=extracts&exintro=&format=json&titles=" + term; // explaintex= returns plaintext, if ommited returns html
return request_url;
}
afetr I console.log(searchTermObjects) i get what i need, the array with objects that have all 4 properties with correct names, but I don't understand why the append_result function doesn't see the 'extract' key.
Next to the logged object in the console is the 'i' sign that says 'Value below was evaluated just now' , and there I have what I wanted -- every search result as an object with title, url, description, and extract keys.
copy this code to your IDE to see if you can help me with finding solution.
I believe the issue you're having is that you're attempting to return a Deferred object, and there's nothing to return yet because of the deferral.
return $.ajax({
type: "GET",
url: get_text(obj['title']),
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error getting text',ermsg)
}
})
The async value is true, so the code is moving on before the request is finished, and you're getting a null value back.
Try setting async: false and see if you get a better response. As pointed out by Andrew Lohr in the comments, this is not a good way to solve the problem, it will only tell you if that is the problem.
If it is, then I would recommend not breaking the request up into multiple functions. You should just chain the AJAX calls, using the deferral approach. It would be structured like this:
$.ajax({ ... }).then(function(data){
// ... do something with the data ...
// Make your followup request.
$.ajax({ ... }).then(function(data) {
// ... finalize the response ...
});
});
Also consider using the context option in the ajax call to pass in a callback method that can be fired once the chain is complete.

Accessing Ajax Response JSON Data in javascript

I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location

How can I capture the Array object returned by an api call through HTTP GET?

The API call
https://myhost.net/api/get_global_search_result/methods/test
returns an Array object. I am trying to hold it in an Array object in order to read the attributes and values in it.
var queryResult = [];
queryResult = browser.get('https://myhost.net/api/get_global_search_result/methods/test/');
console.log('result length: ' + queryResult.length);
This is what I see on my console:
result length: undefined
If I load the above specified URL directly in a browser instance, it shows the Array with its contents.
What is the better way of capturing the array object returned by this call?
What about using JQuery ajax request.
it would be some thing like :
$(document).ready(function() {
$("#testbutton").click(function() {
$.ajax({
url: 'http://localhost:9200/xyz/xyz/xfSJlRT7RtWwdQDPwkIMWg',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function() {
alert('error');
}
});
});
});

Add additional data to jQuery wrapped object data in $.ajax call

I have this working code:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']'),
complete: function (mydata) {
//do something with it
}
});
That successfully posts back any checked checkboxes and all textboxes. But now I want to add some arbitrary data as well to this. But not sure how to format it. Basically i want to simply add my own name=value pair "test=1" so that on the callback I see it like the others. But no matter what I try, I can't see to get the syntax correct in the format it expects. not sure if I should be adding it inside the jQuery() wrap or outside.. I've tried serializing, encodeURIComponent, basic string "&test=1"
Any ideas?
Your best bet is to build the parameters outside of the AJAX call, like so:
var params = jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']');
params.test = 1;
params.test2 = 2;
Then in your AJAX call, simply use:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: params,
complete: function (mydata) {
//do something with it
}
});
EDIT: Typically when using jQuery to collect input, I tend to use the .each function, like so:
var params = new Object();
$.each('input[name^=option]', function() {
if ((this.type === 'checkbox' && $(this).is(':checked')) || this.type === 'text' && this.value !== '') {
params[this.name] = this.value;
}
});
Then if you wish to add parameters, you'd do so either after this, or right after creating your new object.
I forgot I asked this previously. It was answered correctly so I'm sharing the link:
How can I pass form data AND my own variables via jQuery Ajax call?

Why is AJAX/JSON response undefined when used in Bootstrap typeahead function?

I created a function that makes a jquery AJAX call that returns a JSON string. On its own, it works fine -- and I can see the JSON string output when I output the string to the console (console.log).
function getJSONCustomers()
{
var response = $.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
async: false,
cache: false
}).responseText;
return response;
};
However, when I set a variable to contain the output of that function call:
var mydata = getJSONCustomers();
, then try to use it within my Twitter-Bootstrap TypeAhead function (autocomplete for forms):
data = mydata;
console.log(data);
I get an 'undefined' error in my console.
Below is a snippet of this code:
$(document).ready(function() {
var mydata = getJSONCustomers();
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
data = mydata;
console.log(data);
// multiple .typeahead functions follow......
});
Interesting here, is that if I set the data variable to be the hardcoded JSON string returned from the AJAX function, everything works fine:
data = [{"CustNameShort": "CUS1", "CustNameLong": "Customer One"}]
How can I use the JSON string within my typeahead function?
.responseText returns a string. You have to parse the string first to be able to work with the array:
var mydata = JSON.parse(getJSONCustomers());
That being said, you should avoid making synchronous calls. Have a look at How do I return the response from an asynchronous call? to get an idea about how to work with callbacks/promises.
The problem is that the Ajax request hasn't had the chance to complete before typeahead is initialised, so typeahead is initialised with an uninitialised mydata variable. Also, as of jQuery 1.8+ async: false has been deprecated and you need to use the complete/success/error callbacks.
Try this:
function getJSONCustomers(callback) {
$.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
cache: false,
success: callback
});
};
And then you could do something like:
getJSONCustomers(function(mydata) {
// mydata contains data retrieved by the getJSONCustomers code
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
console.log(mydata);
// multiple .typeahead functions follow......
});
});
So your code completes the Ajax call before initialising the typeahead plugin.

Categories