How to show Loading message instantly while using jquery ajax? - php

Below is my Ajax code I have made using jQuery Ajax method.
$(".loading_msg").show();
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
success: function(result){
if(result=='Success'){
$("#msgContainer").html('<div style="color:#3CA322;font-weight:bold;font-size:14px;padding:10px;">Thank you.</div>');
$("#msgContainer").fadeIn();
}
else{
$("#msgContainer").html('<div style="color:red;font-size:12px;padding:10px;">' + result + '</div>');
$("#msgContainer").fadeIn();
}
},
error: function(){
//console.log('error');
},
complete: function(){
//console.log('complete');
$(".loading_msg").hide();
$("#submit").attr("disabled", false);
}
});
So the logic is, whenever the Ajax request is about to made,
the .login_msg container is displayed first
then ajax call made
and when it is completed, again the .loading_msg is hidden.
Now the problem, it is not working smoothly as it should be. So when the ajax call is made, the browser hangs for a seconds but it doesn't show the loading message. But when the request is completed, the login message appears like for half a second and then it goes away as I have set it hidden on request completion.
So I want that the .login_msg should be shown before the request is made.
Any suggestions for this? Thanks in advance.

try using beforeSend and complete settings of $.ajax:
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
beforeSend:function(){
$(".loading_msg").show();
}
complete:function(){
$(".loading_msg").hide();
}
....
....
});

Related

Block ajax script execution before the previous call succeeded

I have a button that executes an ajax function.
Sometimes the server lags so maybe an user presses it more times, thinking the first time it didn't work...
The main ajax function looks like this:
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data:"data=data",
success: function(){
ajax2();
ajax3();
}
});
Since that ajax function updates db and makes others 2 ajax functions i need to block the button from remake the main ajax func...
Only when ajax2() and ajax3() are finished, the button, if pressed, must remake the ajax function.
Hope to have explained well my problem!
disable the button and then reenable it when the 2 ajax are finished
/// the click event
$('yourbutton').prop("disabled",true);
/// show a loading or something....
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data:"data=data",
success: function(){
var ajax1 = ajax2();
var ajax2 = ajax3();
$.when(ajax1,ajax2).done(function(risp1,risp2){
console.log(risp1,risp2);
$('yourbutton').prop("disabled",false);
/// hide the loading
});
}
});
read this for more info
Try this
//before this ajax call disable button
$.ajax({
type: "POST",
url: "page.php",
dataType: "html",
data: "data=data",
success: makeAjaxCalls
});
function makeAjaxCalls() {
var a1 = ajax2();
var a2 = ajax3();
$.when(a1, a2).done(function () {
//enable your button here
});
}
Unbind the event listener when it's activated the first time :
custom_ajax_handler = function(){
$('#mybutton').unbind('click'); //won't intercept event from now on.
//here is your ajax call.
ajax2();
ajax3();
}
$('#mybutton').click(custom_ajax_handler);
Then in ajax3 success rebind it :
success : function(){
$('#mybutton').click(custom_ajax_handler);
}
Note that you probably shouldn't make that much ajax calls.
Or at least that doing so won't help your server with its lags.

Ajax submit not working

I'll make it easy, I want to submit data without using a form, etc, etc, etc...
I have this code:
HTML
<span class="categ-edit">Edit</span>
<span class="categ-add">Add</span>
<span class="categ-delete">Delete</span>
JQUERY
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
});
window.location.href = "categoryactions.php";
});
$('.categ-add').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'add'},
});
window.location.href = "categoryactions.php";
});
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
});
window.location.href = "categoryactions.php";
});
And in categoryactions.php I have this:
PHP
<?php
$action = $_POST['action'];
echo $action;
?>
But when it redirects me to categoryactions.php I get nothing. I'm not sure if that's the way to submit data with AJAX but at least I tried. If someone knows how to fix this, I'll be grateful!
You click handler is making two separate requests. First, you are sending a request with AJAX, then you are going to the page. When you look at the page, you won't see the result because the result was given to the AJAX request.
The point of AJAX is to avoid changing the page.
Try this:
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
success: function(data) {
alert(data);
}
});
});
You are actually calling "categoryactions.php" twice. First as an asynchronous call (ajax) and the second time as a redirect: window.location.href = "categoryactions.php";
In the 2nd call, nothing is being posted so your output is empty. This line does not serve any purpose - you should remove it.
The ajax call happens in the background so you won't see the output from the echo in the browser. if you really want to verify it is working, replace the echo with a file call to write it to a file. Then check the file contents.
Using redirection with Ajax doesn't make sense. You need to use the success method.
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
success: function(data){
alert(data);
//or, put response in a div
$('#someDivId').html(data);
}
});
});
The point of Ajax is to retrieve the response from a request to another page without changing the URL in the address bar. It retrieves the response for you in the variable that is the input to your success method, and then you do something with that.
Example AJAX with PHP
I can't exactly answer your question, but I will help you understand ajax requests to http server and how to handle responses accordingly.
Sample jQuery
$('.categ-edit').click(function() {
$.get('/path/to/file.php', function(data) {
console.log(data);
});
});
Sample file.php
<?php
echo json_encode('HELLO');

Ajax program is not running as I expect

Ajax program is not running as I expect. See the code
$(document).ready(function(){
$("input").keyup(function() {
for(var i=400;i<421;i++){
(function(counter){
counter=String(counter);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
}
});
})(i);
}
alert("hai");
});});
In this code I want to show the alert after completing all Ajax request which is in that for loop. But when I run this code alert is showing first. I'm new to Ajax please can anyone help me to run as I expected.
Ajax is Asynchronous which means, it will continue running the code in parallel. The success function is called after the Ajax request is complete. What you can do is this:
$(document).ready(function(){
$("input").keyup(function() {
var loopsToDo = 20, done=0;
for(var i=400;i<421;i++){
var counter=String(i);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
},
complete : function(){
done++;
if( done == loopsToDo)
{
alert("DONE")
}
}
});
}
});});
Your code is weird. Why does it go
for(var i=400;i<421;i++)
Also, the alert will display first before any of the Ajax calls, because ajax is Asynchronous, meaning it runs seperately to the rest of the code. Since you are running 20 Ajax requests, the alert does not wait for all 20 to complete. What you need to do is keep a count of the Ajax calls in your success part and when that equals 20 then display an alert.
Because AJAX calls are asynchronous, it will set up the AJAX call, then continue to execute the script. The 'success' parameter specifies the callback to use once a response is received - which could happen at any time (hence, asynchronous).
$(document).ready(function(){
$("input").keyup(function() {
for(var i=400;i<421;i++){
(function(counter){
counter=String(counter);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
alert("hai");
}
});
})(i);
}
});
});
That should solve your problems.

Difficulty displaying error message using AJAX jQuery API and PHP.

I'm using the jQuery AJAX function in order to retrieve data from my mySQL database without having to refresh the page. I have everything in working order, my query's are retrieving the correct data from my database. However, I am struggling to echo out an error message when no data can be retrieved based on the users input. I have a php file that provides the user interface for the user to search from, it also contains the following Scripts in the document head. Here is what I have so far:-
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpvalue= $('#users').val();
});
});
</script>
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
}
});
});
});
</script>
Any help would be greatly appreciated, sorry if I haven't explained myself very well.
Thankyou.
Modify your .ajax() call so you can detect error conditions:
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
This is just to get you started: see http://api.jquery.com/jQuery.ajax/ for more details on what you can do with the error handler.
Of course, it's possible that you're getting a good HTTP status from the call, but this defensive programming will make sure.
A tool like Firebug running in your browser can also help you detect bad HTTP status code returns.
In data.php you have to output the error when the data is invalid.
The error setting for $.ajax will only get called if the actual ajax request has a problem like if the server returns a 404. You would have to return an error in your json and check for it like this:
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
if(!data.error) {
$('#output_div').html(data);
}
else {
// show error
}
}
});
});
And then you would return your normal json when the data is fine and then something like this for the error:
{"error": "Oh NOES!"}

Calling AJAX from jQuery and displaying a waiting message

I'm very new at AJAX calls from jQuery and I'm a bit stuck trying do to this; I have an AJAX call from jQuery like this:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {//the_output_here}});
});
});
This script is inside a web page triggered when the user hits a particular row (<tr></tr>) from a table. stats-render.php outputs HTML text with some info and graphics. This answer some times takes a while (15 seconds), so I would like to show the user a waiting message when he/she triggers the script and when the call returns an answer show the output text in a div (lets call it <div id="render-div">).
So the questions are, how can I show a waiting message? If you know a good script for showing this in a modal, I would appreciate it.
How can I output the result from stats-render.php into a div?. Thank you so munch for any help!
Just display a loading message in the div where the results go in the interim.
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) { $('div.for-results').html( /* d... */ ); });
$('div.for-results').html('loading...');
});
});
Or for even more fun:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
clearInterval(loading);
$('div.for-results').html( /* d... */ );
});
$('div.for-results').html('loading');
var loading = setInterval(function() { $('div.for-results')[0].innerHTML += '.' }, 1000);
});
});
The easiest option is probably to check out the jquery-loading plugin.
I just do a simple show the message before the call, and hide it on the success callback like this:
However I think jquery might have a callback option when the ajax call starts, and when it stops.
$(document).ready(function() {
$('tr.table-row').click(function(){
//Show the loading message, or chage a css class, or what have you.
$('#loadingmessagetext').show();
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
//Hide the loading message
$('#loadingmessagetext').hide();
//the_output_here
}
});
});
});

Categories