I'm loading a part of a page using ajax with this script:
<script type="text/javascript">
$(document).ready(function(){
$('#btn_new').live('click',function(){
var parameter = 1;
$.ajax({
type: "POST",
url: "new_message.php",
data: {
parameter:parameter,
},
success: function(msg)
{
$("#lib_container").ajaxComplete(function(event, request, settings)
{
$("#lib_container").html(msg);
});
}
});
});
});
</script>
Inside the lib_container div I have a text input with this script:
<script type="text/javascript">
function searchUsers(str) {
$.ajax({
type: "POST",
url: "users_ajax.php",
data: {
search:str
},
success: function(msg)
{
//console.log(msg);
//$("#users_lst").html(msg.response);
$("#users_lst").ajaxComplete(function(event, request, settings)
{
$("#users_lst").html(msg);
});
}
});
}
</script>
When I load some text in the input, the second ajax script loads the msg variable in the div but then also reloaded the lib_container div.
I've tried many ways to prevent the lib_container ajax trigger but it was in vain. Just putting the input in new page works correctly.
Can anyone help me solve this?
Thanks.
Your problem seems to be that you are registering a new ajaxComplete handler every time you get a successful response from the ajax call. Since it seems like you want to update the html, I'm not sure why you need those ajaxComplete handlers anyway.
Try it like this:
$(document).ready(function(){
$('#btn_new').live('click',function(){
var parameter = 1;
$.ajax({
type: "POST",
url: "new_message.php",
data: { parameter:parameter },
success: function(msg) {
$("#lib_container").html(msg);
}
});
});
});
And by the same token:
function searchUsers(str) {
$.ajax({
type: "POST",
url: "users_ajax.php",
data: { search:str },
success: function(msg) {
$("#users_lst").html(msg);
}
});
}
On another note, .live is deprecated and you really ought to be using ajax promises rather than a success callback. See the jQuery api for more info on that.
Related
I am now in javascript, I am trying to display a indictor icon when ajax starts and hide it when it finishes, below is my code:
CSS:
div.ajax-progress {
//some setting and url
}
<body>
<div class="ajax-progress"></div>
</body>
Javascript:
$('#fileToUpload').on('change', function(e) {
var file = e.target.files[0];
var formData = new FormData($('form')[0]);
imageId = cornerstoneWADOImageLoader.fileManager.add(file);
$.ajax({
url: 'loadfile.php',
type: 'POST',
data: formData,
async: false,
dataType: 'json',
timeout : 60000,
beforeSend :function(){
$(".ajax-progress").show();
},
success: function (html) {}
$(".ajax-progress").hide();
//doing something}
});
});
but nothing happens, any idea? appreciated.
Maybe if you put $(".ajax-progress").show(); before the call of ajax $.ajax({}); and them hide it in the succes.
I don't know if that's the same to what you have in your code but you commented out the success closing bracket }
you can also use console.log() or alert() to see what's going on in your code.
Try rewriting your ajax as below:
$.ajax({
url: 'loadfile.php',
type: 'POST',
data: formData,
async: false,
dataType: 'json',
timeout : 60000,
beforeSend :function(){
//do something
},
success: function (html) {
//doing something
}
});
$(document).ajaxStart(function() {
$(".ajax-progress").show();
});
$(document).ajaxStop(function() {
$(".ajax-progress").hide();
});
This will show and hide $(".ajax-progress") in all your ajax requests within the application.
I am having trouble getting an ajax GET request (or any request for that matter) to retrieve the response. I am simply trying to return the response in an alert event:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
</script>
I can get this and other similar post requests to work by taking away the function in the success option and editing the code like this:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: alert('success')
});
});
});
</script>
Why is this? And more importantly, how can I retrieve the response data and transfer it to an alert message? Any help is appreciated!
** Update:
Upon reading the first two users' responses on this question, this is what I have:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'GET',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:test#email.com))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});
});
});
</script>
I am able to get the error response, so I can confirm there is some kind of error. I also want to point out that I am making the request from a different domain (not crm.zoho.com) so should I be using jsonp? If so, how would I alter the code?
When you have
success: alert('success')
you do NOT have a successful request, you are actually executing this function at the start of AJAX method. The success parameter requires a pointer to a function, and when you use alert('success') you are executing a function instead of providing a pointer to it.
First thing that you need to try is to update type to GET instead of Get:
$.ajax ({
type: 'GET',
Try using the .done() function as follows:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'yourUrl',
dataType: 'json',
}
}).done(function(result) {alert(data);}) //try adding:
.error(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);})
});
});
the error function will also give you some information in your console as to the status of your request.
I'm calling php file through ajax call and if it returns nothing i want to redirect user to another page (It's for error reports, if it doesn't return anything it means that user logged in). Tried to add error section but it doesn't work. Any suggestions will help. Thanks! Btw, I have small jQuery function at the top of the ajax function, why it breaks my whole ajax call?
ajax.js
function loginAjax() {
//$("#email_errors").empty(); //This function doesnt work and kills whole ajax call. Here is loginAjax function call line - <button type = "submit" id = "push_button" onclick = "loginAjax(); return false">PushMe</button>
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
}
});
}
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
},
error: function(){
window.location.replace("http://stackoverflow.com");
}
});
}
To redirect using javascript all you need to do is override the location.href attribute.
function loginAjax() {
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
// the success method is deprecated in favor of done.
done: function(data) {
$("#login_error").html(data.login_message);
},
fail: function(data) {
location.href="path/to/error/page";
}
});
}
I am using ajax, sometimes it takes time to load all the data from my database therefore I need to find a way to display (Loading...) While the data is not yet complete. Below is my sample code, and I am looking for some event while the data is still in process.
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(data){
$('#para').html(data);
}
});
It is very simple..
before you call the ajax start your loading image..& after the success hide the image
for eg :
$.fancybox.showLoading();
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(data){
$.fancybox.hideLoading();
$('#para').html(data);
}
});
here
$.fancybox.showLoading()
is my function in which I have the property of displaying the loader,
This will be internally called whenever an ajax call is made.
$.ajaxStart(function() {
$("img#loading").show();
});
$.ajaxComplete(function() {
$("img#loading").hide();
});
HTML
<img src="../images/loading.gif" alt="wait" id="loading"/>
<div id="loading">LOADING...</div>
var loading = $("#loading");
loading.hide();
function doAjax() {
loading.show();
$.ajax({
url: "/js/beautifier.js",
success: function (data) {
loading.hide();
}
});
}
doAjax();
on jsfiddle
I have function making multiple AJAX request with jQuery like:
function() {
$.ajax({
url: "/url",
data: {
params: json_params,
output: 'json'
},
async: false,
success: function(res) {
data1 = res
}
});
$.ajax({
url: "/url",
data: {
params: json_params,
output: 'json'
},
async: false,
success: function(res) {
data2 = res;
}
return data1 + data2;
});
}
While this function is running and data is loading I want to display a loading image without blocking it.
I have tried showing the loading icon using ajaxSend ajaxComplete, but does not work, since I have multiple ajax calls.
I also tried showing the loading at the beginning of the function and hiding at the end of the function, but failed.
How to do this?
How exactly did you try loading? Using the ajaxStart/ajaxStop events on the elements is one way to accomplish what you want. It could look like this:
$('#loadingContainer')
.hide() // at first, just hide it
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
Maybe this helps you, I often used this before and it works like a charm..
I think the answer is really a combination of several of these. I would begin with ajax start to show the loading image at 0 (or whereever you want the start to be). Then I would use a callback function to increment the loading bar and repaint it.
For example
//when ajax starts, show loading div
$('#loading').hide().on('ajaxStart', function(){
$(this).show();
});
//when ajax ends, hide div
$('#loading').on('ajaxEnd', function(){
$(this).hide();
});
function ajax_increment(value) {
//this is a function for incrementing the loading bar
$('#loading bar').css('width', value);
}
//do ajax request
$.ajax({
url:"", //url here
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data1=res
ajax_increment(20); //increment the loading bar width by 20
}
});
$.ajax({
url:"", //url here
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data1=res
ajax_increment($('loading bar').css('width') + 10); // a little more dynamic than above, just adds 10 to the current width of the bar.
}
});
You could try something like this: Define a callback with a counter, and the callback hides the image after it's been called the required number of times.
showLoadingImage();
var callbackCount = 0;
function ajaxCallback() {
++callbackCount;
if(callbackCount >= 2) {
hideImage();
}
}
$.ajax({
url:"/url",
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data1=res
ajaxCallback();
}
});
$.ajax({
url:"/url",
data: {params:json_params,output:'json'},
async: false,
success: function (res) {
data2=res;
ajaxCallback();
}
});
That's only necessary for asynchronous calls, though. The way you're doing it (all your AJAX calls are synchronous), you should be able to just call hideImage() before returning at the end of your outer function.
You should be able to bind to the start and then end with the following:
$('#loading-image').bind('ajaxStart', function() {
$(this).show();
}).bind('ajaxStop', function() {
$(this).hide();
});
Or you could use beforeSend and on Complete
$.ajax({
url: uri,
cache: false,
beforeSend: function() {
$('#image').show();
},
complete: function() {
$('#image').hide();
},
success: function(html) {
$('.info').append(html);
}
});