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);
}
});
Related
I want to use POST method with AJAX in SAPUI5 javascript but I found an error.
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({
nomorDosir: "01001961288",
kodeCabang: "A02"
}),
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: " + data + " " + JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});
error:
I already did change code with dataType=text, or data: {nomorDosir: "01001961288", kodeCabang: "A02"} (without stringify), but I not yet find the solution. How to fix this problem?
Thanks.
Bobby
Not sure what your use case is but if you are trying to post to an oData service, it might be much easier to use SAPs createEntry method where the URL is the path to the model you want to post to and your JSON are the properties:
var oModel = new sap.ui.model.odata.v2.ODataModel("https://services.odata.org/V2/OData/OData.svc/");
//oModel should use your service uri
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
oModel.createEntry(url, {
properties: {
nomorDosir: "01001961288",
kodeCabang: "A02"
}
}, {
method: "POST",
success: function(response) {
alert(JSON.stringify(response));
//do something
},
error: function(error) {
alert(JSON.stringify(error));
}
});
oModel.submitChanges();
What you have is wrong json format, you have:
data: JSON.stringify({nomorDosir: "01001961288", kodeCabang: "A02"}),
Which actually should be:
data: {"nomorDosir": "01001961288", "kodeCabang": "A02"},
Which then you don't need to do a json.stringify on, because it already IS a json format. Hope this will help you out.
Which you could also try is setting a variable outside like this:
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
var json = {"nomorDosir": "01001961288", "kodeCabang": "A02"};
$.ajax({
type: "POST",
url: url,
data: json,
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: "+data+" "+JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});
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.
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
i need to read string from my customer server.
the string that i need to call is:
http://xxx.xxx.xxx.xxx:8082/My_ws?applic=MyProgram&Param1=493¶m2=55329
The result I get is a string.
If I run it in the browser I get an answer string - OK
i need to get it in my HTML & javascript program
i try this:
function Look() {
$.ajax({
ServiceCallID: 1,
url: 'http://xxx.xxx.xxx.xxx:8082/My_ws?applic=MyProgram&Param1=493¶m2=55329',
type: 'POST',
data: '{"Param1": "' + 2222 + '"}',
data: '{"Param2": "' + 3333 + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
ALL = (data.d).toString();
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
Try this, you need to use stringify if the data is Json otherwise remove JSON.stringify, you cannot have 2 data parameters either, your using utf-8 presume that is a MS web srvc, if your sending data up it's post (usually).
$.ajax({
type: 'Post',
contentType: "application/json; charset=utf-8",
url: "//localhost:38093/api/Acc/", //method Name
data: JSON.stringify({ someVar: 'someValue', someOtherVar: 'someOtherValue'}),
dataType: 'json',
success: someFunction(data), // pass data to function
error: function (msg) {
alert(msg.responsetext);
}
});
I'm trying to get some information from a different domain, the domain allows only jsonp call - others get rejected. How can I get the content instead of execution? Because I get an error in response. I don't need to execute it, I just need it in my script. In any format (the response is json but js doesn't understand it).
I can't affect on that domain so it's impossible to change something on that side.
Here's my code:
$.ajax({
url: url + '?callback=?',
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
window.jsonpCallback = function(response) {
console.log('callback success');
};
There are a few issues with your $.ajax call.
$.ajax({
url: url + '?callback=?',
// this is not needed for JSONP. What this does, is force a local
// AJAX call to accessed as if it were cross domain
crossDomain: true,
// JSONP can only be GET
type: "POST",
data: {key: key},
// contentType is for the request body, it is incorrect here
contentType: "application/json; charset=utf-8;",
// This does not work with JSONP, nor should you be using it anyway.
// It will lock up the browser
async: false,
dataType: 'jsonp',
// This changes the parameter that jQuery will add to the URL
jsonp: 'callback',
// This overrides the callback value that jQuery will add to the URL
// useful to help with caching
// or if the URL has a hard-coded callback (you need to set jsonp: false)
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You should be calling your url like this:
$.ajax({
url: url,
data: {key: key},
dataType: 'jsonp',
success: function(response) {
console.log('callback success');
},
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
JSONP is not JSON. JSONP is actually just adding a script tag to your <head>. The response needs to be a JavaScript file containing a function call with the JSON data as a parameter.
JSONP is something the server needs to support. If the server doesn't respond correctly, you can't use JSONP.
Please read the docs: http://api.jquery.com/jquery.ajax/
var url = "https://status.github.com/api/status.json?callback=apiStatus";
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'apiStatus',
success: function (response) {
console.log('callback success: ', response);
},
error: function (xhr, status, error) {
console.log(status + '; ' + error);
}
});
Try this code.
Also try calling this url directly in ur browser and see what it exactly returns, by this way You can understand better what actually happens :).
The jsonpCallback parameter is used for specifying the name of the function in the JSONP response, not the name of the function in your code. You can likely remove this; jQuery will handle this automatically on your behalf.
Instead, you're looking for the success parameter (to retrieve the response data). For example:
$.ajax({
url: url,
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
success: function(data){
console.log('callback success');
console.log(data);
}
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You can also likely remove the other JSONP-releated parameters, which were set to jQuery defaults. See jQuery.ajax for more information.