the page freeze when uploading file image using ajax - javascript

I created a ajax function for uploading file images, everything works except there's an ugly part where the page freezed at the process (ajax file image processing submission), any ideas, help, suggestions, clues? below is my code reference.
$("#form_image_file_submit").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
$.ajax({
url : this_current.attr("action"),
data: formData,
type: 'post',
cache: false,
async: false,
complete: function(data){
alert(data);
}
});

You have async: false. Change it to true

Use async:true or remove it.
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
Ajax Docs

Related

How to run getJSON synchronously? [duplicate]

GOAL: What I'm after is to get data from database and refresh main.php (more evident through draw_polygon) every time something is added in database (after $.ajax to submit_to_db.php).
So basically I have a main.php that will ajax call another php to receive an array that will be saved to database, and a json call another php to return an array will be used by main.php.
$(document).ready(function() {
get_from_db();
$('#button_cancel').click(function(){
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: {list_item: selected_from_list},
success: function(result){
...
get_from_db();
}
});
});
function get_from_db(){
$.getJSON('get_from_db.php', function(data) {
...
draw_polygon(data);
});
}
});
In my case, what I did was a get_from_db function call for getJSON to actually get data from database, with the data to be used to draw_polygon. But is that how it should be done? I'm a complete newbie and this is my first time to try getJSON and ajax too to be honest. So my question: How does asynchronous work actually? Is there another workaround for this instead of having to call function get_from_db with getJSON (it isn't synchronous, is it? is that why it doesn't update the page when it isn't within a function?) All the time - like $.ajax with async: false (I couldn't get it to work by the way). My approach is working, but I thought maybe there are other better ways to do it. I'd love to learn how.
To make it more clearer, here's what I want to achieve:
#start of page, get data from database (currently through getJSON)
Paint or draw in canvas using the data
When I click the done button it will update the database
I want to AUTOMATICALLY get the data again to repaint the changes in canvas.
Since $.getJSON() uses ajax configurations, just set the global ajax configs:
// Set the global configs to synchronous
$.ajaxSetup({
async: false
});
// Your $.getJSON() request is now synchronous...
// Set the global configs back to asynchronous
$.ajaxSetup({
async: true
});
Asynchronusly does mean the Request is running in the background, and calls your function back when it got a response. This method is best if you want to have a result but allow to use your app within the request. If you want to have a direct response, take a look at a synchron request. this request will pause script execution until it got a response, and the user can not do anything until the response was recieved. You can toggle it via:
async: false,
So for example:
$.ajax({
url: "myurl",
async: false,
...
})
$.getJSON(), doesn't accept a configuration, as it says in the docs it's a shorthand version of:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So just rewrite your request in terms of that and async:false will work just as you expect.
$.getJSON() is a shorthand notation for $.ajax() which can be configured to be synchronous (see jQuery.getJSON and JQuery.ajax):
$.ajax({
dataType: "json",
url: url,
data: data,
async: false,
success: function(data) {
...
draw_polygon(data);
}
});
Try to avoid synchronous calls though. Quote from jQuery doc (see async prop):
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation. Note that synchronous requests may temporarily
lock the browser, disabling any actions while the request is active.
You might want to try jQuery Deferreds like this:
var jqxhr = $.getJSON(url);
jqxhr.done(function(data) {
...
draw_polygon(data);
});

JavaScript ajax, JSONP, Callback function to do something with data

Fellas,
I'm trying to do an ajax call to get some JSON. I can get around the cross origin issues in Chrome very easily but in IE the only way I got it working without throwing an error is using JSONP. My problem is that i don't know how to process the response. I can see that the call executes and it returns JSON in fiddler but how do i catch it and play with it in my code that's below.
$.support.cors = true;
function callAjaxIE(){
$.ajax({
type: 'GET',
async: true,
url: usageUrl,
dataType: 'jsonp',
crossDomain: true,
jsonp: false,
jsonpCallback: processDataIE,
// cache: false,
success: function (data) {
alert('success');
//processData(data)
},
error: function (e){
console.log(e);
}
}).done(function (data) {
alert('done');
});
function processDataIE(){
alert('processing data ie');
}
It works when i run it, it displays a message box saying 'processing data ie' but so what. How do i play with the results?
UPDATE:
So I've updated the code as per Quentin. It doesn't go into the 'success' block. It errors out with the following.
When i look at fiddler. The JSON is there. How do i get it?
Don't force the function name. That's a recipe for race conditions. Remove jsonpCallback: processDataIE. Let jQuery determine the function name.
Don't remove the callback parameter from the URL. Make the server read callback from the query string to determine which function to call. Remove jsonp: false,.
Use the success function as normal. (Get rid of processDataIE, that's what success is for).
Asides:
crossDomain: true is pointless. It tells jQuery that when it is using XHR (which you aren't) and the URL is pointing to the same origin (which it isn't) then it should not add extra headers in case the server does an HTTP redirect to a different origin.
async: true is pointless. That's the default, and JSONP requests can't be anything other than async anyway.
$.support.cors = true; is pointless at best and can be harmful. Remove it.
Don't override jQuery's detection of support for CORS by the browser. You can't make ancient browsers support CORS by lying to jQuery. You're using JSONP anyway, so CORS is irrelevant.
The above is the sensible, standard, robust solution.
If you want the quick hack that maintains all the bad practises you have in play, then just look at the first argument to processDataIE.

Can I cache contents loaded by jQuery.getScript()

As per jQuery documentation (https://api.jquery.com/jquery.getscript/) use more flexible $.ajax() method, but it doesn't work for me described in here (jQuery cannot load plugin file using ajax before calling the plugin function, thus, gives kind of weird result)
By default, $.getScript() sets the cache setting to false. This
appends a timestamped query parameter to the request URL to ensure
that the browser downloads the script each time it is requested. You
can override this feature by setting the cache property globally using
$.ajaxSetup():
$.ajaxSetup({
cache: true
});
But I need to cache few of the contents not all.
Alternatively, you could define a new method that uses the more
flexible $.ajax() method.
It didn't work for me as it doesn't guarantee loading files in a sequence.
Now what is the best solution for this situation?
$.getScript({
url: "foo.js",
cache: true
})
Supported on jQuery 1.12.0 or later
use $.ajax with dataType: 'script' and cache: true.
$.ajax({
cache: true,
url: 'foo.js',
dataType: 'script', // optional, can omit if your server returns proper contentType for js files.
success: function () {
console.log('Hello World!');
}
});
This assumes your server is responding with the headers required for the browser to cache the file.

How can i stop hanging page when a request is send via Ajax

I am facing a serious issue... Whenever i use Ajax to send a request and get an response my browser got hanged.. and show no loading etc...
But when i response is retrieved from the Ajax then browser and page again start working...
Below is the code that i used.....
function ShowContestStatus(contestID)
{
$("#showContestDetails").html('<div class="loadercontest"><img src="assets/images/loading.gif">Loading Contest....</div>');
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', true);
$.ajax({
url:"process/processMyContest.php",
type:'POST',
cache:false,
async:false,
data : {act : 'showcontest', cid : contestID },
success:function(result)
{
$("#showContestDetails").html(result);
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', false);
}
});
}
Please help me on this... i want to get the same response as on other websites when you send a request and they are using ajax the page neither hanged and also each processing like scrolling etc is visible ......
So please suggest me good ideas.... so i can get rid of it and make my ajax smooth for page without effecting and irritate the other person by hanged...
Thanks in advance...:)
The problem is async:false... Since your ajax request is synchronous the script execution will wait for the request to complete to continue..
Since browser uses a single threaded execution pattern(either it will execute script or repaint or wait for user events at a time- not all at the same time), your browser tab will stop listening to user(so it will look like it is hanged)
function ShowContestStatus(contestID) {
$("#showContestDetails").html('<div class="loadercontest"><img src="assets/images/loading.gif">Loading Contest....</div>');
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', true);
$.ajax({
url: "process/processMyContest.php",
type: 'POST',
cache: false,
//remove async: false,
data: {
act: 'showcontest',
cid: contestID
},
success: function (result) {
$("#showContestDetails").html(result);
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', false);
}
});
}
Ajax.async
By default, all requests are sent asynchronously (i.e. this is set to
true by default). If you need synchronous requests, set this option to
false. Cross-domain requests and dataType: "jsonp" requests do not
support synchronous operation. Note that synchronous requests may
temporarily lock the browser, disabling any actions while the request
is active. As of jQuery 1.8, the use of async: false with jqXHR
($.Deferred) is deprecated; you must use the success/error/complete
callback options instead of the corresponding methods of the jqXHR
object such as jqXHR.done() or the deprecated jqXHR.success().
Make async:true for making the browser listen other events while running the ajax code.

How to do a synchronous json ajax call with jquery

I have the following json ajax call:
$.getJSON(server_data.secure_api+'/e/account/check/?callback=?', queryData,
function(data) {
has_error = (data.status == 'failure');
});
Which works perfectly, except that it is asynchronous. I now need to make it synchronous, because I need to pause the calling function until has_error is set. How do I do this?
I have already tried using a .ajax call, like this:
jQuery.ajax({
url: server_data.secure_api+'/e/account/check/?callback=?',
data: queryData,
DataType: 'jsonp',
success: function(result) {
has_error = (data.status == 'failure');
},
async: false
});
But it doesn't work! I've tried setting the DataType to json, jsonp, or not set; I've tried including the ?callback=? and I've tried leaving it off; none of this has worked. What am I doing wrong?
By default, all requests are sent asynchronously (i.e. this is set to
true by default). If you need synchronous requests, set this option to
false. Cross-domain requests and dataType: "jsonp" requests do not
support synchronous operation. Note that synchronous requests may
temporarily lock the browser, disabling any actions while the request
is active.
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding method
http://api.jquery.com/jQuery.ajax/
There's no reason your use case should require synchronous code. If you need some code to delay it's execution until the asynchronous call is completed then place that code in the callback function.

Categories