Ajax POST error (400 BAD REQUEST) - javascript

and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at

It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})

I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function

You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.

$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});

Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"

Related

AJAX to asmx (VB) webmethod - GET with parameters

I've been reading a lot of questions about this error, but just can't seem to get around it (it's incredible how many questions can be found on the web on this topic!!). Let me be straight:
test.asmx
'Simple POST (obviously with parameters)
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json)>
Public Function TestarPost(ByVal Valor as String) As String
Dim x
End Function
'Simple GET - no parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function Testar() As String
return "ok ;>D"
End Function
'GET with parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function TestarGet(ByVal Valor as String) As String
return Valor
End Function
Trying it out in js console window:
obj = { Valor: "x" }
$.ajax({
type: "POST",
url: "test.asmx/TestarPost",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success!
$.ajax({
type: "GET",
url: "ServerSide.asmx/Testar",
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success! Returns correctly data in JSON format
$.ajax({
type: "GET",
url: "test.asmx/TestarGet",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Fails! Doing the same as in Post
The message error is "Invalid web service call, missing value for parameter: \u0027Valor\u0027." Also fails if I send object literal ("Invalide JSON primitive"). However, if I access URL .../ServerSide.asmx/TestarGet?Valor=x, it returns "opa" (maybe a clue?)
What I don't get (pardon the pun) is why, since it's the same as in POST. Maybe because the POST isn't affecting anything and I can't see the result (but it returns no errors, at least).
My goal is to create a function serverSide(asmxMethod, obj) to make a generalized bridge between client and server functions.
I've found a solution (but not an answer). According to a friend, GET doesn't accept json parameters. Unfortunately, even if I send dataType: "text" it fails.
The solution is to use always POST. POST is also able to return data (didn't know that). So with the POST example I can send and receive data in json format without a problem.

Javascript send Json Data

How to send json string via ajax and convert json string to xml?
Error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
$.ajax({
async: true,
url: "WebForm1.aspx/btnSave",
type: "POST",
data: "{data: '" + "{'?xml': {'#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}" + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response.d);
},
error: function (error) {
debugger;
alert(error);
}
});
if send $.ajax data: '{data: "something"} - work perfect, how to put "json like string" instead "something"
WebForm.aspx.cs
[System.Web.Services.WebMethod]
public static string btnSave(string data)
{
string response = "";
try
{
XmlDocument xmlDocument = (XmlDocument)JsonConvert.DeserializeXmlNode(data);
xmlDocument.Save(Server.MapPath("output.xml"));
response = "success";
}
catch (Exception ex)
{
response = "error" + ex.Message;
}
return response;
}
I just want get this string ---------> "{'?xml': {'#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}" + "'}" ------------ in webmethod btnSave and convert it to xml format
the problem lies in the way you are telling jQuery which data to post :
You probably got confused, since the parameter passed on to $.ajax has a property named data.
You are now passing a string right into there, while you should be passing a Json dictionary which contains which variable names and values you want to send.
try this :
Your entire call should look something like this :
(i'm keeping the data you are trying to send in a separate variable for clarity)
var stringData ="{'?xml' : '#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}";
$.ajax({
async: true,
url: "WebForm1.aspx/btnSave",
type: "POST",
data: {data:stringData},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response.d);
},
error: function (error) {
debugger;
alert(error);
}
});
You can't send the data as the json string. You need to call JSON.parse (json_string_here_).
It is also possie that you might need put instead of post, but i cant be sure of that because i dont know if you are doing an insert or update.
Sorry, even after that ive got to say that id be a little more than impressed if you can send an xml file like that. I would imagine that doesnt work very well.

How to pass parameters in GET requests with jQuery

How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];

jQuery.Ajax Post to webservice

I need to post data to my backend system (SAP). I'm trying to use the following code:
Hardcoded the URL example:
var dataString = ""
//Add TO SAP.
var aData =
jQuery.ajax({
type: "POST",
//contentType: "application/xml",
url: "http://delyo001.you.local:8000/sap/bc/youconsulting/ws/rest/anonymous/z_names_post?firstname=testz&lastname=zefzef", // for different servers cross-domain restrictions need to be handled
data: dataString,
//dataType: "json"
success: function(xml) { // callback called when data is received
//oModel.setData(data); // fill the received data into the JSONModel
alert("success to post");
},
error: function(xml) { // callback called when data is received
//oModel.setData(data); // fill the received data into the JSONModel
alert("fail to post");
alert(xml);
}
});
The webservice works via SOAPUI. But not via this way.
Can anyone please guide to what's wrong with this code.
Kind regards,
Vincent
Try set a header as:
header : { "Content-Type" : "application/x-www-form-urlencoded" }

Accessing ajax POST response in javascript

I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
From my handler, I'm sending json string with:
context.Response.write(json);
I think I'll get it in msg.
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
If this is right way to do it, how can I access it in my success function?
To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
Otherwise, it will just be returned to you as text.
Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.
function UpdateMetrics() {
var callback = $.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
var headerdata = callback.getResponseHeader("MaxCount");
// Where MaxCount is name provided in the header.
...
}
});
}
Thanks

Categories

Resources