Different browser gets different result for jQuery ajax call - javascript

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.

Related

Why is res.sendfile() doesn't work when I call from jQuery ajax?

Issue:
The first ajax is working properly in the main.js, the second one is doing its job at first look but I think there might be a bug somewhere. I can reach the getProducts method after I click to the button.
The product_list.html file should appear on the browser screen, but it doesn't.
I get no error message on the front-end or the back-end.
This is what I noticed: After click to the button -> F12 -> Network -> products -> I can see here a status code: 200 and the product_list.html file content as response.
In case the POST ajax call succeeds and in the case I add: location.href = "/products";, the browser will load product_list.html
I use the get ajax call because i need to pass the jwt token in the req header. (I deleted the jwt authentication parts from the code below because I narrowed down the error to the $.ajax() and res.sendFile() relationship)
//routes.js
routes.get("/products", ProductController.getProducts);
//ProductController.js
var root = path.join(__dirname, '../../views');
module.exports = {
getProducts(req, res){
console.log("getProducts!"); //I can see in the console
res.sendFile("product_list.html", {root}) //It doesn't render the html
},
}
//main.js
$("#btn-login").click(function(){
$.ajax({
type: 'POST',
url: "http://localhost:8000/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"username": $("#login-user").val(),
"password": $("#login-pwd").val(),
}),
success: function(data){
if ($("#login-chkbx").is(':checked')){
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
});
}
}else{
console.log("Checkbox is not checked");
}
}
});
});
What causes the issue and how to solve it?
Thanks!
file should appear on the browser screen
No it does not and it should not. The file should be returned to the ajax function call in the success callback:
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
success: function (file) {
// The file is in the "file" variable above.
// Do whatever you want with it. For example you can replace
// the current page with the returned file:
document.body.innerHTML = file;
}
});
That is the whole point of AJAX - a mechanism for programmers to override the normal flow of HTTP requests that loads the response to the browser page. If it allows you to not load the response to the browser page it also means it will not automatically load the response to the browser page - because doing so will not allow you to not load the response.
If you want to automatically load the response then don't use ajax:
// Replace $.ajax(... with:
window.location.href = "http://localhost:8000/products";
However, this method does not allow you to set custom request header.
in your frontend code you do nothing with the GET /products response
the backend sendfile as the name says it just sends the file over to the requester. Being an ajax call, it must be rendered by the frontend code.
Add something like success: response => $('body').html(response)

How to create an ajax request within google scripts with '$' variable error?

I'd like to use the ajax() method to perform an AJAX Request. I've tried to create the below functions within scripts.google.com, but I get the following error:
function AjaxCall() {
var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'https://worker-aws-us-east-1.iron.io/2/projects/',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
}
Error:
ReferenceError: "$" is not defined. (line 5, file "Code")
Is there a way to get around this issue?
It appears that jquery isn't sourced in your HTML. Keep in mind that jquery is a client side, javascript library -- so the browser needs to load the jquery javascript file. In other words, a valid reference needs to be in the HTML that is returned to the client browser.
Your comment indicated that you tried:
<script src="code.jquery.com/jquery-2.1.1.min.js"></script>
Try updating that to:
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
If you don't include the "http://" (or "https://" or "//") in the front of the URL, the browser thinks it's a relative path and will try to load that from the current directory (and that probably isn't what you were trying to do). So, if the page that you were viewing was
http://www.examplesite.com/example.html
Then, the script tag you showed in your comment would try to load jquery from
http://www.examplesite.com/code.jquery.com/jquery-2.1.1.min.js
This is likely returning a 404 error -- check your javascript console to see if it's receiving an error when trying to load the jquery script.
Also, in most cases, it's recommended that you put the script tag at the bottom (right before the closing body tag). This keeps the page rendering from being blocked as the browser download the js file. This is not likely causing the problems you were originally seeing -- just thought I'd mention it since your comment potentially indicated that you were loading it right before the ajax call.

Links brought in after loading a page through jquery AJAX do not work

Running into an issue with a mobile app. We are doing an jQuery ajax to call in a remote page off our sever (using Cordova as the shell). This brings in the remote code (bare-bone HTML) and we plan to use local resource to style it.
getMyPage: function() {
$.ajax({
type: "GET",
url: "http://localhost:8888/shell/",
crossDomain: true,
timeout: 10000,
success: function(data) {
$("appbody").html(data);
},
error: function( xhr,err ) {
alert('Cannot Connect to the Internet');
}
});
}
It brings in the page fine, but when we click on any of the links (served from the CMS Drupal) nothing happens. Through inspector it thinks the files are local using the file:// prefix which do not exist. Anyone know how to make those links perform the same AJAX call to the remote server?
i.e all the links perform the same ajax GET call.

jQuery JSONP not working anymore?

I have been trying to load a JSON file from a cross-domain server. I've tried examples from stackoverflow and from the jQuery docs. I did get it working in a previous project, but now it strangely does not. The error returned from jQuery is unreadable to me. What can possibly go wrong here?
$(document).ready(function() {
console.log("Start loading");
$.ajax({
type: 'GET',
url: "http://www.nightoferror.nl/data/data.json",
dataType: 'jsonp',
crossDomain: true,
error: function(data) {
console.log('error', data);
},
success: function(data) {
console.log('success', data);
}
});
});
And the erratic JSFiddle here: http://jsfiddle.net/ZuyJV/4/
Content-Type:application/javascript
rather than Content-Type:application/json;
Could it be because your file is named .js, that Apache is serving the content type itself?
Try changing the file type, to JSON and setting up Apache to serve that filetype with the correct MimeType.
I found this using Fiddler - A HTTP Debugger.. open Fiddler(2), make your request in your browser and Fiddler2 then picks it up. From there, just checked the response for your file.
It looks like your server is returning the response as "Application/Javascript"

Failed to load resource + $.ajax call in Chrome

I am having a very strange issue with Chrome and AJAX, I have an autocomplete form that has been working for a while. I fired up Visual Studio this morning and it doesn't work anymore. It works fine in production (with Chrome) and works fine locally if I use Firefox or IE, for chrome it doesn't!
I get the error:
Failed to load resource
in Developer tools, When I expand on the error I get:
f.support.ajax.f.ajaxTransport.sendjquery-1.7.1.min.js:4
f.extend.ajaxjquery-1.7.1.min.js:4
$.autocomplete.sourceCreate:217
a.widget._searchjquery-ui-1.8.17.custom.min.js:127
a.widget.searchjquery-ui-1.8.17.custom.min.js:127
(anonymous function)jquery-ui-1.8.17.custom.min.js:127
I placed a breakpoint in the callback function on the server but it doesn't even make it to the server. The error is definitely on the client side, here is the client-side code:
$("#LocationTxt").autocomplete({
minLength: 4,
source: function (req, resp) {
$.ajax({
type: "GET",
url: "/Ad/SearchLocations",
data: "term=" + req.term,
contentType: "application/json; charset=utf-8",
success: function (data) {
resp($.map(data, function (value, key) {
return { data: value, label: data[key].Name, value: data[key].Name };
}));
},
error: function (data) {
alert(data.statusText);
}
});
},
select: function (e, ui) {
var cityId = ui.item.data.Id;
$('#AdListing_LocationID').val(cityId);
}
});
Also the error event gets triggered, and the statusText property is simply "error". Not very helpful. I am running Chrome version: 17.0.963.46 (I have the latest version as on 2/9/2012). I believe my Chrome updated this morning when I fired up my PC, but I am not sure. Is there a log to tell when my chrome was updated?
If you are working on a local copy of the code, make sure you are working from within a web-server such as localhost. If you are working directly from the file system, google chrome will not allow you to make ajax requests to files on the file system for security reasons.
A few more things...
Remove this:
contentType: "application/json; charset=utf-8",
You aren't sending json, you are sending a GET request. Instead, add this
dataType: "json",
so that jQuery expects to receive json.
It also may help to have your server return headers setting the contentType to application/json with the proper charset utf-8.

Categories