I'm making a functional mockup using mootools,and in this prototype I have to load an html file via request.HTML, but as soon as I run the script, the call never reaches the onSuccess due to the state = 0.
The blame could be that the request is treated as a violation of the crossdomain.
So I was wondering if is out there a way to work it around?
this is the code I use for performing the request
req = new Request.HTML({
url: "detail.html",
onFailure: function(a) { console.log("iFailed: " + a); },
onSuccess: function(r3, rEls, rHTML, rJS) {
console.log("It worked!!");
},
onComplete: function() { console.log('completed'); }
}).send();
as I run this it always goes into the onFailure and in the onComplete without hitting the onSuccess.
I need this to work with safari, because the mock shall work on an iphone/ipad/ipod.
thx a ton
in the end I managed it bu injecting an iframe via js, instead of populating the div via ajax.
it's kind of lame and it sucks a lot, but at least it work and it's good for prototyping purposes.
Related
I am presently developing a web application with jQuery mobile. However, I found that when a "changePage" fails, I can no longer send ajax requests. After the failure, all ajax requests return an error. Here's the code executed when the submit button on the form is clicked (it's a basic user login screen):
// Event when user click the Submit login button
$('#submitLogin').on("click", function () {
// submit the user credentials to the server
$.ajax({
type: "POST",
url: "./LogUser",
data: {
EmployeeID: $('#EmployeeID').val(),
EmployeePIN: $('#EmployeePIN').val()
},
dataType: "text",
async: true,
cache: false,
error: function (rqst, text, thrownError) {
$('#dlg-login-error-message').text(thrownError);
$('#dlg-login-error-popup').popup("open");
},
success: function (data) {
if (data == "Success") {
$.mobile.changePage("./LoadScreen/Menu");
}
else {
$('#dlg-login-error-message').text(data);
$('#dlg-login-error-popup').popup("open");
}
}
});
return false;
});
If the post itself fails, I can resubmit without problem. If the .mobile.changePage fails, a "page not found" is displayed, but I am not able to resubmit, ajax no longer making request to the server and jumping directly to the error callback with a "not found" error.
I am guessing the problem comes from the fact that jQuery mobile uses AJAX request to load pages, and that somehow, ajax calls are getting mixed up somewhere.
I did more tests, even intercepted the pageloadfailed event, but nothing works. After the page change failure, AJAX calls no longer sends anything to the server and jump automatically to the error callback function.
I tried with async=false, same problem. I tried debugging jQuery-mobile, but I am still not able to find the "changePage" function itself ( the .code is quite confusing ).
I just spent the last two days trying to figure out a way to resolve this and I am seriously thinking of using something else than jQuery-mobile for our development.
I have found a workaround for my problem, but I do not know the full impact of this solution yet.
To prevent the problem, I had to set the "pushStateEnabled" configuration option to "false".
So if you find yourself with the same problem, try putting the following in a script right before the loading of the "jQuery-mobile" script.
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
Example:
<!-- Load the script for jQuery -->
<script src="~/Scripts/jquery-2.1.4.js"></script>
<!-- Set default for jQuery-Mobile, before it is actually loaded -->
<script>
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
</script>
<!-- Load the script for jQuery-Mobile -->
<script src="~/Scripts/jquery.mobile-1.4.5.js"></script>
Below is my react code I want that firstly the ajax code should execute then the rest of the code should execute.
expected output in console:
inside ajax
outside ajax
current output in console :
outside ajax
inside ajax
import React from 'react';
import request from 'superagent'
const UserItems = () => {
request.get('http://localhost:4000/user/1/items.json')
.then((res, err) => {
if (err) {
console.log("errror found")
}
var data = JSON.parse(res.text)
console.log("inside ajax")
console.log(data)
})
console.log("outside ajax")
console.log(data)
};
export default UserItems;
Any suggestion !!!
As hainguyen points out, ajax is typically asynchronous so the code afterwards will run until the request is complete, at which time the inner function is executed. So the outer console logs will almost certainly run first in your code. While there are ways around this as hainguyen points out, most recommend against it. Ajax is something which takes time, and therefore your code structure should reflect that. If you ever find yourself wanting to run code while the ajax request is in process, you might dislike a synchronous structure. My "I wait for no one" log shows the power of an asynchronous approach since that logic will run quickly while you would normally be waiting on the request without being able to do anything.
Rather than make it synchronous why not use functions to handle the asynchronous behavior better like wrapping whatever you want to run after the inside console log in a function: (I called it outside()) This will output "inside ajax", "outside ajax". This way you can create dependencies on your ajax return and still have the option for running stuff in the meantime.
import React from 'react';
import request from 'superagent';
const UserItems = () => {
request.get('http://localhost:4000/user/1/items.json')
.then((res, err) => {
if (err) {
console.log("errror found");
}
var data = JSON.parse(res.text);
console.log("inside ajax");
console.log(data);
outside();
});
function outside(){
console.log("outside ajax");
console.log(data);
}
console.log("I wait for no one, run me as quick as possible!");
};
export default UserItems;
I don't know about request library but ajax is async by default. If you want ajax perform sync request, you should do something like this:
function getRemote() {
return $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
}
Important line: async: false
I found allot of examples of AJAX and I think I can get some code with it to work on my own. If only I knew what the use of all the terms of the AJAX code where.
I think in general it lacks the availability of these guides or special pages where constructed code is explained in detail for new programmers.
This would help enormously because of the misunderstanding of the syntax in many cases. Me for example spend 8 hours a day on my internship to learn PHP, Jquery, HTML from scratch and there is allot of information out there but its not structured and in most cases to technical. Any tips on that maby ? :)
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
Ajax is asynchronous, which mean you can use it to get new informations from the server without reloading the whole page.
Here's an explanation of your code :
$.ajax({
$ is the JQuery object, on which you're calling the ajax function
type: 'POST',
You're gonna send your data by post, which mean that you'll have to get them in php with $_POST['variable_name']. You could also put GET instead
url: 'http://kyleschaeffer.com/feed/',
the url you want to reach
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
as you're sending your request with POST, you cannot pass data directly from the URL.
So you have to pass them like that. { nameVar: 'value', .... }
If you were sending with GET, you could directly write them into url like : "http://my_url.php?var1=val1&var2=val2 etc ...
beforeSend:function()
You can define an action before sending your ajax request
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
Here, inside your div "ajax-panel" you want to write some content. (a div "loading" and a picture inside "loading").
success:function(data)
If your request is successful, you can do something. By successful it means if server answer 200 i guess, anyway ... If you have a response from server... ;)
$('#ajax-panel').empty();
You delete content into ajax-panel
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
You're adding some html AFTER (append) the ajax-panel div
error:function()
Not sure you were looking for that, hope that help you ;)
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develope next generation web application
Take a took at this
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
},
error : function() {// When Service call fails
}
});
I am trying to send data to server using ajax, but the problem is that I have a consuming process before sending the data.
The process takes about 5 seconds and the spinner has to run in the process.
So in my code the spinner doesnt show until the ajax call starts (probably because the process is blocking everything)
If I move the call "consumingprocess" into "beforesend", then it doesnt work and I am not sure why.
So the question is how to show the spinner, while everything is beeing called (the consumingprocess and the ajax call)
Thanks
This is my code:
$("#btnAccept").bind("click", function(event, ui) {
//start spinner, works fine but only shows after consumingprocess has finished
$.mobile.loading( 'show' );
console.log("btnAccept");
var data = consmuingprocess();
console.log(data);
// data is fine
$.ajax({
type : "POST",
url : url,
dataType : "xml",
contentType : "text/xml;charset=UTF-8",
data : data,
requestHeaders : {
Origin : '*'
},
crossDomain : true,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxx");
console.log("beforeSend");
},
error : errorAJAX,
success : parseXml
});
});
});
What you can do is
call your loading window
delay so the loading window has a chance to display
run the rest of your code.
You would do this using an interval:
$("#btnAccept").bind("click", function(event, ui) {
var intervalId;
function delayedStuff = function() {
// make sure we only run this once
window.clearInterval(intervalId);
var data = consmuingprocess();
$.ajax({
// set up your ajax request and handlers
});
};
$.mobile.loading( 'show' );
// wait 1/2 second, then run delayedStuff
intervalId = window.setInterval(delayedStuff, 500);
});
But this technique comes with an important caveat: while your very expensive consumingProcess function is running, all animations and javascript still comes to a halt. On Chrome, even animated gifs stop running. All we've done here is just given your page changes a chance to display.
There are a couple of possible solutions available:
Take a closer look at your consumingprocess() function and see if it can be optimized. There is probably a faster way to do whatever it is you're doing that's taking so long.
Use WebWorkers. The downside is compatibility: IE and most older browsers don't support it. I haven't done multi-threaded programming with JavaScript at all, so I don't know how effective this is.
I have a JavaScript application that works like this:
Uploads a file, receives the uploaded file ID as a response
This is done using the BlueImp uploader
Uses the file ID to refer to the file in subsequent requests, in this case to receive a preview of the uploaded file.
This is the code for the file upload 'complete' handler. It's originally written in Coffee Script (http://pastebin.com/708Cf9tu).
var completeHandler = function(e, data) {
var url;
if (data.textStatus !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget i konsollen");
console.group('Upload failure');
console.error(data.textStatus);
console.error(data.result);
console.groupEnd('Upload failure');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
return;
}
self.fileUploadResponse = data.result;
url = "" + config.api_root + "/" + config.api_path_tabulardatafilepreview;
return $.ajax(url, {
type: 'POST',
dataType: 'json',
async: false,
data: {
'file_handle': data.result.file_handle,
'rownum': 5
},
complete: function(req, text_status) {
if (text_status !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget " + "i konsollen");
console.group('Failed to receive data file preview');
console.log(text_status);
console.log(req.responseText);
console.log(req);
console.groupEnd('Failed to receive data file preview');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
}
self.previewData = JSON.parse(req.responseText);
return self.setStage(2);
}
});
};
This works brilliantly in FireFox, but in Chrome I just started to get an error in the second jQuery Ajax request. It now returns with status "error", with no responseText and with statusText set to "Error: NETWORK_ERR: XMLHttpRequest Exception 101". Though this doesn't happen in all cases. The uploaded file doesn't seem to have anything to do with the issue, because a 10KB csv file works, a 120KB xlsx file fails but a 1.2MB xlsx works. Additionally it's the second Ajax request that fails, and it doesn't do anything but send two small integers to the server. Why does that fail!?
Also this just started happening today. I haven't changed anything that I know of, and I have not updated Chrome.
Does anyone have a clue as to why Chrome is doing this? Can it have anything to do with an Ajax request being launched in the complete handler of a previous Ajax request?
Thanks for any guesses that can help me solve this
Turns out it's a bad idea to start lengthy processes inside Ajax event handlers. In my case, starting a new synchronous Ajax request in the event handler was the mistake. I have since made both requests asynchronous and separated the code into neat functions, and I'm no longer bothered by the exception.