How to Send Ajax Request After A Specific Time - javascript

How to Send Ajax Request in specific time and only that particular event
I m User Time Interval But it’s not Working.
i want get data in request 1 for use in request 2 but it get null data in request 2
setInterval()
it's not Working for me.
I want To send Request 2 After the some time of Request 1
Request 1:-
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
},
success: function (data) {
console.log(id);
if (data.status) {
var html_data = '';
var item = data.value;
console.log(item);
$('.hospitalPart[data-id=' + id + ']').val(item.hospitalNumber);
$('.mfgPartNumber[data-id=' + id + ']').val(item.mfgPartNumber);
// $('.mfgPartNumber[data-id='+id+']').text('something');
} else {
$('.hospitalPart[data-id=' + id + ']').val('');
$('.mfgPartNumber[data-id=' + id + ']').val('');
}
$('.quantity[data-id=' + id + ']').val('');
$('.purchaseType[data-id=' + id + ']').val('');
$('#serial-text' + id).val('');
$('#serial-drop' + id).val('');
$('#serial-drop' + id).empty();
}
});
}
});
Request 2:-
$(document).on('change', '.supplyItem', function (event) {
var timer, delay = 2000;
var id = $(this).attr("data-id");
var client = $("#hospital").val();
timer = setInterval(function(){
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospitalPart = $(".hospitalPart[data-id=" + id + "]").val();
var mfgPartNumber = $(".mfgPartNumber[data-id=" + id + "]").val();
alert(supplyItem);
alert(hospitalPart);
alert(mfgPartNumber);
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: hospitalPart,
mfgPartNumber: mfgPartNumber,
client: client,
},
success: function (data) {
if (data.status) {
var html_data = '';
var check = data.value;
if (check == 'True') {
html_data += "<option value=''>Purchase Type</option><option value='Bulk'>Bulk</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
} else {
html_data += "<option value=''>Purchase Type</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
}
}
}
});
}, delay);
clearInterval(timer);
});

You can move Request 2 into a function and this JS code will call the Request2 function after given interval of time (milliseconds), I have set it to 5 seconds for now.
setInterval(function () { Request2(); }, 5000);
function Request2(){
console.log("Request 2 called");
//add request 2 code here
}

jQuery's $.ajax method returns a promise, which is passed the result of the server-side call. You can chain these calls together so that you can build the result of multiple ajax calls. When you use it this way you do away with success callbacks as they are no longer necessary.
Applied to your code it might looks something like this:
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
})
.then(function(data1){
// process result of call1 and make call2
var item = data1.value;
return $.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: value.hospitalPart, // note using result from 1 directly
mfgPartNumber: value.mfgPartNumber,
client: hospital
}
});
})
.then(function(data2){
// process result of call2
});
};
});
The point here is that you don't need to stash the result of call1 into some elements and re-read them before making call2, and trying to wait enough time before making call2. You just chain it all together with then.

Ok first though: Instead of using setInterval and then clearing the interval after it has run a single time, why not just use
setTimeout(function, delay);
Then personally I prefer to use XMLHttpRequest instead of Jquery AJAX, Jquery uses XMLHttpRequest at its base anyway,I just prefer it so I dont have to use Jquery, but if your already using Jquery in your site then it should be no more heavy. Here is a quick example of XMLHttpRequest so u can use it if you prefer.
var xhr = new XMLHttpRequest();
xhr.open("POST", 'URL::to("admin/repcasetracker/getdevicedata")', true);
xhr.setRequestHeader("Content-Type", "application/json charset=utf8");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// content is loaded...
if (xhr.responseText) {
//Some code to run after the server responds and it was successfull
}
}
};
xhr.send(JSON.stringify({test:'test'})); //This is the data you are handing to the server
Notice the use of xhr.responseText, JQuery uses the same variable and this is usually the response from the server. One sure way to know is use your browser's debugging engine (F12 on Chrome and Firefox, have no idea on other browsers) to inspect the variables, it is very easy to ascertain the correct variable to use.
And then one last thought: I see you are not declaring the content-type and not JSON.stringify'ing() your data when you send it to the server.
Best way to debug a situation like this is 'proccess of elimation' so find out if the server is receiving the data then if the server is proccessing the data correctly and then check if the server is sending the data correctly.
If you are using Nginx use the /var/log/nginx/error.log to see if it throws any errors ( tip: tail -f /var/log/nginx/error.log | Apache uses /var/log/http/error.log on most distros ) and if you are using .NET just debug it in Visual Studio.
And read up on the Jquery success event there is 2 more arguments that gets passed - String textStatus and jqXHR jqXHR
http://api.jquery.com/jquery.ajax/
So to summarize:
Make sure to declare the dataType: 'json'
Use the correct variable, should be responseText
when passing the server data and using 'json' make sure to JSON.stringify() it
And I don't quite see why you want to use setTimeout in the first place.
If you are simply waiting for the server to respond then using any type of delay will be a terrible idea, instead use the events that gets fired after the server responds.
So in Jquery that is success: function() {} and error: function() {}
and in XMLHttpRequest its the xhr.onreadystatechange = function () { }

Related

YQL AJAX cross domain request stopped working

I have been using the following code to successfully read the contents of an external webpage as a string - I haven't used this program in a month or so but it has suddenly stopped working even though the code has not been changed. I suspect the YQL API has been updated but I couldn't find any documentation that I could understand on this. (I am a beginner at JS). If someone could point me to how to update my code it would be much appreciated!
Code:
function formSubmitted(raceID) {
if(raceID.length < 4 && raceID > 0){
savedRaceID = raceID;
raceUrl = "http://www.bbk-online.net/gpt/lap"+raceID+".htm";
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0].replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
//THE ERROR IS COMING FROM ABOVE - REPLACE IS BEING CALLED ON A NULL OBJECT??
//SUGGESTS NO DATA RETURNED?
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: raceUrl,
type: 'GET',
success: function(res) {
processData(res.responseText);
}
});
}
else{
alert("Please enter a valid race number...");
}
}
I have highlighted where the error is coming from - it appears that the function is not returning any data?

Why is this $.ajax function successful only the second time it's called?

I'm experimenting with the Rotten Tomatoes API. On a click event, a search returns JSON data for the closest matched movie title and thumbnail image to the search input.
Upon completion of that first $.ajax request, a second $.ajax request is made, using var resultID, which was declared at the top and set upon 'success' of the first $ajax request.
As of now, when I click for the first time, it runs the first request successfully, but it can't run return json.total (upon 'complete') because the resultID is returned as 'undefined'. But the second time I click, resultID has apparently been set, since it will return json.total successfully.
I'm guessing this a simple problem related to how I'm declaring and calling resultID (or the asynchronous firing of ajax), but I'm not sure what it is. Can anyone explain?
var apiKey = '***********';
var resultID = "";
$('#search-submit').click(function(){
var queryText = $('#movie-search').val();
var queryURI = encodeURI(queryText);
var searchApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=" + queryURI + "&page_limit=10&page=1&apikey=" + apiKey;
var reviewApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies/" + resultID + "/reviews.json?review_type=top_critic&page_limit=10&page=1&country=us&apikey=" + apiKey;
$.ajax({
url: searchApiRequest,
type: 'GET',
dataType: 'jsonp',
error: function() {
console.log('there was error in processing the search request.');
},
success: function(json) {
var movieInfo = json.movies[0];
var noResultsMessage = 'your search returned no matches. Please try again.';
var resultTitle = movieInfo.title;
var resultThumb = movieInfo.posters.thumbnail;
var resultDesc = movieInfo.critics_consensus;
var reviewsPublicURL = movieInfo.links.reviews;
var reviewsRequest = reviewsPublicURL;
resultID = movieInfo.id; // supposed to set global var resultID to movieID
$('.search-results').find('img').attr('src',resultThumb).end().find('h1').text(resultTitle).end().find('p').text(resultDesc);
},
complete: function() {
$.ajax({
url:reviewApiRequest,
type: 'GET',
dataType: 'jsonp',
error: function(json) {
console.log('for whatever reason, we could not find any reviews of this movie');
},
success: function(json) {
console.log(json.total);
}
});
}
});
});
You need to not only set a global resultID but also refresh a reviewApiRequest as well. It doesn't magically change its value by itself when you update resultID.

using .ajax() in .each()

I'm trying to iterate through elements of .ball class and check if their associated url exists:
$(".ball").each(function(i){
var url;
var c_day = $(this).data('day');
var c_mon = $(this).data('mon');
var c_year = $(this).data('year');
url = c_year + "/" + c_mon + "/" + c_day + ".html";
$.ajax({
url: url,
error: function()
{
alert('file: ' + url + ' does not exist');
},
success: function()
{
alert('file: ' + url + 'EXXXXXXISTS!!!!!');
blogA[ blog_count ] = url;
blog_count++;
$(this).css("color", "red" );
}
});
});
I've done some research and read that using .ajax in .each causes a lot of problems but I couldn't wrap my head around on how to fix it.
The problem is that I get really weird results (has to do with asynchronous?). If I alert url outside of ajax, it correctly iterates through the elements. If I alert url in ajax, it spits out urls that belong to the last element of the class.
Something like this, in order to simplify your code
function successHandler(url, ball) {
return function(ret) {
alert('file: ' + url + 'EXXXXXXISTS!!!!!');
ball.css('color','red')
}
}
var balls = $('.ball'), requests = []
balls.each(function(index, ball) {
var url = ...
requests.push($.ajax({ url : url , success : successHandler(url, ball) })
})
$.when.apply($, requests).done(function() {
alert('all balls are checked')
})
Or with ES6:
const success = (url,ball)=>(ret)=>ball.css('color','red')
const balls = $('.balls')
, reqs = balls.map( (b, i) => {
const url = ...
return $.ajax({url, success:success(url,ball)})
})
$.when.apply($, reqs).done( (resps) => alert('all done'))
A Little explanation: You are blindly using this in your callback, not knowing in which context it is going to be executed. In order to work around it and has your URL into callback we are creating function that returns a function, so it will have URL of current .ball DOM object in the context.
You'll probably also need to execute code after all ajax requests are done, so using $.when is the simplest way of doing it. And we are storing all promises just for this reason.
If you aren't concerned about the order of execution of each ajax call and just want to know when they are all done and the array is fully populated, then you can get this to work by fixing your reference to this and by adding a callback function that is called when all items are done:
// this function called when the ajax calls for all balls have finished
// at this point, blogA and blog_count will be populated
function ballsDone() {
// put your code here
}
var balls = $(".ball");
var cnt = balls.length;
balls.each(function(i){
var url;
var self = $(this);
var c_day = self.data('day');
var c_mon = self.data('mon');
var c_year = self.data('year');
url = c_year + "/" + c_mon + "/" + c_day + ".html";
$.ajax({
url: url,
error: function()
{
alert('file: ' + url + ' does not exist');
if (--cnt <= 0) {
ballsDone();
}
},
success: function()
{
blogA[ blog_count ] = url;
blog_count++;
self.css("color", "red" );
if (--cnt <= 0) {
ballsDone();
}
}
});
});
Keep in mind that the ajax calls are asynchronous so the ONLY place you can use the results from the ajax call is in the success handler. You can't use the results of the ajax calls right after the .each() call in a synchronous fashion because the ajax calls have not yet finished. You must wait for the success handler to be called and when cnt success handlers have been called, then they are all done and you can then process the results.

Javascript Array loses data

I'm having trouble getting my information into an array in an ajax call, if I alert the information right after I insert it into the array it works fine, but if I do it at the end it alerts unidentified. I made sure that books is declared outside so it doesn't interfere.
var books = [];
$.ajax({
url: 'getFolderContents.php',
dataType: 'json',
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
},
error: function()
{
alert("error");
}
});
alert(books[0]);
Your
alert(books[0]);
will be executed while the Ajax call is running and therefore will not have any elements at this point of execution yet. Ajax is asynchronous - while you are doing a request to your PHP script your script continues execution.
Put all actions with books in your success function.
Another hint: As of jQuery version 1.8 you cannot longer use the parameter async: false to create a synchronous "A"jax call. You have to use the callback functions. Have a look at the docs for $.ajax
Your array hasn't lost any data; the data hasn't been put in there yet. The 'A' stands for "asynchronous", meaning your success callback hasn't run yet at the time you call the alert.
Put the alert inside your callback instead:
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
alert(books[0]);
},
Your alert is executing before the success function is called. Perhaps seeing the same code using a promise will make things clearer.
$.ajax( url: 'getFolderContents.php', dataType: "json" )
//the then function's first argument is the success handler
.then(function( data ) {
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
alert(books[0]
});
});
I always feel this syntax makes async stuff make more sense. Otherwise this code functions exactly like Blazemonger's correct answer.
Your AJAX call is asynchronous, that's why it is undefined.
The alert at the end happens before the ajax success callback, because ajax is asynchronous.

How to replace function params?

I'm using the following code to make ajax call where the form data is passed as params.
//ajax call
function restServiceCall(origin,destination,tripType,dateDepart,dateReturn){
dataString = 'origin='+ origin + '&destination=' + destination + '&tripType='+tripType;
$.jsonp({
"url": flightURL,
callbackParameter:jsonpCallBack,
data: dataString,
beforeSend:function(){$('#loadingdiv').show()},
"success": function(data) {
if(data.error != null){
$('#errtitle').html('<h2 class="pgtitle">Error !! '+data.error+'</h2>').show();
$("#displaydiv,loadingdiv").hide();
}else{
renderData (data,dateDepart,dateReturn);
}
},
"error": function(xOptions, textStatus) {
$('#errtitle').html('<h2 class="pgtitle">Sorry the service you are looking for is currently unavailable</h2>').show();
$("#displaydiv,loadingdiv").hide();
}
});
}
Besides making the call from form I also use it in the following function wherein I just need to pass either the dateDepart/dateReturn as params.
//for pagination
$('.pagenation a').bind('click',function(){
var numDays = 7;
var self = $(this);
var dateTemp = self.parents(':eq(1)').attr('id')=="onewaytripdiv"? parseDate(dateDepart):parseDate(dateReturn);
if(self.hasClass('left')){
var tempDepDate = removeNumOfDays(dateTemp,numDays);
}else{
var tempDepDate = addNumOfDays(dateTemp,numDays);
}
var changedDate = tempDepDate.getDate()+' '+cx.monthNamesShort[tempDepDate.getMonth()]+' '+tempDepDate.getFullYear();
if(self.parents(':eq(1)').attr('id')=="onewaytripdiv"){
dateDepart = changedDate;
}else{
dateReturn = changedDate;
}
restServiceCall(origin,destination,tripType,dateDepart,dateReturn);
});
I would like to remove the params in the function call, as the params may vary. Please suggest an alternative to pass the params.
How about passing an array of parameters instead? And then pass another value, such as an integer to indicate to the function what to expect in it's parameter array.
e.g
restServiceCall(myParams, 0);

Categories

Resources