I have the following code:
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: String(' ' + $('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
The value in InputTextBox has leading 0's but when this is posted to the url the leading 0's are truncated.
When sending json to a server, you should use the built-in JSON.stringify method to create json rather than creating it manually.
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: JSON.stringify($('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
This will result in sending "0005" instead of 0005, which when parsed, will be converted back into the string rather than a number which will lose the leading zeros.
Testing the code on this page;
$.ajax({
type: "Post",
url: '/test',
contentType: "application/json",
data: String(' 004'),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
obviously alerts the 404 page but in the net tab of Chrome and Firefox shows the data is sent correctly ' 004'.
Please re ask your question with the code on the server, as the issue is not client side.
As Kevin B noted ' 004' is a type numeric according to the JSON specification
so if you want the zeros and want to use a JSON library on the server sent the data as '" 004"' or use JSON.stringify(' 004').
Removing contentType: "application/json", in my ajax call fixed the issue for me
Reason:-
contentType: "application/json", will get the values first converted to numbers as it tries to parse your data to JSON. Removing this line from your ajax call will stop the parsing of data.
Note : The parsing will happen not only in your data you are POSTing, but also it will parse the queryStrings in your URL when you use GET method
Related
trying to send an ajax post request
function ajaxCall(request_data) {
alert(request_data['table'] + request_data['name'] + request_data['description']);
$.ajax({
type: "POST",
cache: false,
url: "../src/api.php/InsertTo",
data: request_data,
dataType: "json",
contentType: 'application/json',
success: function() {
alert('good');
/* $('form').hide();
$('h3').append("Object Successfully Inserted!");*/
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown + textStatus);
}
});
it throws error every time, 'request_data' is an object and url return just a simple string for now, please find the problem
You have to use JSON.stringify() method.
data: JSON.stringify(request_data)
Also, contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
Can you try with the below code after using JSON.stringify on the request_data. As per the docs
"The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified."
As you are using dataType: "json" and contentType: 'application/json;' you should convert the javascript value to a proper JSON string.
Please find more in the below link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
function ajaxCall(request_data) {
alert(request_data['table'] + request_data['name'] + request_data['description']);
$.ajax({
type: "POST",
cache: false,
url: "../src/api.php/InsertTo",
data: JSON.stringify(request_data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert('good');
console.log(data); // print the returned object
/* $('form').hide();
$('h3').append("Object Successfully Inserted!");*/
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown + textStatus);
}
});
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.
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.
I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
$.ajax({
type: "GET",
url: "Default.aspx/GetStatus",
data: "{statusText:'" + statusText + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Please advise. You should also know that I'm new into web development.
You can't have a request body in a GET request, you have to use a POST request for that
The string you are constrcting is not valid JSON since:
Property names must be strings
You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON
Generate your JSON programatically.
{
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify({
statusText: statusText
}),
// etc
Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.
Try this:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
var jsonText = new Object();
jsonText.statusText = statusText;
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify(jsonText);,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
I need to get xml document from a server, then client signs it and sends back to server.
At server side I have web method which saves document:
[WebMethod]
public static void SaveSignedDocument(string SignedData)
{
SignedCms signedCms = new SignedCms();
....
}
Then, I get document from a server and after success receive it I make client to sign it and send back. Here is Javascript
// get xml to sign
$.ajax({
type: "POST",
url: "Default.aspx/GetXMLReceipt",
data: "{'ITN': " + ITN + " }",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (xml) {
// xml file was got
var xmlString = xmlToString(xmlData);
// Sign data
var SignedData = SignData(xmlString);
// Send it to server
$.ajax({
url: 'Default.aspx/SaveSignedDocument',
data: "{ 'SignedData': '" + SignedData + "' }",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){
alert('Document was successfully sent!');
}
error: function (data, status, jqXHR) {
alert('Send signed data failed - ' + jqXHR);
}
});
},
error: function (data, status, jqXHR) {
alert('Get data failed - ' + jqXHR);
}
});
The problem is that none of the alert at second requests ever fire. If I change request to synchronous everything is ok but why it does not work like written above? The server receives nothing and if we look to network traffic I see that request was interrupted. Why?
Encode your data properly, do not use any string concatenations. Here's the correct way:
data: JSON.stringify({ ITN: ITN }),
and on your second AJAX request:
data: JSON.stringify({ SignedData: SignedData })
The JSON.stringify method will ensure that you are sending valid JSON to your server by properly encoding the argument.