0

I send data from my view to controller

    $.ajax({
       type: "POST",
       url: "/registerAgency",
       data:  JSON.stringify(data),
       contentType: "application/json; charset=utf-8",
       success: function(responseData, textStatus, jqXHR) {
           alert("data saved")
       },
       error: function(jqXHR, textStatus, errorThrown) {
          alert("error");
       }
   })

});

And I don't understand why my request doesn't use content type application/json but use application/x-www-form-urlencoded

There are such a questions on this forum, but I really haven't any ideas how to resolve such a situation

Oleh K
  • 11
  • 2
  • 7
  • Testing your exact code in jsFiddle works perfectly fine, the request header gets the correct contentType header – adeneo Feb 06 '16 at 18:30
  • What are you trying to JSON.stringify()? Can you show us the sample parameters to be stringified? – duduwe Feb 06 '16 at 18:46
  • instead of data try this dataType :'json' – XAF Feb 06 '16 at 18:52
  • Here is my JSON { "agencyName":"sadf", "description":"asdf", "phoneNumber":"1111111111121", "webSite":"", "address":{ "country":"asdfasdf", "region":"asdf", "postalCode":"23423", "locality":"asdfasdf", "additionalInfo":"asdfasd" } } – Oleh K Feb 06 '16 at 18:59
  • @OlehKh, I deleted my answer because I might have missed something. What are you really trying to accomplish? Based on my simulation, specifying contentType: 'application/json' won't work - no error though and header content-type becomes application/json, but server receives nothing/empty. Can you kindly elaborate on your goal? – duduwe Feb 06 '16 at 19:12

1 Answers1

0

I'm as well a bit curious on this issue as I don't normally use contentType: 'application/json'. The way it's handled is quite different from using $_POST, $_GET, or $_REQUEST. Of course, it is in json content type.

jquery

var data = { "agencyName":"sadf", "description":"asdf", "phoneNumber":"1111111111121", "webSite":"", "address":{ "country":"asdfasdf", "region":"asdf", "postalCode":"23423", "locality":"asdfasdf", "additionalInfo":"asdfasd" } };

$.ajax({
    type: "POST",
    url: ".../registerAgency.php",
    data: JSON.stringify( data ),
    contentType: 'application/json; charset=utf-8',
    success: function(responseData, textStatus, jqXHR) {
       alert(responseData);
    },
    error: function(jqXHR, textStatus, errorThrown) {
      alert("error");
    }   
});

php/server

<?php
    // parameters are not accessible via POST, GET, nor REQUEST
    $res = json_decode( file_get_contents('php://input') );
    var_dump($res);
?>

Reference: Ajax call with contentType: 'application/json' not working

Community
  • 1
  • 1
duduwe
  • 888
  • 7
  • 16