Ajax post not working - html

I am trying to post a form via ajax. Its giving me "405 Method Not Allowed" error. The same html file works if i put the url in the action part of html form and submit it manually on a button click(so its not a csrf issue..rite?).
what could be the problem?

Ensure that you are using the same method for your ajax request.
Maybe you are using "POST" method for you form and "GET" for your ajax request.
CSRF should throw a 403 and if the a method (POST,GET,PUT,DELETE,...) is not allowed you will see a 405 error message.
Edit: Try to submit your form with jquery:
// change the selector!
var data = $("form").serialize();
alert(data);
$.ajax({
type: "POST",
url: "/your-backend.php",
data: data,
});
What does firebug says when you do this?

Related

submitting a form works in some instances, but returns error 403 in other instances

I have an mvc3 application which makes use of an ajaxsubmit to a controller action.
The <form> opening tag in my page appears like this:
<form action="/application/home/Save?Length=0" class="form-horizontal" data ajax="true" data-ajax-method="POST" data-ajax-mode="after" data-ajax update="#jsonResult" enctype="multipart/form-data" id="inputForm" method="post" role="form">
If i submit this form from within the network that the server is based, the post request will always work. But if i submit the form externally, on occasions i get this generic error:
403 Forbidden: You don't have permission to access /application/home/Save on this server.
The above error doesnt always occur. only in particular instances.
Upon analysing the request headers, The only difference i see is Content-length:
They have the following:
The only other difference that i think could be the cause of this issue is in one of the fields in the request payload.
Now one of the fields i pass to the server is in a special code that has tilders and carrot symbols. Here is an example:
------WebKitFormBoundaryvvviIpe8b82tAvOd
Content-Disposition: form-data; name="udfArray"
["1~d^testfield~d^R"]
Whenever the form submit fails, it happens to have the above form data. When it succeeds, the field is set to []
The trouble is, i dont understand why having the code set to ["1~d^testfield~d^R"] should be an issue if it works within the network.
If anyone could point me in the right direction for making this work externally that would be great.
Here is my submit code:
//options for submit action
var options = {
data: {
udfArray: ko.toJSON(self.TempArray()),
title: self.title(),
given_name: self.givenName(),
//... other fields
},
uploadProgress: function () {
},
dataType: "json",
success: function (result) {
//do something
}
};
$('#inputForm').ajaxForm();
$('#inputForm').unbind('submit').submit(function () {
$('#loadingDiv').show();
$(this).ajaxSubmit(options);
return false;
});

calling REST service on form submit

I am trying to call service http://localhost:8080/app/search It gets data in RequestBody as
{
"skills":["c","java"],
"country":["India"],
"state":["Maharashtra","Gujrat"],
"city":["Mumbai","Pune"],
"highestDegree":["MCA","BE"],
"functionalArea":["IT"],
"functionalRole":["Tester"]
}
and header Content-Type:application/json
I tested above service with Postman and it gives me correct output. Now i tried to call above service from html form its giving me error that request is syntactically incorect.
My HTML form is
<form method="POST" action="http://localhost:8080/app/search">
<!--(form ellements with multiple select textbox )-->
</form
Is it right way or I need model from backbone?
It's a wrong way, you have to create a Model and set it's url to your service :
var MyModel = Backbone.Model.extend({
url: '/app/search'
});
and when you click the submit button catch it in your view, set the form data in your model and call it's save function.

Consuming broadbandmap.gov json service errors

I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?
That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.
This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).

jQuery not handling JSON response from AJAX POST

Updated: I'm posting HTML FORM data but expecting to receive JSON data. I am not trying to POST JSON data.
I am trying to get a JSON response back from doing a HTML FORM POST request. I have successfully received a JSON back when using a simple HTML FORM POST request (i.e. not AJAX). My JSON response from the HTML FORM POST is this:
{"success":true,"data":1234567}
The problem occurs when I try to handle the request and response with jQuery's .ajax().
$.ajax({
type: "POST",
url: URL,
data: data1,
dataType: "json",
success: function(data, textStatus, jqXHR) {
alert ("success");
},
error: function(xhr, status, error) {
alert ("Error: " + error);
}
});
After running the above code and debugging in Firebug, it appears that the POST request is going through, but something is going wrong on the handling of the response. Firebug tells me the following regarding the HTTP response from the POST request:
Response Headers
Cache-Control private
Content-Length 31
Content-Type application/json; charset=utf-8
...
So it appears that the 31 bytes of data is being sent. However, when debugging the actual Javascript, the error function gets called and the xhr object is this:
Object { readyState=0, status=0, statusText="error"}
I know the jQuery.ajax() document states that "In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown." However, I believe my JSON is valid as I have checked it at jsonlint.com.
What else could be going wrong?
It looks to me like you are getting a server error. I would check the status code of the response and fix whatever is causing the request to fail on the server.
your getting an error because data1 is not formatted in json, so when it receives the data it gets a parse error. data1 needs to be formatted:
data1={"apikey":apikey,
"firstname":fName
}
I was having the same problem. It seems that this is an issue with Cross Domain.
Finding this SO answer: https://stackoverflow.com/a/7605563/154513
helped me.
Some times Jquery return Internal Error 500 for currectly data.
There is example for read the same json data withour error
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqres.in/api/products/3", true);
xhr.onload = function(){
console.log(xhr.responseText);
};
xhr.send();

Jquery ajax call: how to parse results?

I have a modal dialog (done through jquery UI) that submit a form to a remote controller Action.
This is the jquery function called:
$("fpForm").submit(function() {
$.ajax({
type: "POST",
url: "ForgotPassword",
data: $("#fpForm").serialize(),
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
}
});
});
The action does some verification on the data and then send back a response in JSON format. Let's say, for example, that this is a sample response:
{"result":"NOK","message":"The user is not registered on the system"}
My questions are:
Why the debug alert that I have set in the "success" and "error" block does not are get executed?
How I can write my code to parse the response while remaining in wait for it on the dialog?
How can I write code to block the form elements during the ajax call?
I am sorry if the question could seem stupid for most of you but I am completely new to ajax and I am trying to learn throgh some experienced pattern that I know.
Thank you for your responses
The first error is the usage of $("fpForm").submit instead of $("#fpForm").submit.
If the server sand back JSON data, for example as JsonResult, you should include dataType: "json" to convert result to the object in object. After that you can replace alert(response); to
alert('Result: ' + response.result + ', Message: ' + response.message);
To block the form element I'll recommend you to use jQuery BlockUI Plugin. On the demos you will find different examples of usage and find the way which you like.
My questions are:
Why the debug alert that I have set in the "success" and "error" block
does not are get executed?
How I can write my code to parse the response while remaining in wait
for it on the dialog?
How can I write code to block the form elements during the ajax
call?
If you meant to use the id then you missed the # designator:
$("#fpForm")
Add the sync : true option on the call?
You could either: set the disabled attribute on the form elements AFTER posting the request, or else mask the page with an element (possibly semi-transparent) to divert the inputs.