Call the ajax function again after Complete function - javascript

I'm trying to re-execute the function with other parameter in the complete callback, but it isn't working as I want. It works well at the first call, but when I call it again, it only alerts the test alert twice and doesn't execute the function again. My intention is to execute the function with another parameter,that is the id of the element every time that the user click on the element. I appreciate if anyone could help me, what should I do? Thanks. =)
jQuery(function($){
var load_pages = function($page){
$.ajax({
type : "POST",
data : {page_name : $page},
dataType : "html",
url : "http://localhost/includes/loadpages.php",
beforeSend : function(){
$("#content").addClass("hide");
if($page.substr(0,9) == "categoria"){
$("#content").removeClass("hide");
$("#the-portfolio").remove();
}
},
success : function(data){
$data = $(data);
if($data.length){
if($page == 'lista_portfolio'){
$(".submenu").append($data);
$(".submenu").append('<div class="end"></div>');
}
else{
if(!$("#content") == false){
$("#wrapper").append('<div id="content"></div>');
}
$("#content").append($data);
$(".foot").animate({bottom: 0},700,'easeOutExpo');
$data.fadeIn(500);
}
}
},
error : function(jqXHR, textStatus, errorThrown) {
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
},
complete : function() {
$("#portfolio_categories_list li a").click(function(){
alert("test");
$categoria = $(this).attr("title").split("Ver todos os posts arquivados em ");
load_pages("categoria"+$categoria[1]);
return false;
});
}
});
}// end load_pages
});

Try not to call load_pages() on complete because it causes a Recursive function which can make you run out of memory.
Instead, call your function out of the $.ajax and then by binding the event click, like this.
$(document).on("click","#portfolio_categories_list li > a",function(e){
e.preventDefault();
alert("test");
$categoria = $(this).attr("title").split("Ver todos os posts arquivados em ");
load_pages("categoria"+$categoria[1]);
});

Did not see why you adding the event handler in complete callback, bind the event after you append the element to the dom in success callback should work well. And please provide some console/XHR requests output to help check your problem, put more console log instead of alert will help to track the problem

Related

Show ajax process 1 by 1 when something is done

I have a code and it works, and it shows all notifications at the same time.
I have question..
How to get notifications when one of the functions is done? (Notifications appear one by one)
There are several functions in the indexing.php file.
$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
buatindex();
hitungbobot();
panjangvektor();
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
In index.php there is a code to call that function
<script type="text/javascript">
function preproses(){
var preprosesx = "preproses";
$.ajax({
type : "POST",
url : "indexing.php",
data: {preproses:preprosesx},
error: function(){
$("#notif").prepend("fail");
},
success: function(html){
$("#notif").prepend("Process done <br/>"+html);
},
});
return false;
}
</script>
click to precess
If all processes are completed, a notification will appear
<span id="notif"></span>
$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
setTimeout(function(){ buatindex() }, 3000);
setTimeout(function(){ hitungbobot() }, 3000);
setTimeout(function(){ panjangvektor() }, 3000);
console.log("Completed all");
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
Also you can console.log in ajax success response.
Something Like this : JsFiddle Example
count your post parameter ($_POST["preproses"]) and keep into an javascript variable like var count = ""; . you can also take an hidden text variable which will be increase by 1 after every notification send. after all notification values send this hidden variable will be equal to the count variable. then you can be sure that all the notifications have been sent. Hope this will work for you..:)
Haven't you tried async: false yet? This will stop further processing until one ajax request is complete.

Google Recaptcha Ajax response strange checking order

I am making my registration page for my service. I need to check either Google's Recaptcha successfully verified or not. I decided to use an jquery.ajax.
I have created a function "checkCaptcha()" which sets isCAPT (if captcha valid or not) either true (FLD_VALID) or not (FLD_EMPTY):
function checkCaptcha() {
alert("1");
var captcha_response_text = grecaptcha.getResponse();
var request = $.ajax({
url: "ajax/registrationA.php",
type: "post",
data: { captcha: true, captcha_response: captcha_response_text }
});
request.done(function (response, textStatus, jqXHR) {
alert("2");
if(response) {
isCAPT = FLD_VALID;
}
else {
isCAPT = FLD_EMPTY;
}
});
}
I have to say that "registrationA.php" works fine. No problems there.
After this function, I am checking my submit button handling "onclick" event:
apply_button.onclick = function () {
checkCaptcha();
alert("3");
//alert("Капча " + isCAPT + " Логин " + isLOGIN + " Почта " + isMAIL + " Пароль " + isPASS + " Соответствие " + isPAS2);
return false;
};
You can see three "alert(...)" operators. The problem is that when I press submit button (apply_button) I get three alerts: 1, 3, 2. How can I fix this problem. I need to wait until "requiest.done" executes and only than go to "alert("3")". It is essential because now this function checks fields before checking captcha state which leads to an error because in this case isCAPT equals false.
Please help me with this problem. Maybe there is a better way to check if captcha verified or not (maybe there is a function like "grecaptcha.isVerified").
You need to check deferred.promise() method to work with asynchronous data. Check JQ documentation for that. In a few words it does exactly what you need. It allows to wait until the 2nd asynchronous request is finished and starts the 3d function.

Ajax post working but not callback message in Android browser

im implementing sign up with ajax on my site its working perfectly on desktop but causing problem in Android Browser The problem is after i click on signup button in android browser it post data to database but do not replace the html message.And alert native code error.
function postdata(){
var chkfrm = checkdata();
if(chkfrm == 0){
var url = '<?php echo base_url();?>index.php/Signup/signin';
$.ajax({
type: "POST",
url: url,
data: $("#formI").serialize(), // serializes the form's elements.
beforeSend:function(){
$("#signupdiv").html('<h1>Loadinng...........</h1>');
},
success:function(data)
{
$("#signupdiv").html(data);
},
error:function () {
alert(console.log);
}
});
e.preventDefault();
}
else {
$("#msgjava").html('<p>We need a little bit information from you.Please fill it.</p>');
return false;
}
You can't do e.preventDefault(); where you are because e is not passed into this function (thus it is undefined). This will cause an error and stop JS execution.
In what you posted, you are also missing a closing brace at the end of the postdata() function.
Your alert says "native code" because that's what this line of code:
alert(console.log)
will do. console.log is a native function so alerting a native function won't do anything useful. You need to make that alert a lot more useful. To see in more detail what error is coming back from the ajax function, change your error handler to something like this:
error: function(jqXHR, textStatus, errorThrown) {
alert("status = " + textStatus + ", errorThrown = " + errorThrown);
}
And, then see what it says.

$.ajax not working first time

I have a button in html page.
<input type="image" src="images/login_button.png" id="imageButton" onclick="LoginButtonClick();" />
I am calling this method on button click:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
alert ("Inside Ajax."); // This alert not executing first 1 or 2 times.
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
}
});
}
As I mentioned above $.ajax not working first 2 , 3 button click attempts.
In mozilla it throws an error "[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: JQuery.js :: :: line 20" data: no]"
Is there any way to fix this issues..
I'm not sure why it is executing later. But here's the deal--you're placing the alert in the object literal that defines the parameters for the .ajax method. It doesn't belong there. Try putting the alert in your success and/or error handlers.
UPDATE
How long are you waiting? When you initiate an ajax request, it isn't going to hang the UI. It could be that you're seeing the result of the first click on your 3rd or 4th attempt and think that you're triggering it on that 3rd or 4th attempt.
The $.ajax() function receives as a parameter a set of key/value pairs that configure the Ajax request. I don't think that the syntax will be correct by placing the alert() in there.
Note - entering an absolute path isnt going to work if the domain is not the current one - it is against the Same Origin Policy that browsers adhere too - this might explain why nothing happens when its executed - i suggest you look in your browser debugger to verify.
You should be binding the click event like this :
$(document).ready(function() {
$('#imageButton').click(function() {
// code here
});
});
so your complete code will look like this :
HTML
<input type="image" src="images/login_button.png" id="imageButton" />
JavaScript
$(document).ready(function () {
$('#imageButton').click(function () {
alert("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function (response, status, xhr) {
if (response != "") {
alert("Response receive ");
} else {
alert("Invalid Data.");
}
}
});
});
});
I have removed the alert ("Inside Ajax."); line as this will not be executed - you pass an object {} of parameters not code to execute. If you want to execute before the ajax request is sent do this :
$.ajax({
beforeSend: function() {
alert('inside ajax');
}
// other options here
});
Docs for the $.ajax() function are here
I agree that you have the second alert in the wrong place, and dont know what pmamml.ajaxError function is but may be your call returns with error and therefore your success alerts are not firing. You can check with error and complete functions as follows:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown){
alert ("ajax call returns error: " + errorThrown);
},
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
},
complete:function(jqXHR, textStatus){
alert('completed with either success or fail');
}
});
}
You can test with Google Chrome's Developer tools -> Network tab, if a request is made and returned (https://developers.google.com/chrome-developer-tools/docs/network)

How to check if javascript function is ready/done (jQuery)

I am working on a learning planner which gets its data (languagekeys, tasks, activities, etc.) from a database. Because I need a JSON string, I encode it with json_encode to work with it in JavaScript.
I have a different function (for keys, tasks, activities, etc.) which gets this data and writes it into an array.
function get_tasks(start_date,end_date){
maxsubtasks=0;
maxtasks=0;
$.getJSON(json_data+"?t_startdate="+start_date+"&t_enddate="+end_date, function(data) {
tasks=new Array();
$.each(data.tasks, function(i,item){
tasks[i]= new Object();
tasks[i]["t_id"]=item.t_id;
tasks[i]["t_title"]=item.t_title;
tasks[i]["t_content"]=item.t_content;
. . .
if ( i > data.tasks.length) return false;
maxtasks = data.tasks.length;
if(item.t_parent > 0){
maxsubtasks++;
}
});
});
return true;
}
Everything is working just fine. I need some help, because I now have to call this function in $(document).ready(). I want to build my learning planner only once the function get_tasks() is complete (the array is filled with data). Otherwise, I will get errors.
How can this be solved?
Here is what I have in $(document).ready():
if(get_tasks(first_day,last_day) && get_tmp_data()){ // If this function is done
// This function should be fired -- just like a callback in jQuery
init_learnplanner();
}
You can add a callback to the function:
function get_tasks(start_date, end_date, callback) {
Then after populating the array in the function, call the callback function:
if (callback) callback();
Now you can use the callback parameter to initialise the learning planner:
get_tasks(first_day, last_day, function() {
init_learnplanner();
});
You should be able to specify a callback in $.getJSON, which gets executed as soon the request is completed.
EDIT:
You're already doing this, but why don't you just call the second code block from the end of the callback funciton in $.getJSON?
Other answers haven't worked for me because I have 5 functions which use my data with $.getJSON, and I need to have collected all information to even start init_learnplanner().
After several hours of searching, I've discovered the jQuery function ajaxComplete, which works like a charm for me. jQuery tracks all ajax calls that have been fired and triggers anything assigned .ajaxComplete() when one is complete.
What I'm doing is usually something like this:
simple, looks like beginner but it works :) :D
<script type="text/javascript">
var isBusy = true;
$(document).ready(function () {
// do your stuff here
isBusy = false;
});
function exampleajax() {
if(isBusy) return false;
isBusy=true;
$.ajax({
async: true,
type: 'POST',
url: "???.asp",
dataType: "jsonp",
data: qs,
error: function(xhr, ajaxOptions, thrownError){
//console.log(xhr.responseText + " AJAX - error() " + xhr.statusText + " - " + thrownError);
},
beforeSend: function(){
//console.log( "AJAX - beforeSend()" );
},
complete: function(){
//console.log( "AJAX - complete()" );
isBusy = false;
},
success: function(json){
//console.log("json");
}
});
}
</script>
hope this help you

Categories