I am trying to write a jQuery Ajax function, to reduce the amount of code in the page because the script is called a few times in the page. I can't seem to get it to work. Here is the code i have:
var loadURL = $(this).attr('href');
function load(){
$.ajax({
url: loadURL,
type: 'GET',
cache: true,
data: {
delay: 4
},
success: function(data) {
$('#load').html(data)
}
});
return false;}
$('#one').click(function(){ load(); });
$('#two').click(function(){ load(); });
$('#three').click(function(){ load(); });
Two
Two
Two
can anyone guide me here please?
i think the way you are getting href is wrong
function load(item){
var loadURL = $(item).attr('href');
$.ajax({
url: loadURL,
type: 'GET',
cache: true,
data: {
delay: 4
},
success: function(data) {
$('#load').html(data)
}
});
return false;}
$('#one').click(function()
{
load($(this));
return false; //you should mention return false here
});
It is worth noting that you can define your own jQuery functions if you wish..
Related
I use Jquery-ajax calls to get information from a api and store it. The problem I encounter is the following:
When first call is made call everything seems normal. When the call is made 2nd time (after 1 min )again one only call takes place but with 3rd call 2 times sendData function is getting called ,4th time 4 times sendData function is called.
Please tell me where i am going wrong.Thanks in advance.
$(document).ready(function() {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
async: false,
success: function(resp) {
if (resp != null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
setInterval(ajaxCall, 1000 * 60);
} else {
alert("something went wrong");
}
}
});
});
I would suggest you to move calling method to Ajax's complete method:
$(document).ready(function () {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
success: function (resp) {
if (resp !== null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
} else {
alert("something went wrong");
}
},
complete: function () {
setInterval(ajaxCall, 1000 * 60);
}
});
})
});
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 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);
}
});
I am using ASP.NET MVC and jQuery and I am loading a PartialView via Ajax. A seperate JavaSriptFile belongs to this PartialView. On success, the return html is inserted in the DOM. In the JavaScript, some stuff is done and that together might take a little moment. The loaded content is then displayed in a dialog.
Simplified Code:
1 $.ajax({
2 url: /user/edit,
3 dataType: 'html',
4 data: { id: 1 },
5 success: function (htmlCode) {
6 $('#dialogEditUser').html(htmlCode);
7 $('#dialogEditUser').dialog('open');
8 });
9 };
This code works and sometimes not, depending on how fast the PartialView's JavaScript is executed. So sometimes, the dialog does not open. So i changed line number 7 to;:
7 setTimeout(function() { $j('#dialogEditUser').dialog('open') }, 250);
Now everything works fine. But this "hack" is not very suitable. How can I check if the PartialView's JavaScript has been executed on the loaded content? Is there maybe any way to return a fully rendered PartialView (so the JavaScript has already been executed where I get the return of the AjaxCall?
By default ajax will not wait for the request to finish.
Try setting async option to false:
$.ajax({
url: /user/edit,
dataType: 'html',
async: false,
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
$('#dialogEditUser').dialog('open');
});
};
More details in docs
Why not make the $('#dialogEditUser').dialog('open'); in the js you are loading? That way when the call is made you know the corresponding js is loaded already
Try wrapping that code in a ready block:
$(document).ready(function(){
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
$('#dialogEditUser').dialog('open');
});
};
});
'#dialogEditUser' might to be loaded yet when the success callback gets called.
If, at the end of your partial view, you have got an element with an specific id like #finishLoad. Why not try this?
var waitToOpenDialog = function(){
var jFinish = $('#finishLoad');
if(jFinish.length<=0){
setTimeout(waitToOpenDialog, 10);
}else{
$('#dialogEditUser').dialog('open');
}
}
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
waitToOpenDialog();
});
};
Well if you cant modify your DOM or don't have any id like #finishLoad you cant try (keeping async=true) with (more or less) this:
var waitToOpenDialog = function(){
var jDialogUser= $('#dialogEditUser');
if(jDialogUser.html().length<=0){
setTimeout(waitToOpenDialog, 10);
}else{
jDialogUser.dialog('open');
}
}
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
waitToOpenDialog();
});
};
Or you can try with complete:
$.ajax({
url: /user/edit,
dataType: 'html',
data: { id: 1 },
success: function (htmlCode) {
$('#dialogEditUser').html(htmlCode);
},
complete: function(){
$('#dialogEditUser').dialog('open');
}
)};
function VReload()
{
$.ajax({
type: "GET",
url: "/foo/",
success: function (data) {
$("#myid").html(data);
}
});
}
$(document).ready(function() {
setInterval('VReload()', 1000)
});
This piece of code is working fine on Mozilla and chrome but not on IE. Ajax call is not firing on IE. What could be the reason.
Switch off caching by doing this:
$.ajax({
type: "GET",
cache: false,
url: "/foo/",
success: function (data) {
$("#myid").html(data);
}
});
set cache false
$.ajaxSetup({ cache: false });
or
$.ajax({
cache: false,
//other options
});
Try this:
function VReload()
{
var timestamp = new Date();
$.ajax({
type: "GET",
url: "/foo/" + "×tamp=" + timestamp.getTime(),
success: function (data) {
$("#myid").html(data);
}
});
}
$(document).ready(function() {
setInterval('VReload()', 1000)
});
use jQuery's $.get() function
$.get('/foo/', {}, function(data){
// whatever
});