Ajax request works on local server but not online - javascript

I have built my first website and it works on local server but not online. The problem is loading a json file with Ajax. In the published version I get the error message that my object is undefined.
This is a (simplified) version of my code that shows the problem:
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
This is the message in the console when running on local server:
great success! main.js:37:13
Object { id: "brunskar", title: "<h2>Brunskär</h2>", image: "img/countryside.jpg" }
But when I publish online this is what I get:
great success! main.js:37:13
TypeError: torp.items is undefined
In the Utilities Net section I get status code 200 and the whole content of the JSON file is readable under the "reply" tab, so it seems like the file is loaded. But I don't understand why my object is undefined.

Sounds like an asynchronous issue (your page is loading before your ajax call can return the data, therefor it is returned as undefined) one way to solve this is to put a function inside your ajax call that fires your page functions that use the data being returned by the call.
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
function usePageData (); <----calls webpage function utilizing
data
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
Hope that helps!

Problem solved by changing
contentType: "application/json"
to
dataType: "json"!
I used the tip from Patrick Evans in one of the comments. Thank you for the help!

Related

$.AJAX Post not working in JS but works in Advanced Rest Client

I'm having an issue with my JavaScript being able to contact the HttpPost service. I can access the same signature using the "Advance Rest Client Application" for chrome. However when I run my code in Console in Chrome I am unable to reach the service. Any thoughts? What am I missing from the signature on one vs the other? Please let me know if you need any more information.
JS AJAX Request (Stuck in Pending status)
$.ajax({
type: 'POST',
url: 'http://local/r/GetSettings',
data: '[{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]',
dataType: "json",
success: function(data){
alert(data)
},
error : function (error) {
alert("Error: " + error);
console.log("ERROR. not working", error);
}
});
C# Service
[HttpPost]
public ActionResult GetSettings(List<Source> sources)
{
return new ContentResult
{
Content = "{}",
ContentType = "application/json"
};
}
Advanced Rest Client Application (Success in returning {})
http://local/r/GetSettings
Content-Type: application/x-www-form-urlencoded
Payload::: [{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]
Change your URL for ajax request
AppContextRootName: Your application context root
$.ajax({
type : 'POST',
url : '/AppContextRootName/GetSettings',
dataType : 'json'
});
Thanks for the answers. I found out my issue why the Ajax call was not executing. I found out you can execute a AJAX statement while paused in the debugger!!! So don't try! It will execute and return and object but it will show pending in the network. Once you unpause the actual call is executed. You should just use Alert("Hello world") in the success and error and you will see it come back once you unpause.

Call post on external Rest API with Ajax

I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};
You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

The error function not working

Hi I just tried testing if the error function would return an alert but it didn't fire. I altered the url link hoping that it would generate an alert since it won't be able to find or get json data. All I am getting is "Uncaught TypeError: Cannot read property 'length' of undefined jquery-1.9.1.min.js:3"
$(document).on('pagebeforeshow', '#blogposts', function () {
//$.mobile.showPageLoadingMsg();
$.ajax({
url: "http://howtodeployit.com/api/get_recent_po",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function () {
$.mobile.showPageLoadingMsg(true);
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
success: function (data) {
$.each(data.posts, function (key, val) {
console.log(data.posts);
var result = $('<li/>').append([$("<h3>", {
html: val.title
}), $("<p>", {
html: val.excerpt
})]).wrapInner('');
$('#postlist').append(result).trigger('create');
return (key !== 4);
});
$("#postlist").listview();
},
error: function (data) {
alert("Data not found");
}
});
});
I think the problem is that, when you make the AJAX request your code is executing the success callback, not the error callback. Thus when you execute:
$.each(data.posts, function(key, val) {
The $.each function is trying to get the length of data which is NULL.
It doesn't look right that you have defined a jsonp callback function and yet your still using the success and error callbacks. This SO question might help a bit :
Use of success / jsonpCallback with ajax request
Maybe here $.each(data.posts, data.posts is undefined and that's why you get an error. Log data in success callback and see what it contains.
I created a clean Fiddle. Opening the given URL gives a 301 redirect followed by a 200 JSON response. The HTTP status code says that everything is fine, so jQuery doesn't know there was an error.
You mixed up two different concepts here: jQuery's error callback is for network errors and all these things. If you transport error states inside your JSON with HTTP status code 200 you have to deal with it on your own inside the success callback.
Sorry, SO doesn't allow JS-Fiddle links without code:
beforeSend: function() { console.log('beforeSend'); },
complete: function() { console.log('complete'); },
success:function (data) { console.log('success') },
error: function(data) { console.log('error') }
Thanks everyone for your input. I did take on-board all suggestions. Recommendation from Jason seems to had made more sense so while investigating his suggestion I came to this site to read up more about jasonCallback. removing the jasonCallback option though did not fix the issue but strangely this issue seems to do with the url I was using for my json caalback.
What I then did was to change the url from "http://howtodeployit.com/api/get_recent_po" to "http://howtodeployit.com/category/daily-devotion/feed/?json=recentstories" and it worked. Even though both returned error in the console but the second was the one that triggered the error function. Why I am looking into it.

$.post is not working (anywhere)! Why?

My calls to $.post are not working all over my code. I'm not sending the request to other domains and, actually, I'm doing everything localhosted. My localhost alias was automatically defined by the Mac OS X 10.8 as ramon.local and I'm requesting from http://ramon.local/linkebuy_0.7/resourceX to http://ramon.local/linkebuy_0.7/resourceY. There are no errors on Chrome's console.
The server side doesn't receive the request and I can check it by accessing directly from the browser (typing the URL).
It's not just one call that is not working, none of them are. They were all working days ago and I'm suspicious that I accidentally changed something on my local settings. What could it be?
Here's an example of what I'm facing:
$.post(
<<CORRECT URL INSIDE THE DOMAIN>>,
{},
function(response) {
console.log('THIS SHOULD BE PRINTED ON CONSOLE');
alert('THIS SHOULD BE POPPED UP');
}
);
I don't get the alert, neither the console message while running the code above. So I tried the following:
$.support.cors = true;
$.ajax({
url: "http://ramon.local/linkebuy_0.7",
dataType: "json",
type: "GET",
crossDomain: true,
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
alert(error + " - " + status);
}
});
I just came with $.support.cors = true; and crossDomain: true to check if it was a cross domain issue. So I was alerted No Transport - error same way as before.
What can I do to solve that?
Thanks in advance.
Try this and see if you are getting any alert:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("your url", function() {
alert("success");
}).success(function() {
alert("second success");
}).error(function() {
alert("error");
}).complete(function() {
alert("complete");
});
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
alert("second complete");
});​
Well, I solved the problem in a very strange way.
I deleted the JQuery file and downloaded it again, replacing the old one. Happens it worked out.
So, if you're:
Making AJAX requests that are not cross-domain;
Using JQuery for it (e.g. $.post, $.get, etc);
Getting No Transport AJAX error
Then re-download and replace you're JQuery source.
Else, if you're making cross-domain requests (not this case), then look for JSONP and try to set $.support.cors = true; at the beginning of you're code.
Thanks everyone for the comments and answers.

jQuery $.getJSON not working

I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});

Categories

Resources