Zepto/JQuery AJAX request automatically downloading media files from requested html - javascript

I need to make AJAX request for HTML content, but when I look into firebug it seems that request is downloading media files attached to requested html (images, CSS). How can I stop it? I need only plain text from PHP-genereted HTML.
$.ajax({
type: 'GET',
url: 'http://examplehost.com,
dataType: 'text',
cache: false,
success: function (data) {
// SUCCESS CODE HERE
},
error: function (xhr, type, error) {
// ERROR CODE HERE
},
complete: function() {
// ON COMPLETE CODE HERE
}
});
I also must have possibility to run functions when request is complete!
Im using ZEPTO library, but its JQuery clone, so the functions are similar.

Related

Why can't my ajax get request find my handler route when I add arguments?

I am building a web app that displays data about flowers that is stored in my local server running bottle.
My front end is html, js with ajax;
My back end is python with bottle
In the browser there is an empty div in which the data is to be displayed.
Below it there is a row of images. When the user clicks on an image the data should display in the div above.
I tried using $.ajax instead of $.get, and I'm getting the same result.
This is my event listener in js:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
This is my handler for this request:
#get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(data is an array of dictionaries, each containing data of a single flower)
I am getting a 404 error (the function get_flower_desc is not executed at all) that possibly is happening because of the argument, because whenever I use a a function with no parameters and pass in no arguments I am getting the result that I'm expecting.
I found that I had to formulate an AJAX request quite precisely to get it to work well with Bottle in a similar scenario.
Here is an example with a GET request. You could attach this function to the event handler or move it directly to the event handler.
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
However, I found better results using a POST request from AJAX instead.
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
For the POST request, the backend in Bottle should look like this.
#post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
Make sure your data is valid JSON and that the database code you have is working correctly.
These solutions using AJAX with Bottle worked well for me.

AJAX call stops page from loading other elements

I'm building a website using Laravel and Jquery. The page is issuing multiple AJAX calls.
One of these calls can take multiple seconds and it seems to be blocking other elements of the page from loading. This includes images and other AJAX calls.
My code more or less looks like this.
$.ajax({
async: true,
url: url,
data: {
//data
},
success: function (response) {
//Process response (append html, images, etc.)
for (var key in response) {
newAJAXCall(response[key]);
}
},
error: function (xhr) {
}
});
newAJAXCall call looks like this:
$.ajax({
async: true,
url: url,
data: {
//data
},
success: function (response) {
//Process response
},
error: function (xhr) {
}
});
newAJAXCall is what's causing the problem. Some of the calls are done within 200 ms. but some can take multiple seconds. When this happens, if any elements didn't load yet they stop loading.
In the case of images, the html for them is already existing. The browser just stops loading them until the AJAX call is done.
I already tried setting async and using a timeout but nothing seems to fix it. The problem happens both in Chrome and Safari so it doesn't seem to be browser specific.
EDIT: Even when the for-loop is removed and the new ajax call is only issued once the problem persists if the call lasts long.
EDIT2: Could it be possible that Laravel/Php is limiting the amount of connections a single client can open?
EDIT3: It seems to be my server which causes the problem. When I load the images from a different server than my own they load fine during the ajax requests.
The problem was that my localhost server didn't have enough capacity. When the website runs on my dedicated server everything loads fine.
As per my comment, please consider putting for loop within newAJAXCall success function
$.ajax({
async: true,
url: url,
data: {
//data
},
success: function (response) {
//Process response (append html, images, etc.)
newAJAXCall(response);
},
error: function (xhr) {
}
});
function newAJAXCall(response) {
$.ajax({
async: true,
url: url,
data: {
//data
},
success: function (response) {
for (var key in response) {
//Process response[key]
}
},
error: function (xhr) {
}
});
}

Correct use of JSONP

To successfully use JSONP (e.g. via jquery - $.ajax ... etc.) must always be that the requested page is designed to provide data corresponding to this format?
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also will I get an error?
This question might seem trivial to some users, but I'm starting right now to learn these technologies, and the matter is a bit complicated.
Based on these (ref1 ref2) references it would seem that there must be consistency between the request with JSONP and implementation of the server response.
Edit
I have this jQuery request
$.ajax({
url: "https://sites.google.com/site/problemsstore/javascript/test.js",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
And I have loaded in https://sites.google.com/site/mysite/javascript/test.js?attredirects=0&d=1 this test.js file:
function myCall(data) {
console.log('succeed');
}
myCall({ some : "data" });
When I am connected I hope to obtain as console's output: succeed succeed.
Instead this is what I get:
succeed
failed
Edit2
$.ajax({
url: "https://sites.google.com/site/bentofelicianolopez/jscript-jsonp/test.js?attredirects=0&d=1",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
jsonp: 'myCall',
//contentType: 'application/json',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
The .js file:
myCall({ some : "data" });
The output:
failed test4.html:94:9
ReferenceError: myCall is not defined /*this is the syntactical error of which I said*/
test.js:1:1
To successfully use JSONP (e.g. via jquery - $ .ajax ... etc.) must always be, that the requested page is designed to provide data corresponding to this format?
Yes. A request for JSONP will only work if the response is expressed as JSONP.
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also I will get an error?
You can have a static JavaScript program that conforms to the JSONP format (it requires hardcoding the callback function name), so not necessarily.

Different browser gets different result for jQuery ajax call

I am trying to make a $.ajax call but get a different result on different server.
In my js file, I have the following code
function getData () {
$.ajax({
async: false,
type:'GET',
contentType: "application/json",
url: 'sample.json',
dataType: 'json',
success:function(result){
alert("successful");
},
error: function (xhr, status) {
alert("failed");
}
});
}
The js file is included in an HTML file where there is a button with its onclick method as getData().
My problem is, it will pop up a "failed" alert window if I open the html file in IE or Chrome, but a "successful" window if I open the html in Firefox.
Solved:
I had the problem when trying to run that function from a local html file instead of on a server. And running on server solves the problem.
This is a security measure in browsers which prevents access to the file system. Firefox just has a different security measure that allows file access. Use a webserver and you won't run into this issue.

In IE lightbox doesn't show if a synchronous ajax request is made

I've got the following code that shows a lightbox 'please wait' box, then does a synchronous ajax request which removes the lightbox when it finishes. Works fine everywhere else, but in IE, the lightbox doesn't show. The Ajax request works fine, but it just seems to ignore the lightbox.
The showLightbox function just does that, show a modal lightbox with the passed in text.
showLightbox("Please Wait");
$.ajax({
async: true,
dataType: 'json',
type: 'GET',
url: checkValidUrl,
data: submitData,
error: function(request, textStatus, errorThrown) {
valid = false;
},
success: function(data, textStatus) {
valid=true;
},
complete: function(request, textStatus) {
hideLightbox();
}
});
If I make the ajax requst async it works fine, but I need it to be synchronous because this is a validation method.
Update: Also, if I wrap the whole ajax request in a setTimeout it also works in IE, but that is asynchronous too
Update 2: I just replaced the lightbox with a simple div and did a jQuery .show() on beforeSend and .hide() on complete, and it didn't show that either, so it doesn't seem to have anything to do with the lightbox. If I whack an alert() immediately after showLightbox() it does show the lightbox
My guess is that IE either is too busy doing the request to show the lightbox or that it thinks it's supposed to stop to do the request. Try adding the showLightbox() function to the $.ajax function itself, to the beforeSend option.
$.ajax({
async: true,
dataType: 'json',
type: 'GET',
url: checkValidUrl,
data: submitData,
beforeSend: showLightbox(),
error: function(request, textStatus, errorThrown) {
valid = false;
},
success: function(data, textStatus) {
valid=true;
},
complete: function(request, textStatus) {
hideLightbox();
}
});
In your ajax call, you need to call the lightbox functionality again. I used Lytebox, so it may be different for you.
$j.post("kitchen.php", $j("#post_form").serialize(),function(result) {
//xmlhttp.open("GET","ajax_test.php",true);
//xmlhttp.send();
$j('#grab_kitchen').attr({'disabled' : 'false'});
$j('#grab_kitchen').removeAttr('disabled');
$j('#Output').fadeIn(500);
$j('#Output').html(result);
$j("body").css("cursor", "auto");
// add there your lytebox function to work
initLytebox();
});
This smells funny.
Firstly, I can't think of any good reason for using a synchronous request -- doing so locks the user's browser until the response is returned. It's a terrible user experience which would make most users think your website is killing their browser.
Secondly, you say you're doing this for validation? Any user who is malicious enough to try to alter a form while they wait for the asynchronous response would also be smart enough to just change your "async: false" to "async: true". Remember that all validation on the client side is only there for the benefit of the user, and all proper validation should be done server-side. I don't see why you'd need to do things this way.
Perhaps you should show the lightbox, and then do a setTimeout before you actually begin the synchronous request. I suspect that IE doesn't render your DOM changes until it gets control back from your JS function, and that doesn't happen until after the ajax request, and the box is hidden again. Give it a chance to render the lightbox, and then start your ajax request.
showLightbox("Please Wait");
setTimeout(function() {
$.ajax({
async: false,
dataType: 'json',
type: 'GET',
url: checkValidUrl,
data: submitData,
error: function(request, textStatus, errorThrown) {
valid = false;
},
success: function(data, textStatus) {
valid=true;
},
complete: function(request, textStatus) {
hideLightbox();
}
});
}, 100);
I have the same exact issue.
http://www.precisehomebuilders.com/kitchen-remodeling
There is a button at the bottom of the page that grabs more photo galleries, which works.
Here's the thing: if I do a "save as" after the ajax call and reload it, then it totally works. There's just something about grabbing lightbox items through ajax.

Categories