Looping through two JSON arrays Ajax - javascript

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

Related

How do i split ajax return values using jquery

I want to split the ajax returned values using jQuery.
Here is my code:
var url = "/StudentProgress/GetStudProgDet/";
$.ajax({
url: url,
data: { currentAcadYr: iAcademicYearText, currentSem: iSemesterText },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
var result = $(data).text().split(':');
var ProgAcadYearCode = result[0].ProgAcadYearCode;
var productSize = result[1];
// alert(data.ProgAcadYearCode);
//$("#ToProgressAcademicYearId option").filter(function () {
// return this.text == testsem;
//}).attr('selected', true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
I got a result like this:
data = {
success: true,
progAcadYearCode: 20172018,
progAcadYearId: 17,
progressSemId: 47,
progressSemNo: 2
}
How do I extract the desired values from the JSON using jQuery?
Based on data what you shown,you have to directly fetch it's properties like below:-
success: function (data) {
console.log(data.success);
console.log(data.progAcadYearCode); //and so on
},

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

Get ID of element in jQuery autocomplete source function

I have a webservice method that takes the id of an element to determine the source for autocompletes.
In a nutshell, I'm doing this:
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this).attr('id');
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
response(JSON.parse(msg.d));
},
error: function() {
response([]);
}
});
}
});
But id isn't referring to the original selector.
What can I do to get the id of the selected input element? Or what is a better strategy for this?
You'd need to maintain a context of each input element, something like this:
$("input[type='text']").each(function (i, ele) {
ele = $(ele);
ele.autocomplete({
source: function (request, response) {
var id = ele.attr('id');
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// ...
},
error: function () {
// ...
},
async: false
});
}
});
});
Try
$(this.element).prop("id");
this.element[0].id;
$(this.element.get(0)).attr('id');
JSFIDDLE
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
response(JSON.parse(msg.d));
},
error: function() {
response([]);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input type="text" id="asd"></input>

Error while adding JSON responses to an array [duplicate]

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;
}
});
}

Ajax doesn't execute success function

My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});

Categories