I have working requests code in python and need it in ajax
var jsonData = {"x":"y"};
$.ajax({
url: url,
type: 'POST',
data: jsonData,
//dataType: "JSON",
error: function(e) {
console.log(e);
}
});
json: jsonData, JSON.stringify, 'Content-Type': 'application/json' and changing names doesn't work, I tried a lot of things, but everytime error 400
this python code works fine
payload = {
'a':'b',
'a': 'b'
}
#but it doesn't work with field 'data' or 'params', must be named 'json'
r = requests.post(url, json=payload) #data=payload won't work, otherwise error 400
print(r.text)
try setting contentType: "application/json" on ajax
Related
I have this small but annoying problem. I really not usual with a web thing. I try to request to my php file using ajax jquery. When I want to retrieve the data I send from ajax, it return undefined index. I dunno what's the problem, it make me spend a lot of time to solve it. Thanks
Below is my ajax code
var at=this.name.substring(this.name.length,7);
var value_header = $("#key"+at).val();
var jsObj = { new_value:value_header, id:at, data:'header'};
console.log(JSON.stringify(jsObj));
$.ajax({
type: 'POST',
headers: 'application/urlformencoded',
url: 'admin_crud.php',
data: jsObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log("Sukses");
}
When I call the below code in my php file, the result is 'Undefined index: data'
echo $_POST['data'];
//Edit
So, when I try var_dump($_POST);, the result is array(0) {}. Where is my mistake? I thought I had send the right one
//Edit
As I mention above, I want it to run perfect without error. Thanks
Remove headers, change your datatype to text and catch errors in the ajax call
$.ajax({
type: "POST",
dataType: "text",
data: jsObj,
url: "admin_crud.php",
success: function (result) {
console.log("success", result);
},
error: function (e) {
console.log("Unsuccessful:", e);
}
});
I have another solution beside #Marco Sanchez too, I don't know it always work or not, but in my case, it work :
$.ajax({
type: 'POST',
url: 'admin_crud.php',
headers: "Content-type: application/x-www-form-urlencoded"
data: "new_value="+value_header+"&id="+at+"&data=header",
success: function(data){
console.log("Sukses");
console.log(data);
}
});
I am trying post a string to web service but I am getting this error (Google Chrome Extension Project):
jquery-2.1.1.min.js:4 POST http://localhost:49242/Service.asmx/test
500 (Internal Server Error)
Here is my ajax code:
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify({ 'data': data.param1 }),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
My service:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string test(string param1) {
return param1;
}
I am working on this problem about 3 days. Can you help me ?
By the way, I have a question. I am posting json variable to service with ajax(like you see), but service returning xml value. Is there a problem or [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] this code block solving problem?
Your error come from your data parameter. Stringify data object instead of { 'data': data.param1 } :
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify(data),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
Your stringifyed data will result in {"param1":"Words"}, then your service should be able to bind the param1 parameter.
I was facing this type of error on AJAX post response. I was spending too much time behind this issue and finally I caught it.
It throws a 500 internal error because the AJAX response has a lot of content from the server so it returns a timeout of execution.
So I just added the line below and it's working fine.
Page.Server.ScriptTimeout = 300;
I am working on an app that sends a POST request to a web service. My POST request looks like this:
$.ajax({
type: 'POST', url: getEntityUrl(), cache: 'false',
contentType:'application/json',
headers: {
'api-key':'myKeyHere',
'Content-Type':'application/json'
},
data: {
firstName:'Jon',
lastName:'Smith'
},
success: function() { alert('good job'); },
error: function() { alert('oops'); }
});
When I execute this, I'm getting a 400 Bad Request. I watched the request in Fiddler. I noticed that the parameters I sent are being sent as "firstName=Jon&lastName=Smith". However, they need to be sent across as JSON like I have them defined in the data parameter. I confirmed this is the problem by modifying the request in the composer in Fiddler. What am I doing wrong?
Thanks
If you pass jQuery a plain object through the data parameter (as you do here) then it will encode the data as application/x-www-form-urlencoded.
Just setting the contentType is insufficient.
If you want to send JSON then you must encode it yourself. You can use JSON.stringify for that.
data: JSON.stringify({
firstName:'Jon',
lastName:'Smith'
}),
You need to stringify the data like following.
$.ajax({
type: 'POST',
url: getEntityUrl(),
contentType: 'application/json',
headers: {
'api-key': 'myKeyHere',
'Content-Type': 'application/json'
},
data: JSON.stringify({ firstName: 'Jon', lastName: 'Smith' }), //change here
success: function () { alert('good job'); },
error: function () { alert('oops'); }
});
I'm calling a page (external, on other domain), with this code:
var instagram_container = $('div#instagram-answer');
if (instagram_container.length>0)
{
var url = 'http://www.xxxx.it/admin/get_instagram_token';
$.ajax({
type : 'GET',
url : url,
async : false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(response)
{
console.log(response);
instagram_container.html(response.client_id);
},
error: function(e)
{
console.log(e);
}
});
}
I have answer with console.log(e) (basically it recognizes as error)?
Object { readyState=4, status=200, statusText="success", altri elementi...}
But in Firebug, under NET tab, I have the right answer...
This is the console. Line 19 is exactly the
console.log(e);
in error section.
My goal is obtain that Json. Thank you
Is your server returning plain text, or an actual JSON file? Jquery will ignore the response if the server returned a string instead of JSON.
The response type should be: "application/json"
EDIT:
I'd recommend you to use the basic jquery ajax call:
$.ajax({
url: "test.html",
cache: false
})
.done(function( response ) {
console.log(response);
});
I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});