Where am i going wrong - ajax - php

I have the following link-
Grab Coupon
Where i have initialized $var3 like this
$var3 = "brand1,camp2";
The code for the function popitup2() is -
<script language="javascript" type="text/javascript">
function popitup2(id) {
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
success: function(){
alert( "Data Saved: " );
}
});
newwindow2=window.open('','name','height=225,width=350');
var tmp = newwindow2.document;
....some more code...
...at end...
return true;
}
</script>
Now when i click the link ex.com opens up without any alert i.e without running the php script through ajax and the javascript after that. If i remove the ajax call from the function popitup2() then the remaining javascript gets executed correctly.

Agree with previous answer that you are executing asynchronous Ajax request.
From documentation Async parameter may not work in 2 cases: Cross-domain requests or if dataType: "jsonp".
If you are doing crossdomain request, I can suggest only:
Grab Coupon
<script type="text/javascript">
function popitup2(id, link) {
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
context: link,
success: function(){
alert( "Data Saved: " );
window.location = $(this).attr("href");
}
....
return false;
});
With such approach we track clicking for sure.
There is another problem with such approaches, that tracking server should be fast otherwise, user will wait long time till navigate to resource.

What's happening here is that you're performing an asynchronous AJAX request, meaning that when you perform the request, the rest of your function continues to run. When the AJAX result comes back, it then fires the alert in your success function, but since you've clicked a link, you've navigated away from that page already.
Try adding an async: false to the ajax function's parameters to wait for the result to come back before continuing, like so:
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
async: false,
success: function() {
alert( "Data Saved: ");
}
});

You are passing two arguments to JS function. But function prototype (first line) accept only one. This lead into JS error.

Related

continue jQuery after mysql data has loaded

I am using jquery and php along with WordPress to access data from a mysql database.
I managed to retrieve that data but would like jquery to wait until all the data has been retrieved.
Below is the pertinent code segment.
Both alert commands display nothing because the data has not finished loading.
How can I re-code this?
jQuery(document).ready(function ($) {
load_qs('foo');
alert($(".all-qa-free").val());
//////////////////////////////////////////////////////////////////////////
function load_qs(data) {
var data = {
action: 'load_question_set',
async: false,
cache: false,
qset_id: data
};
$.post(the_ajax_script.ajaxurl, data, function (response) {
var mydb_data = $.parseJSON(response);
$("#all-qa").val(mydb_data.qa);
alert($(".all-qa-free").val());
return;
});
}
});
Ajax calls are asynchronous, while the JS executes synchronously. jQuery/JavaScript initiates the ajax calls and immediately goes to the next line for executing. It doesn't wait for the response to come from the server.
Solution:
Do all the processing, which you want to do on server response in the callback function itself. In your case, in the below function:
function(response) {
var mydb_data = $.parseJSON(response);
$("#all-qa").val(mydb_data.qa);
alert ($(".all-qa-free").val());
return;
}
Otherwise you will keep facing this issue. Try putting alert in the callback function. It'll definitely work.
One more thing, you are putting value in id "#all-qa" and fetching data from ".all-qa-free", please check if you are doing this right.
--
HappyCoding
You should set async: true in your ajax call.
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
If you set async: true then that statement will begin it's execution and next statement will be called regardless of whether the async statement has completed yet.

How can make sure code after my ajax request only runs if the request was a success?

I have a link, delete, that removes an item from an array, and then removes a row from a table on my html page.
It runs the ajax request first to amend the array, then removes the row. If for some reason the ajax request was to fail then the html table row would still be deleted I think.
Is there a way to make sure subsequent code afer the ajax request only runs if it is successful? I tried moving it into the success function but then it didn't run at all..
This is how I have it set up at the moment...
$(document).ready(function () { //delete
$(document).on("click", "a[class='del']", function () {
var ID = $(this).attr("id"); //<----- get the ID of the column
$.ajax({
//contentType: "text",
url: 'proDel.php', //the url you are sending datas to which will again send the result
type: 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data: 'val1=' + ID, //Data you are sending
success: function (data) {
// do nothing, array was amended in php file
}
})
//Code here that deletes the table row(runs whether the array was changed or not!!
})
})
The problem might be that you are not returning valid JSON.
You were correct in thinking that you should move the code that deletes the table row into the success callback. You say you tried that, but the success callback was not executed.
Since you specify dataType: 'json', jQuery will attempt to parse the response body into a JavaScript object (or array or null). If the response body cannot be parsed (because it is not valid JSON), jQuery will call the error callback, rather than the success callback.
An empty response body is not valid JSON. You must at least return "null". Or if you do not plan on returning any data, just change to dataType: 'text'.
Move the code that deletes row to success callback.
$.ajax({
//contentType: "text",
url : 'proDel.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// Code here that deletes the table row
}
});
Try you ajax with success parameter as well as an error to see if there is a problem, hope this helps..
$(document).ready(function (){
$(document).on("click", "a[class='del']", function(){
var elem = $(this); //to make $(this) accessible in you success callback
var ID= elem.attr("id"); // get ID of the column
$.ajax({
url : 'proDel.php', //the url you are sending datas to
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// success, Code here that deletes the table row , do something with 'elem'
},
error: function(x,e) {
//log error if any
console.log("failed with: "+x.status+", e="+e+", response="+x.responseText);
}
});
});
});
Since jQuery 1.5 you may use chainable methods of object returning by jQuery.ajax(). In your case (ensure executing code on ajax request completion) you have to use deferred.always() method. Somehow like this:
$.ajax({
...
})
.always({
//Code here that deletes the table row
})
In earlier jQuery versions you have to use complete option (handler) in jQuery.ajax() for your purpose.
First thing is that when looking at the ajax request success does not mean that the request returned a correct/true value. That just means that there was a response from the other end.
That tripped me up during my first couple times working with and debugging ajax calls.
I don't know if that's part of what is not working for you here, but something to consider.
Secondly, and to answer your real question, you'll have to put a function call in the success branch, else it might never get called, or be called at a non-deterministic time (the whole nature of an asynchronous call).
var a = function(){
$.ajax({
success : function (){
// code here fires if there is a response to your ajax request
// you should put in an function callback here to check the response for
// your success conditions.
// if your conditions are met, make the changes that you need to
b();
}
failure: function() {
// code here fires if the ajax request receives no response
}
})
// any code here will fire immediately after the ajax call is fired.
// it will not wait for the ajax response.
}
var b = function(){
// stuff you want to do according to the ajax response parameters
}

Optimize ajax synchronously calls

I have some ajax script that fire off about 250 synchronous PHP calls . This is my script
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
async:false,
dataType: 'json',
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
In the first part script fetch more than 250 urls from database and for every url script do some php calculation using another ajax call. when the loop ends script do final ajax call.
When i run this programe in firefox, it run successfully for only 40 urls, then browser shows dialog box with option of whether user want to stop this script or not, if user want to run this script then the script run again for next 40 urls , same proccess occure till the end.
How i can optimize this script, i dont want browser show option to stop this script. Please help.
Thanks
Try this:
function nextrequest() {
if (requests.length == 0) {
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
return;
}
var val = requests.pop();
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
var requests = [];
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
dataType: 'json',
success: function(data){
requests = data;
nextrequest();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
success: function(data) {
// do something...
nextrequest();
}
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
});
}
You store all the URLs in a global variable, and everytime a request is done, you get the next one, until all of them are consumed, (requests.length == 0), you call the final request.
This way the user can still do something else on the page, and you can display progress everytime a request is done. Also, a good thing is that you can make 2 calls at once, or more, to make the process faster.
Ajax call needs much time to complete, as it communicates with remote server. The slowest thing there is a query to the server. You should send one batch request with all data needed to the server, that should separate the data and handle it. Everything should be completed about 250 times faster.
make some time interval for each ajax request
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
setTimeout(saveimage(val.url),3000);
}

PHP Multiple Ajax requests: First request block second request

I've got 2 ajax requests on one page. I ran first request and separately start second one. But second one stops working after the first has been run. And continue when first is over.
First requst take long time - something like 30 - 60 seconds and in this time I need second request to show logs what happens with first request. I try to use async: true but it's not help me.
Here it's my code
<script type="text/javascript">
var auto_refresh = setInterval( function()
{ asyncGet('log.php') }, 1000
);
function asyncGet(addr) {
$.ajax({
url: addr,
async: true,
success: function (response) {
$('#loadLog').html(response);
}
});
}
function getConn(addr) {
$.ajax({
url: addr,
async: true,
success: function (response) {
stopGet();
}
});
}
</script>
<div id="loadLog" class="lLog"></div>
and I call first ajax request in this way: getConn('main.php'); from function when press button.
Second request it's running, but not show respons before first request complete.
I wil attach image from firebug.
main.php - is request that take longer time.
log.php - is the logger that is blocked.
Would really appreciate some pointers to where I'm going wrong
This may be a problem with session. Check out this post. Suppose you may need to close session in your main.php as fast as possible.

JQuery Ajax using post - is it blocking?

Is there a way to make jQuery's post method wait for server side code to complete?
In my example below, post is not waiting for my php script to finish. Though php is calling sleep(10), post returns right away, resulting in javascript clearing out the value in #temsg and changing the text of $sendmsg too early.
$('#sendmsg').click(function() {
$("#sendmsg").html("sending....");
var msg = $("#temsg").val();
var to_id = 123;
$.post("http://localhost:8888/ci/index.php/members/addMessage",
{message: msg, tomember: to_id},
function(data){
$("#temsg").val('');
$("#sendmsg").html("Leave Message");
},'json');
$("#infomsg").show();
$("#infomsg").html("Message Sent!");
setTimeout(function() { $("#infomsg").hide('slow'); }, 3000);
});
Ajax is (supposed to be) asynchronous - that means that the $.post() method is non-blocking and returns immediately and the rest of your function continues executing, and then eventually when a response comes back the success handler is called.
You can make the JS code pause until the Ajax request returns by doing a synchronous (blocking) request, but given that (most) browsers run JavaScript on the same thread as the UI that means the browser will not respond to anything until the response comes back which is horrible for the user - essentially the browser would be locked up for the ten seconds that your server-side code is sleeping.
The solution is to stick with the default asynchronous request but move the code from after your $.post() call into the success handler:
$('#sendmsg').click(function() {
$("#sendmsg").html("sending....");
var msg = $("#temsg").val();
var to_id = 123;
$.post("http://localhost:8888/ci/index.php/members/addMessage",
{message: msg, tomember: to_id},
function(data){
$("#temsg").val('');
$("#sendmsg").html("Leave Message");
$("#infomsg").show();
$("#infomsg").html("Message Sent!");
setTimeout(function() { $("#infomsg").hide('slow'); }, 3000);
},'json');
});
Ajax is asynchronous. The fact the code keeps running doesn't mean the sleep didn't occur.
That thread on the server "sleeps" , while javascript continue executing the next lines.
Example how to use async:false:
$.ajax({
url: "http://localhost:8888/ci/index.php/members/addMessage",
async: false,
data: {message: msg, tomember: to_id},
dataType: 'json',
success: function(data){
$("#temsg").val('');
$("#sendmsg").html("Leave Message");
}
});
ajax docs

Categories