Jquery AJAX always errors - javascript

I am using nginx web server and running a website on localhost. I want to be able to get my files through the server with jquery's AJAX function but it always throws an error. I've made a folder called TESTFOLDER inside my 'data' folder and it has a txt file called test.txt.
This is my javascript code
$.ajax({
url: "../data/TESTFOLDER/",
type: 'GET',
dataType: "txt",
headers: {
Accept : "text/html",
"Content-Type": "text/html"
},
success: function(data){
console.log('there was a success');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('there was an error');
}
});
This is my nginx configuration block for the folder
location /data/TESTFOLDER/ {
autoindex on;
try_files $uri $uri;
add_header Content-Type application/txt;
}
I always get this error:
NetworkError: 500 Internal Server Error
when it tries to reach the data/TESTFOLDER
I have of course tried it simpler than this, without the headers and all that. Nothing seems to work though. Please help if you can.
EDIT:
Yes, I can get to the file by typing out local host/data/TESTFOLDER/test.txt in my browser.
The ../ doesn't seem to be causing problems because in both cases, I get the error message 500 Internal Server Error - local host/data/TESTFOLDER/, i.e. not local host/../data/TESTFOLDER/
The server error log says: 2020#2644: rewrite or internal redirection cycle while internally redirecting to "/data/TESTFOLDER/", client: 127.0.0.1, server: localhost, request: "GET /data/TESTFOLDER/ HTTP/1.1", host: "localhost", referrer: "http:// localhost/index.html"
NOTE: The word local host is in two seperate words here because they won't allow me to post links.
EDIT2: I should note that while local host/data/TESTFOLDER/test.txt works fine in my browser, local host/data/TESTFOLDER/ throws the error 500. Should this be happening?

your url is malformed. if you want to use a relative path in an Ajax call, you don't need to use the ...
source: Relative URLs in AJAX requests
You can just use url: "/data/TESTFOLDER/". Your current url tries to access http://localhost:63542/../Data/TESTFOLDER/, which probably doesn't exist, but the server tries to locate it and throws an error.

You can catch different http-statuscodes with ajax.
Example:
$.ajax({
statusCode: {
500: function() {
// do something
}
}
});

You misuse try_files and get internal redirection loop.
Also, MIME type for text is text/plain.

Related

File creation works from localhost but not from mobile

I am trying to send a file creation request to a remote RESTful API.
Whenever I do this from a local server, it works fine. Whenever I do this from an iOS device, it fails with a CSRF validation failed error. As far as I can tell, that shouldn't happen as it is the exact same code executing on both devices...
This is built using PhoneGap/Cordova. The version of iOS is iOS 11 and the iOS device is an iPhone 8.
Here's the code:
var mathRandom = Math.random();
var data = {"file": {
"file": base64,
"filename": localStorage.username + mathRandom + ".jpg",
"filepath": "public://" + localStorage.username + mathRandom + ".jpg"
}
};
var result = $.ajax({
type: "POST",
data: data,
url: SITE_URL + "/" + ENDPOINT + '/file.json',
dataType: 'json',
async: false,
error: function (jqXHR, textStatus, errorThrown) {
moduleDebugger('account', errorThrown, "FILE SAVE ERROR");
return 'null';
},
success: function (data, textStatus, jqXHR) {
moduleDebugger('account', data, 'success');
}
});
(Yes, I know it is async, but this block of code absolutely MUST execute before anything after it - I am fine with the UX degradation)
I am using the same user, permissions are currently set so that ANYONE should be able to create files, even anonymously (for testing).
My CORS settings are these:
Internal path
Access-Control-Allow-Origin. Use <mirror> to echo back the Origin header.
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
*|<mirror>|GET, PUT, POST, DELETE|Content-Type, Authorization, X-CSRF-Token|true
What would prevent a mobile user from saving a file, but not a user from localhost? Note, the server where the file will be saved is remote to both of these devices.
This is the error message:
Failed to load resource: the server responded with a status of 401
(Unauthorized : CSRF validation failed)
I am also getting the error:
Failed to load resource: Data URL Decoding Failed
But I am unsure if it is related to the above error - it comes a while after this error occurs. I have been unable to pinpoint what is causing it to occur.
EDIT: Even a static base64 string that I've tested repeatedly on localhost doesn't work.

Cannot get proper json response from my simple nodejs server

SERVER : cloud server, Ubuntu 15.04 x64. nginx is installed listening port 80.
SERVER program : written using NodeJS, simply response in json. like { msg : "done" }
Client (HTML page using React and JQuery) : simple ask the server for the json data.
The problem is on client
// 1)
this.serverRequest = $.get({url:'https://api.github.com/users/octocat/gists', success:function(ret) {
// 2)
//this.serverRequest = $.get({url:'http://my_server_ip_address:7534/test', success:function(ret) {
alert("ok done");
}.bind(this), error:function(e) {
alert("Error : " + e);
}.bind(this)});
I have no problem with 1) request. I do receive some data.
but with 2) request, 'error' function is called and executing 'alert('Error :' + e);' only shows 'Error : [object Object]'. It does not show any useful information..
So I thought my nodejs server program has some problems and I went on searching for answers. I think I try all possible answers..
1) setting iptable to accept port 7534.
2) making nodejs server to listen on 0.0.0.0
3) using res.json().. res.jsonp()
I can see {msg : "done"} if I try with Chrome. so I guess my nodejs server works.
Look the message of error. Instead of alert(e) use console.log(e), for see properties of object e.
ok following #Juven_v 's answer..I figured the 'object' was Error object. And I was able to see the error message through console.log(e).
Here is summary of the solution I found:
1) When the server program responses, put header **Access-Control-Allow-Origin with value *.
I am using nodeJS with express so the code is
res.header('Access-Control-Allow-Origin', '*');
And the client requests with the url.
I use JQuery and the code is
$.get({
url: "http://address!!!!",
type: "GET",
success: function(result) {
console.log("yay");
console.log(result);
},
error: function (err) {
console.log(err);
},
});
If the above client code does not work, then try to add 'dataType: "json"'
2) If I add the following code in the server program..
res.header('Access-Control-Allow-Headers', 'Content-type');
then the client request must have
//contentType: "application/json",
References :
How does Access-Control-Allow-Origin header work?
jQuery AJAX to node server throws net::ERR_CONNECTION_REFUSED
net::ERR_CONNECTION_REFUSED Error jQuery ajax node.js
THANK YOU ALL!!!!

JQuery ajax GET request to URL fails although HTTP status is 200 OK

I apologize if this question has already been answered.
I am trying to retrieve data from a REST web service that exposes a JSON interface using jQuery .ajax call.
When I call the service using the URL, the jQuery call fails although I get a HTTP status code 200 OK.
When I copy the response into a file on the filesystem and retrieve this, the same call works.
Both the file I am accessing and the web service I am calling are on the same machine.
Some notes on the url used in the code below:
Using:
url: "http://localhost:9090/app/user/861",
the call fails, goes into .fail on all browsers.
The URL itself returns the json on all browsers:
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
when using "test.json" in the local filesystem following is the behavior:
url: "ajax/test.json",
On Firefox, the call executes, goes into .done and displays the result on page.
On Chrome, the call fails with status 404 and the following message -
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I tried different combinations changing dataType:"jsonp", adding a ?callback=? to the end of the URL, and enclosing the data in the test.json with a '(' and a ')' without luck.
Please understand I am new to UI programming, javascript and jQuery.
Please help with what I am doing wrong. Here's the javascript:
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url:"ajax/test.json",
// the following commented call fails, goes into .fail
// url:"http://localhost:9090/app/user/861",
contentType: "application/json",
accepts: "application/json",
dataType: "json"
})
.done(function(data) {
alert("Success");
console.log(data);
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
})
.fail(function(data) {
console.log(data);
alert("Failed");
})
.always(function() {
alert("In Always");
});
});
</script>
The following is the output when I paste the url into the browser (also the contents of ajax/test.json):
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
Your problem is not about UI programming, it's about the security model of modern browsers :p
Access-Control-Allow-Origin errors occurs when you call a webservice (ie: load a JSON file) from a domain that is different from the one hosting your HTML page.
In your case, you are opening the html file from your hard drive (file:///) and calling a webservice on localhost.
This is a security feature in all modern browsers that forbid getting data from a foreign webservice without the webservice owners authorizing you (or everyone, wildcards are allowed) to call it.
I recommend reading the following guide from MDN, so that you understand WHY you are having this problem.
It will then be easy to resolve
https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
If you control the source code of the webservice, or the webserver hosting it, you need to add Access-Control-Allow-Origin HTTP headers.
Do you make your ajax call using Apache on wamp, lamp, xampp or mamp or not? I think you work directly using some files lets say on your desktop and not from the www file of wamp. If the browser sends a correct url then the backend responds great, your frontend code seems fine so i think chrome complains about your not using localhost. Am i right? Whats your local development setup?
If it's a local file on the client-side, use file:/// to prefix the URL:
url: 'file:///ajax/test.json'
The third / in file:/// indicates:
As a special case, can be the string "localhost" or the empty
string; this is interpreted as `the machine from which the URL is
being interpreted'.
3.10
Reference here
Download a tool called fiddler, from http://fiddler2.com/ great way to debug web requests and to see why they are failing.
This will help you narrow down the issue you are experiencing and we can help you further because currently its all guess work.
I had the same issue, all worked fine in I.E and FireFox, a had one ajax call to a rest service using jsonp and it worked fine in chrome, however when I tried to load a file using jsonp I got the cross domain error. In short i had to add "file:" to my file path in the url
$.ajax({
type : 'GET',
url : 'file:jsondata/rain_acc_data.json',
dataType : 'jsonp',
jsonpCallback : "jsoncallback",
success : function(data) {
aler('ok');
},
error : function(jqXHR, status) {
alert("Failed to load list" + status + jqXHR);
}
});
this worked for me, make sure to wrap your json in the file with jsoncallback("your jason here");

Dojo XHR don't send a request to other server at all, but everything works in jQuery

I have the development enviroment consisting of the Apache HTTP server for fast Javascript development and the application server (WebSphere) that provides the JSON REST API. Of course, Access-Control-Allow-Origin is set (to *).
The following code results in error:
xhr.post({
url: "http://localhost:8080/rest-sample/rest/test/list",
handleAs: "json",
load: onload
});
RequestError: Unable to load
http://localhost:8080/rest-sample/rest/test/list status: 0
ErrorCtor()create.js (Zeile 13) onError()xhr.js (Zeile 80)
var err = Error.call(this, message),
There is a JavaScript error thrown instead of sending the AJAX request. However, in the same time, the following jQuery snipplet function perfect:
var url = "http://localhost:8080/rest-sample/rest/test/list"
$.post(url, {}, onLoad, 'json')
My question is: what I'm doing wrong? How to send the AJAX request to the other server using Dojo?
I'm using dojo 1.9
Your server must also send Access-Control-Allow-Headers: x-requested-with.
I think xhr.post is no longer supported, i suggest to use dojo/request, or at least dojo/request/xhr
require(["dojo/request/xhr"], function(xhr){
xhr("http://localhost/rest-sample/rest/test/list", {
handleAs: "json",
method: "POST"
}).then(function(data){
// Do something with the handled data
}, function(err){
// Handle the error condition
}, function(evt){
// Handle a progress event from the request if the
// browser supports XHR2
});
});
If it's Cross origin problem i would suggest using ReverseProxy on your http server.
add this to your httpd.conf
ProxyPass /rest-sample/ http://localhost:8080/rest-sample/

JQuery Ajax Post results in 500 Internal Server Error

I am trying to perform this AJAX post but for some reason I am getting a server 500 error. I can see it hit break points in the controller. So the problem seems to be on the callback. Anyone?
$.ajax({
type: "POST",
url: "InlineNotes/Note.ashx?id=" + noteid,
data: "{}",
dataType: "json",
success: function(data) {
alert(data[1]);
},
error: function(data){
alert("fail");
}
});
This is the string that should be returned:
{status:'200', text: 'Something'}
I suspect that the server method is throwing an exception after it passes your breakpoint. Use Firefox/Firebug or the IE8 developer tools to look at the actual response you are getting from the server. If there has been an exception you'll get the YSOD html, which should help you figure out where to look.
One more thing -- your data property should be {} not "{}", the former is an empty object while the latter is a string that is invalid as a query parameter. Better yet, just leave it out if you aren't passing any data.
in case if someone using the codeigniter framework, the problem may be caused by the csrf protection config enabled.
This is Ajax Request Simple Code To Fetch Data Through Ajax Request
$.ajax({
type: "POST",
url: "InlineNotes/Note.ashx",
data: '{"id":"' + noteid+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
},
error: function(data){
alert("fail");
}
});
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
type:'POST'
I experienced a similar compound error, which required two solutions. In my case the technology stack was MVC/ ASP.NET / IIS/ JQuery. The server side was failing with a 500 error, and this was occurring before the request was handled by the controller making the debug on the server side difficult.
The following client side debug enabled me to determine the server error
In the $.ajax error call back, display the error detail to the console
error: (error) => {
console.log(JSON.stringify(error));
}
This at least, enabled me to view the initial server error
“The JSON request was too large to be serialized”
This was resolved in the client web.config
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
However, the request still failed. But this time with a different error that I was now able to debug on the server side
“Request Entity too large”
This was resolved by adding the following to the service web.config
<configuration>
…
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferPoolSize="524288">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
The configuration values may require further tuning, but at least it resolved the server errors caused by the ajax post.
You can look up HTTP status codes here (or here), this error is telling you:
"The server encountered an unexpected condition which prevented it from fulfilling the request."
You need to debug your server.
I run into the same thing today. As suggested before get Firebug for Firefox, Enable Console and preview POST response. That helped me to find out how stupid the problem was. My action was expecting value of a type int and I was posting string. (ASP.NET MVC2)
There should be an event logged in the EventVwr (Warning from asp.net), which could provide you more details on where the error could be.
A 500 from ASP.NET probably means an unhandled exception was thrown at some point when serving the request.
I suggest you attach a debugger to the web server process (assuming you have access).
One strange thing: You make a POST request to the server, but you do not pass any data (everything is in the query string). Perhaps it should be a GET request instead?
You should also double check that the URL is correct.
I just face this problem today. with this kind of error, you won't get any responses from server, therefore, it's very hard to locate the problem.
But I can tell you "500 internal server error" is error with server not client, you got an error in server side script. Comment out the code closure by closure and try to run it again, you'll soon find out you miss a character somewhere.
You can also get that error in VB if the function you're calling starts with Public Shared Function rather than Public Function in the webservice. (As might happen if you move or copy the function out of a class). Just another thing to watch for.
Can you post the signature of your method that is supposed to accept this post?
Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:
<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
$.ajax({
type:'POST',
url:url,
data:message,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:successFunc,
error:errorFunc
});
};
Then my errorFunc javascript is like this:
function(request, textStatus, errorThrown) {
$("#install").text("Error doing auto-installer search, proceed with ticket submission\n"
+request.statusText); }
Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery's library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:
<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>
so check all that, and post your controller method signature in case that's part of the issue
I found myself having this error to. I had .htaccess redirect configured in a directory. Well it reroutes ajax calls to ofcourse ($.post(../ajax.php)), so it couldn't find the actual file (resulting in 500 error).
I 'fixed' it by placing the ajax.php in a directory (So .htaccess didn't affect).
I was able to find the solution using the Chrome debugger (I don't have Firebug or other third-party tools installed)
Go to developer tab (CTRL+MAJ+I)
Network > click on the request which failed, in red > Preview
It showed me that I had a problem on the server, when I was returning a value which was self-referencing.
In my case it was simple issue, but hard to find. Page directive had wrong Inherits attributes. It just need to include the top level and it worked.
Wrong code
<%# Page Language="C#" CodeBehind="BusLogic.aspx.cs" Inherits="BusLogic"%>
Correct code
<%# Page Language="C#" CodeBehind="BusLogic.aspx.cs" Inherits="Web.BusLogic" %>
When using the CodeIgniter framework with CSRF protection enabled, load the following script in every page where an ajax POST may happen:
$(function(){
$.ajaxSetup({
data: {
<?php echo $this->config->item('csrf_token_name'); ?>: $.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>')
}
});
});
Requires: jQuery and jQuery.cookie plugin
Sources: https://stackoverflow.com/a/7154317/2539869 and http://jerel.co/blog/2012/03/a-simple-solution-to-codeigniter-csrf-protection-and-ajax
The JSON data you are passing to the server should have same name as you forming in client side.
Ex:
var obj = { Id: $('#CompanyId').val(),
Name: $("#CompanyName").val()
};
$.Ajax(data: obj,
url: "home/InsertCompany".....
If the name is different, ex:
[HttpPost]
public ActionResult InsertCompany(Int32 Id, string WrongName)
{
}
You will get this error.
If you are not passing the data, remove the data attribute from AJAX request.
I had this issue, and found out that the server side C# method should be static.
Client Side:
$.ajax({
type: "POST",
url: "Default.aspx/ListItem_Selected",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: ListItemElectionSuccess,
error: ListItemElectionError
});
function ListItemElectionSuccess(data) {
alert([data.d]);
}
function ListItemElectionError(data) {
}
Server Side:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static String ListItem_Selected()
{
return "server responce";
}
}
As mentioned I think your return string data is very long. so the JSON format has been corrupted.
There's other way for this problem. You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
Use a Try Catch block on your server side and in the catch block pass back the exception error to the client. This should give you a helpful error message.
I also faced the same problem. Here are two ways by which I have solved it-
1. If you're using some framework, make sure you are sending a CSRF token with the ajax call as well
Here is how the syntax will look like for laravel -
<meta name="_token" content="{{ csrf_token() }}">
In your js file make sure to call this before sending the ajax call
$.ajaxSetup({
headers: {
'X_CSRF-TOKEN' : $('meta[name="_token"]').attr('content')
}
});
Another way to solve it would be to change method from post to get
For me, the error was in php file to which i was sending request.
Error was in database connectivity. After fixing the php code, error resolved.
Your code contains dataType: json.
In this case jQuery evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner. Any malformed JSON is rejected and a parse error is thrown. An empty response is also rejected.
The server should return a response of null or {} instead.
I found this occurred in chrome when I did two ajax queries in the jquery 'on load' handler,
i.e. like $(function() { $.ajax() ... $.ajax() ... });
I avoided it using:
setTimeout(function_to_do_2nd_ajax_request, 1);
it's presumably a chrome and/or jquery bug
I had this problem because the page I called ajax post from had EnableViewState="false" and EnableViewStateMac="false" but not the page called.
When I put this on both pages everything started to work. I suspected this when I saw MAC address exception.
Your return string data can be very long.
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
For example:
1 Char = 1 Byte
5 Char = 5 Byte
"Hakki" = 5 Byte
I have had similar issues with AJAX code that sporadically returns the "500 internal server error". I resolved the problem by increasing the "fastCGI" RequestTimeout and ActivityTimeout values.
I'm late on this, but I was having this issue and what I've learned was that it was an error on my PHP code (in my case the syntax of a select to the db). Usually this error 500 is something to do using syntax - in my experience. In other word: "peopleware" issue! :D
As an addition to the "malformed JSON" answer, if the query you are running returns an object or anything that prevents the data to be serialised, you will get this error. You should always be sure you have JSON and only JSON at the end of your action method or whatever it is you are getting the data from.
Usually your property is not completely right or something wrong with your server processing.

Categories

Resources