.ajaxComplete not working - javascript

Hi i currently having a problem with firing .ajaxComplete function, whereby it should be working on a demo site. I'm refer to this function from here http://www.bitrepository.com/a-simple-ajax-username-availability-checker.html
Here are my code :
<SCRIPT type="text/javascript">
<!--
/*
Credits: Bit Repository
Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html
*/
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#userID").change(function() {
var usr = $("#userID").val();
if(usr.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check.php",
data: "userID="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == "OK")
{
$("#userID").removeClass('object_error'); // if necessary
$("#userID").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
}
});
});
//-->
</SCRIPT>
I had try to alert the msg , the check.php able to return back the msg value, but it stop on the .ajaxComplete() there where it does not trigger the function after the .ajaxComplete(). Please guide me through this. Thanks

From the document
As of jQuery 1.8, the .ajaxComplete() method should only be attached
to document.
So
$(document).ajaxComplete(function(event, request, settings){
});
But in your code, there is no need to use ajaxComplete, the success callback will be called only when the ajax call is finished, so you can just check the value of msg directly in it.
$.ajax({
type: "POST",
url: "check.php",
data: "userID=" + usr,
success: function (msg) {
if (msg == "OK") {
$("#userID").removeClass('object_error'); // if necessary
$("#userID").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
} else {
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
$(this).html(msg);
}
}
});

Related

Ajax not working properly

Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.

if and else not working, always showing the same window

I have a problem with my html webpage, I am trying to use a code to show determinate window's login, the problem is no matter what statement(if-else, if-if, or other) I use...always display the same window (mean always display the window I coded on deslogeado.php, I can't make display the window coded on logeado.php).
Some details: msg is an string which can bring the word 'cero'(here will display a window to user can login) or other word (here will display a window where user is already logged).
<script type="text/javascript">
$(document).ready(function()
{
var flag = 'cero';
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
console.log(msg);
if(msg === flag)
$('#apDiv7').load('deslogeado.php');
if(msg !== flag)
$('#apDiv7').load('logeado.php');
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
var flag = 'cero';
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
tipo=typeof msg;
console.log(msg,flag);
if(msg == flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "getSesion.php",
success: function(data)
{
var flag='cero';
console.log(data,flag);
if(data === flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
}
})
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({ url: "getSesion.php", dataType: "json" }).done(function(data)
{
if(data.message == flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
});
});
</script>
Tried with 1,2 and 3 equal on if, I don't know if an html attribute problem or what. I really hope someone can help me! My regards!
When sending data via ajax in the future, consider formatting it with JSON, which will alleviate the ambiguity of free text (with possible spaces before/after).
You are using AJAX which is asynchronous. You should use the "success" callback, or the done() method of the Deferred Ajax call.
$.ajax({ url: "getSesion.php", dataType: "json" }).done(function(data) {
if(data.message == flag) {
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
});
Your php script should return a json formatted object like:
{ "message":"cero" }

Limiting search results Javascript

I was wondering how to limit the search result in the Javascript file, my JS file details as following:
/* JS File */
<script>
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
</script
I just need to add similar to following code to be able to load a loading images before the result and limit the results into five or whatever, and if possible add load more later.
<script>
function loadSearch(query) {
document.body.style.overflow='hidden';
if (typeof xhr != "undefined") {
xhr.abort();
clearTimeout(timeout);
}
if (query.length >= 3) {
timeout = setTimeout(function () {
$('#moreResults').slideDown(300);
$('#search_results').slideDown(500).html('<br /><p align="center"><img src="http://www.tektontools.com/images/loading.gif"></p>');
xhr = $.ajax({
url: 'http://www.tektontools.com/search_results.inc.php?query='+encodeURIComponent(query),
success: function(data) {
$("#search_results").html(data);
}
});
}, 500);
} else {
unloadSearch();
}
}
function unloadSearch() {
document.body.style.overflow='';
$('#search_results').delay(100).slideUp(300);
$('#moreResults').delay(100).slideUp(300);
}
</script>
I have got the 2nd code from another template page, and I am just failing to adjust it to fit my search template (1st code), I'd appreciate it if someone could help me to adjust it, thanks a lot.
If you want to do this on the javascript side, you can use slice.
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html.slice(0, 5);
}
});
I would personally suggest that you do the limiting of rows on the server side to minimize the amount of data you transfer between the client and the server.

jQuery - Resume form submit after ajax call

Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?
At the moment it gets to the success bit but it doesn't resubmit the form which should submit and redirect the user to the http://example.com website.
Thank you very much for any help in advance
If it's not possible to do it this way, is there another way of getting it to work?
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit(); // mistake: changed $(this) to $('form') - Problem still persists though it does not resubmit and redirect to http://example.com
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
Edit:
Stackoverflow posts checked out for the code below:
Resume form submission after $.ajax call
How to reenable event.preventDefault?
I just thought I'd mention I have also tried this code without avail.
var ajaxSent = false;
$(document).ready(function() {
$('form').submit(function(e) {
if ( !ajaxSent)
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
alert('submit form');
ajaxSent = true;
$('form').attr('action', 'http://example.com');
$('form').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
I have also tried this code without any luck as well.
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
Solution was quite simple and involved adding and setting async to false in .ajax(). In addition, I have re-worked the code to work of the submit button instead which submits the form when the AJAX passes successfully.
Here is my working code:
$(document).ready(function() {
var testing = false;
$('#btn-login').on('click', function() {
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
async: false,
success: function(data) {
if (data == 'true')
{
testing = true;
$('form').attr('action', 'https://example.com');
$('form').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
return testing;
});
});
It's no good practice to reselect all form tags throughout your code, what if you have multiple forms on the page?
Also you'd better use .on() and .off() with jQuery.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
// cache the current form so you make sure to only have data from this one
var form = this,
$form = $(form);
$.ajax({
url: form.action,
type: form.method,
data: $form.serialize(),
success: function(data) {
if (data == 'true')
{
$form.attr('action', 'http://example.com').off('submit').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
In one line you use $('form') to select the form to change its action, but then you use $(this) to try to select that same form. I would guess that this inside the callback function isn't what you expect it to be, and is something other than your form (possibly the window object).
Just chain the calls:
$('form').attr('action', 'http://example.com').unbind('submit').submit();

Returning from a nested function in javascript

I'm trying to make a function that uses jquery's ajaxfunction to get some info from my ajax.php file.
code:
function ajaxIt(dataLine){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
console.log("[AjaxIt]: "+dataLine+" returned "+msg);
return msg;
}
});
}
if(ajaxIt("action=loggedIn")=="1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
The problem is that I can't get the success function to return all the way to the ajaxIt function. Could anyone shed some light onto how I could do something like that?
Thanks.
You need to invoke a callback function to process data that way:
function ajaxIt(dataLine, cb){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
if($.isFunction(cb))
cb.apply(null, [msg]);
}
});
}
ajaxIt("action=loggedIn", function(data){
if(data === "1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
});
$.ajax is asynchronous. This means that it will return right away, instead of waiting for the AJAX query to execute and retrieve a result from the server. By the time the message from the server arrives, your ajaxIt function has already finished working.
What you should use here is a continuation-passing style. Provide ajaxIt with a continuation: a function that explains what should be done once ajaxIt has finished working.
function ajaxIt(data, continuation) {
data.ajax = true;
$.post("ajax;php", data, function(msg) {
console.log("[AjaxIt]: returned "+msg);
continuation(msg);
});
}
ajaxIt({action:"logged-in"}, function(result) {
if (result == "1") {
console.log("Logged In");
loggedIn=true;
initiate2();
}
});

Categories