4

I am receiving the 406 error when I am sending a JSON data object through the jQuery AJAX function to a backend service so the data can be stored into the database.

AJAX FUNCTION

data = {
  questions: questions,
  test_id: test_id,
  action: 'update'
};

gmtjax({
    url: gmt.contextPath + 'tests/questions/process_form',
    type: 'POST',
    data: data,
    dataType: 'json',
    $spinner: gmt.$spinnerContainer,
    success: function(returnData) {
      console.log('success');
    },
    error: function(){
      //console.log('error');
    },
    $errorContainer: gmt.$mainContainer
});

JSON structure:

{
    "test_id": "1",
    "action": "update",
    "questions": [
        {
            "question": "Exploitation strategies seek to create value from unfamiliar resources and activities.",
            "options": [
                {
                    "name": "True"
                },
                {
                    "name": "False"
                }
            ]
        }
    ]
} 

Process Form Function (Backend)

function process_form(){
  print_r($_POST);
}

When I submit the data the STATUS CODE on the XHR request is 406 Not Acceptable.

Request Header

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,af;q=0.6,ms;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:1726
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:ci_session=08c62699d06dfcf8ba853cacb350ab3b
Host:testingsite.com
Origin:https://testingsite.com
Pragma:no-cache
Referer:https://testingsite.com/tests/manage/id/194/goto/2
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
X-Requested-With:XMLHttpRequest

RESPONSE

false

When the request fails it does not even enter the process_form function to print out the POST array.


However, when I modify the 'create value' string in the question to something like 'create a value' the form submits successfully. The only thing I can think of is some SQL Injection prevention detection on the server layer (GoDaddy) but I am unsure on how to address this.

What could be causing the 406 error when Content-Type is obviously not the issue.

12Bo
  • 116
  • 1
  • 3
  • 11
  • you have to first pinpoint what the problem is. Either your json is sometimes malformed or doesn't contain what the backend requires, or there's something wrong with the backend. – Kevin B Aug 04 '14 at 17:47
  • Can you share the code that is firing the AJAX request and the code that is processing on the back end as well? – Jason Bell Aug 04 '14 at 17:51
  • did you try to remove the dataType: 'json' and submit anything else just to check if it works? That way you can be sure if its the json or another thing. – pecci Aug 22 '14 at 19:57
  • Does `process_form` get called `process_form()` ? – guest271314 Aug 25 '14 at 15:09
  • @guest271314 - That is web service so the process_form() is called based on the URL. – 12Bo Aug 26 '14 at 18:02
  • @12Bo Does `data` get stored at db ? At Question , `success` callback appear to be `console.log("success")` ? Does `console` return `"success"` ? Is requirement to return results of `print_r()` to `console` at `success` callback ? Thanks – guest271314 Aug 27 '14 at 00:09

7 Answers7

4

It could be caused by a module called mod_security and it can cause this problem. Your code looks fine to me. So, check out your host, see if mod_security is installed and enabled, and if it is, try disabling it temporarily and then test this code again. If mod_security is not the culprit, don't forget to re-enable it.

jay_t55
  • 11,362
  • 28
  • 103
  • 174
2

The problem is that you are sending post data as application/x-www-form-urlencoded, while your service probably requires application/json. Try sending actual JSON:

gmtjax({
    url: gmt.contextPath + 'tests/questions/process_form',
    type: 'POST',
    data: JSON.stringify(data),
    contentType: "application/json",
    dataType: 'json',
    $spinner: gmt.$spinnerContainer,
    success: function(returnData) {
      console.log('success');
    },
    error: function(){
      //console.log('error');
    },
    $errorContainer: gmt.$mainContainer
});
Jonathan Amend
  • 12,715
  • 3
  • 22
  • 29
  • Are you using any particular frameworks on the PHP site? What's the call stack that should lead to `process_form()`? What are the new request headers and full response headers? (please update the question with this info) – Jonathan Amend Aug 26 '14 at 18:06
1

Try

at close of php at process form page

echo print_r($_POST);

at success callback

console.log(returnData);

if request , response successful , should return

Array
(
    [test_id] => 1
    [action] => update
    [questions] => Array
        (
            [0] => Array
                (
                    [question] => Exploitation strategies seek to create value from unfamiliar resources and activities.
                    [options] => Array
                        (
                            [0] => Array
                                (
                                    [name] => True
                                )

                            [1] => Array
                                (
                                    [name] => False
                                )

                        )

                )

        )

)
1

at error callback

error : function(jqxhr, textStatus, errorThrown) {
  console.log(textStatus, jqxhr.getAllResponseHeaders()
             , errorThrown)
}

at ajaxSetup

$.ajaxSetup({
   statusCode : {
            200 : function (data, textStatus, jqxhr) {
                    console.log(data);
            },
            406 : function (jqxhr, textStatus, errorThrown) {
                    console.log(textStatus + "\n" + errorThrown);
            }
        }
 });

try log both 200 success , 406 statusCode error.

guest271314
  • 1
  • 15
  • 104
  • 177
1

406 Not Acceptable error using jQuery AJAX It turned out the problem was that I was submitting the ajax request using the POST method but not actually sending any post data. For example:

  $.ajax({
   type: "POST",
   url: "index.php?action=foo",
   success: function(msg){
 
    }
  });
Nazmul Haque
  • 720
  • 8
  • 13
0

The symptoms that you're describing are characteristic of a web application firewall put in place by your web host. Contact their support department.

0

Try changing the type of AJAX call to GET from POST type. It might help you.

Somnath Paul
  • 190
  • 1
  • 6
  • 17
  • This wouldn't be possible because the number of questions could by dynamic and don't want to worry about hitting the URL character limit. – 12Bo Aug 26 '14 at 18:04
0

May be a header issue. Try adding this to your $.ajax():

headers: { 
    Accept : "application/json"
}
Zakaria
  • 983
  • 15
  • 24