Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  177] [ 7]  / answers: 1 / hits: 24590  / 10 Years ago, sun, may 25, 2014, 12:00:00

When I am using the following to respond to a button click, it it called (verified by using the console.log()), however, the http request it generated has the header Content-Type: application/x-www-form-urlencoded; charset=UTF-8rn. Shouldn't it be json?



I am using google chrome 34.0.1847.132 on Ubuntu. Jquery version 1.8.3.



Thanks in advance!



function action (mode) {
console.log(action called with mode + mode);
$.ajax({
type: POST,
url: '/saas.php',
data: {
action: (mode == 1)? start : stop
},
dataType: json,
success: function(data) {
//alert(data);
if (data.msg != null) {
alert(data.msg);
} else {
if (mode == 1) {
document.getElementById('createLoadGen').innerHTML = 'creating loadGen...';
setTimeout(checkStatus, 1000);
}
}
}
});
if (mode == 2) {
document.getElementById('createLoadGen').innerHTML = '<button onclick=action(1) >create LoadGen</button>';
document.getElementById('deleteLoadGen').style.display = 'none'
}
}

More From » jquery

 Answers
1

Not generally. The Content-Type header in the request describes the content in the request body, not the type of content that is expected in the response (describing the expected response format is the job of the Accept header).



By default, jQuery will encode the data using the standard encoding used by HTML forms.



Now, it might be that the server is expecting the request to be formatted as JSON, in which case you would need to make the following modifications to the jQuery call:




  1. Say that you are sending JSON

  2. Encode the content you are sending as JSON instead of letting jQuery encode it itself



Such:



  data: JSON.stringify({
action: (mode == 1)? start : stop
}),
contentType: application/json,


sass.php will then have to parse the JSON request instead of letting PHP do it invisibly in the background and just plucking the data out of $_POST.


[#70857] Thursday, May 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yesseniadajab

Total Points: 258
Total Questions: 101
Total Answers: 127

Location: Mexico
Member since Mon, Sep 12, 2022
2 Years ago
;