Error while adding JSON responses to an array [duplicate] - javascript

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to make a url shortener using goog.gl api. Thanks to #Barmar now I can get my short URL using this code:
var shortURL;
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
shortURL = response.id;
}
});
But I want to shorten an array of links! So I decided to use loop.
I created longURL[] and shortURL[] but if I run this code I get such output in shortURL array: [undefined × 10, "http://goo.gl/AxzWLx"]; Full code:
var longURL = [];//there are some urls
var shortURL = [];
for (var k = 0; k < longURL.length; k++) {
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL[k] +'"}',
dataType: 'json',
success: function(response) {
shortURL[k] = response.id;
}
});
}

The problem is that all your callback functions share the same value of k, because it's not a per-function closure variable. You can use the context: option to pass the appropriate value to each callback.
var longURL = [];//there are some urls
var shortURL = [];
for (var k = 0; k < longURL.length; k++) {
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL[k] +'"}',
dataType: 'json',
context: k,
success: function(response) {
shortURL[this] = response.id;
}
});
}
Another solution is to use $.each(). Since each iteration is a function call, you'll close over the parameters:
var longURL = [];//there are some urls
var shortURL = [];
$.each(longURL, function(k, url) {
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + url +'"}',
dataType: 'json',
success: function(response) {
shortURL[k] = response.id;
}
});
});

This is a classic JavaScript problem. In your success function, you are using the same k for each AJAX call. You need to capture the value of k for each iteration.
var longURL = [];//there are some urls
var shortURL = [];
for (var k = 0; k < longURL.length; k++) {
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL[k] +'"}',
dataType: 'json',
context: {key: k}, // the "this" value in the callback
success: function(response) {
shortURL[this.key] = response.id;
}
});
}

Related

How to get the data value during Jquery Ajax calling?

I'm calling Ajax like below
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: '{ "jsondata":' + jsondata + ',"key":"' + getValue('id') + '"}',
success: function (data) {
callback(data);
},
error: function (error) {
callback(error.responseText);
}
});
I want to get the "Data" value at calling time because after the call the execution doesn't goes to the desired web method and the error is showing like
""Message":"Invalid web service call, missing value for parameter: \u0027obj\u0027..."
I have to track the the Ajax posting value during Ajax call and find out what is the problem with posting data.Is there any tricks to get the data value before Ajax calling?
Any help will be appreciated.
Edit: I'm sending the jsondata value like below
var jsondata = '{ "pagenumber":"' + pagenumber + '","sortColumn":"' + sortColumn + '","sortDirection":"' + sortDirection + '","rowPerPage":"' + rowPerPage + '"}';
Thanks.
I was just checking with below code -
please have a look. please check beforesend content
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/dummy',
dataType: "json",
data: '{dummy:"dummy"}',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error);
},
beforeSend: function(data,data1) {
console.log('before'+data1.data)
},
});
})
});
var path = "test_ajax.php";
var jsondata = "Testing123";
var test = "test";
var data = {jsondata : jsondata,key : test};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: data,
success: function (data) {
alert("success:"+data);
},
error: function (error) {
alert("failure"+error.responseText);
}
});

put JSON response in var and output it

I have a form which sends Zip code + housenumber to an external page and the external page sends me a json response with the address information back.
This all works but how can i grab this json response put it into a variable and output it again on my page.
Here i do a post to a page
function validate() {
var postc = $('#postc').val();
var huisnr = $('#huisnr').val();
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
});
and i get this response in the header of postcodecheck.php
{"location":[{"city":"Amsterdam","postcode":"1012NX","straat":"Kalverstraat","nummer":1}]}
How can i grab this reponse and put it into a variable ?
Any help would be highly appriciated.
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false,
success: function(data) {
$.each(data.location, function(index, value) {
console.log("City " + value.city)
console.log("postcode " + value.postcode)
console.log("straat " + value.straat)
})
}
});
Add success and inside success you can iterate on the data
Demo
you can use request callback to get the retrieved data & put it into a variable
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
})
.done(function(data) {
console.log(data);});
The ajax call have another attribute called success you need to use it.
var store = '';
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false,
success: function(result){
store = result;
}
});
Result
console.log(store); //{"location":[{"city":"Amsterdam","postcode":"1012NX","straat":"Kalverstraat","nummer":1}]}
You need to use the done method and pass data as an argument to the callback function that will then contain the response from the server.
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
}).done(function(data) {
var result = data;
alert(result);
});

Looping through two JSON arrays Ajax

I'm trying to get data from a Json file using the id from a previous previous ajax call looping through the the second array based on the id gotten from the first
I have tried
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
$('.blog').empty();
for (var i=0; i<n; i++) {
var storytitle = output.data[i].story_view;
var id = output.data[i].titleID;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var n2 = output2.data[0].episode_count;
for (var i=0; i<n2; i++) {
var titles = output2.data[i].title;
console.log(storytitle + " " + titles);
}
}
else {
console.log('faileds');
}
});
}
} else {
console.log('failed');
}
});
});
The storyTitle has a single value and loops through all the titles when i check my console.
I tried debugging and found out the second for-loop was only executed once, after executing request2.done, it goes back to the first for-loop after the first has finish all its loop, it executes the second for-loop.
I don't know where am missing it.I need help with this.
Finally solved the problem...Changed my code to...
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var CLASS = this.story_view;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
console.log(id + " " + id2);
})
}
})
})
} else {
console.log('failed');
}
});
})
And it worked fine....thanks to Swapnil Godambe

Ajax call not accepting Names with apostrophe as a parameter

$(".loadingPnl").removeClass('hdn');
var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/SaveAvailableFavoriteItem";
var linkName = $('.txtLinkName').val();
linkName = linkName.replace("'","\'");
$.ajax({
type: "POST",
url: callUrl,
data: "{'linkName': '" + linkName + "', 'webSiteUrl':'" + $('.txtWebAddress').val() + "','iconId':'" + $(".ddlIcons").val() + "'}",
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
return true;
}
The problem is you're building JSON yourself as the request parameters. Moreover, you're building invalid JSON (JSON property names are always with double quotes (")).
Instead, pass an object and let jQuery take care of how to send it - if you pass that instead of a string the server can figure it out. If you really want to do it yourself you can also pass an object to JSON.stringify.
var payload = {
linkName: linkName,
webSiteUrl: $('.txtWebAddress').val(),
iconId: $(".ddlIcons").val()
};
$.ajax({
type: "POST",
url: callUrl,
data: JSON.stringify(payload), // or just payload
contentType: "application/json; charset=utf-8",
processData: false, // if you just pass payload, remove this
dataType: "json"
// you had two `return`s here, but they wouldn't work, make sure
// you understand why
// http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call
});
You can send a JSON instead. Or use JSON.stringify if you want String.
{
'linkName' : linkName,
'webSiteUrl' : $('.txtWebAddress').val(),
'iconId' : $(".ddlIcons").val()
}
Don't create JSON string by yourself AND don't use JSON.stringify().
Problem with creating JSON string yourself is to escape string properly for JavaScript (which could be tricky). see Special Characters
Problem with JSON.stringify is that I found it somehow slower than XMLHttpRequest which is strange because I thought it is using JSON.stringify behind curtains.
XMLHttpRequest is handling this for you. If you just pass your object as a data and XMLHttRequest will do the trick.
$.ajax({
type: "POST",
url: callUrl,
data: {'linkName': linkName,
'webSiteUrl': $('.txtWebAddress').val(),
'iconId': $(".ddlIcons").val()
},
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});

How to extract text from JSON response?

I am trying to make url shortener that uses goo.gl API. But i stucked when I have to get short URL from JSON response!
After entering this code in Chrome Console:
var longURL = "http://stackoverflow.com/questions/ask"
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
var result = JSON.parse(response);
}
});
I get following ouptut:
I see that my short URL is in resoinseText.id. How to extract it from there?
You don't need to call JSON.parse(), because jQuery does that automatically when you specify dataType: 'json'. The value you want will then be in the id property of response.
var longURL = "http://stackoverflow.com/questions/ask"
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
console.log(response.id);
}
});

Categories