basically I want a Jquery function to call a PHP script multiple times, and every single time, load the response into a div, this is the code I have now:
images = 10;
while(images > 0)
{
$.ajax({
type: "POST",
url: "processimage.php",
data: { image : 1 },
async: false,
success: function(data) {
$( "#logger" ).append(data+ '<br />');
}
});
images--;
}
What this code is doing is processing all the images and then appending the full response, but I want it to append the response for every single image. Somehow the while block is entirely being processed before updating the #logger div. Am I missing something?
you must remove the async: false. which in turn allows the requests to complete and be appended as they finish. However, you'll then realize that they are being appended out of order! to fix that, we can use promise objects and .then.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: images
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
images--;
}
Now, there's still one more possible issue. if you needed to pass the current value of images with each request, the previous code will send all requests after the first with the last value of images. To fix that, we can use an iffe.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
(function(i){
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: i
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
})(images);
images--;
}
And then you can make it DRYer as suggested below by storing the options in a separate variable:
images = 10;
var ajaxOpts = {
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
};
var req = $.ajax(ajaxOpts);
images--;
while (images > 0) {
(function(i){
req.then(function(){
ajaxOpts.data.image = i;
return $.ajax(ajaxOpts);
});
})(images);
images--;
}
Related
I'm new to JavaScript and jQuery. I'm currenly having the following code in my javascript file, however it doesn't seem to be working. I'm using this from prototype.js :
var url = '/sip/TnsViewScreenResponse';
var myAjax = new Ajax.Request(url, {
method: "post",
headers:{
'X-Requested-By': 'XMLHttpRequest'
},
parameters: "tin=" + tin,
success: function transResult(response) {
document.getElementById('tinVersionsOf_' + tin).innerHTML
= response.responseText;
document.getElementById('ajax_loading_img').style.display
= 'none';
document.getElementById('tinVersionsOf_' + tin).style.display =
'block';
},
error: function transResult(response) {
document.getElementById('ajax_loading_img').style.display = 'none';
alert('Failure: Problem in fetching the Data');
},
}
);
return false;
This seems to be conflicting with the other jQuery files being used in the file, so I want to convert this to plain JavaScript or jQuery. I have tried the below but it doesn't seem to be working. How can I make this right ?
var url = '/sip/TnsViewScreenResponse';
var myAjax = $.ajax({
type: "POST",
url: url,
data: tin,
success: function transResult(response) {
$('#tinVersionsOf_' + tin).html(response.responseText);
$('ajax_loading_img').css("display","none") ;
$('#tinVersionsOf_' + tin).css("display","block");
},
error: function transResult(response) {
$('#ajax_loading_img').hide();
alert('Failure: Problem in fetching the Data');
},
}
});
The above code is getting skipped while being parsed in the browser, which I had checked with inspect element option in Google chrome.
Try This
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/sip/TnsViewScreenResponse",
data: JSON.stringify({ mydata: tin }),//where tin is ur data
success: function (result) {
//include your stuff
},
error:function(error)
{
// include your stuff
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to get the following code to send variables to a PHP page via POST. I am not quite sure how to do it. This is my code sending data via GET and receiving it via JSON encoding. What do I need to change to pass variables to process_parts.php via POST?
function imagething(){
var done = false,
offset = 0,
limit = 20;
if(!done) {
var url = "process_parts.php?offset=" + offset + "&limit=" + limit;
$.ajax({
//async: false, defaults to async
url: url
}).done(function(response) {
if (response.processed !== limit) {
// asked to process 20, only processed <=19 - there aren't any more
done = true;
}
offset += response.processed;
$("#mybox").html("<span class=\"color_blue\">Processed a total of " + offset + " parts.</span>");
alert(response.table_row);
console.log(response);
imagething(); //<--------------------------recursive call
}).fail(function(jqXHR, textStatus) {
$("#mybox").html("Error after processing " + offset + " parts. Error: " + textStatus);
done = true;
});
}
}
imagething();
The default method is GET, to change that, use the type parameter. You can also provide your querystring properties as an object so that they are not immediately obvious in the URL:
var url = "process_parts.php";
$.ajax({
url: url,
type: 'POST',
data: {
offset: offset,
limit: limit
}
}).done(function() {
// rest of your code...
});
Try This
$.ajax({
url: "URL",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(ty),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
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;
}
}
});
});
In the following JavaScript code I repeatedly make AJAX calls to my FastCGI module to query some values. At some point the code terminates when the data variable for the div2 case is not 0 but contains the value that should go into div1 while the div1 displays the value that was supposed to go into div2.
I am using the Chromium Browser (14.0.835.202 (Developer Build 103287 Linux) Ubuntu 10.10) but it also happens with FireFox. I also tried using the XMLHttpRequest object alone and I got the same results.
How can this be and how can this be solved?
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
}
});
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
Maybe try have them sequential:
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
});
}
If your requirements allows, try this:
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
});
}
Try to execute the calls synchronously by adding the async=false option.
Hi how do i go about loading up my javascript files after an ajax call has been made, reason being it seems once i click submit, some javascript functions do not end up working. I tried using "$getscript" however it was a bit buggy especially in google chrome? This is what my call looks like;
function InsertStatus() {
var fStatus1 = document.getElementById('<%=txtStatus.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebServices/UserList.asmx/InsertUserStatus",
data: "{ 'fStatus': '" + fStatus1 + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d == "Successful") {
$("#col-3").load(location.href + " #col-3>*", "");
$.getScript('scripts/script.js', function () {
});
}
else {
alert("its false");
$.getScript('scripts/script.js', function () {
});
}
}
});
};
Replace $.getScript('scripts/script.js', function () {});
With:
$.ajax({
dataType: 'script',
url: 'scripts/script.js',
crossDomain:true,
success: function(response)
{
//Whatever
}
});