0

I have a problem to send the JSON data from JQuery with GET request. This is my JQuery to send the data with GET.

    var xhr = new XMLHttpRequest();
    var url = "http://example.com/share/new?data=" + JSON.stringify({"id": "1", "type": "new", "data": "testabcd"});
    xhr.open("GET", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
        }
    };
    xhr.send();

This is in my Controller file.

    public function share()
    {
        header('Content-type: application/json');

        $Data = json_decode($_GET["data"]);

        $data_share = array(
            'id' => $Data['id'],
            'type' => $Data['type'],
            'data' => $Data['data']);

        $this->db->insert('mytable', $data_share);

        return "200";
    }

The problem is nothing grab in the Controller and the insert query doesn't insert anything. How to fix this problem ? Maybe I do something wrong in my code ? Thank you before.

Antonio
  • 729
  • 3
  • 11
  • 31

1 Answers1

4

when you send json data to php its in doesn't come in $_POST or $_GET its in php://input strem;

the ajax request u send ws not jQuery its core js, which is good but its quite unflexible and tends to break in different browser. i just used the jQuery version of the ajax which is very flexible and cross-browser as well.

try this : JS:

$.ajax({
      method:'POST',
      contentType:'application/json',
      url:'http://example.com/share/new',
      data: JSON.stringify({"id": "1", "type": "new", "data": "testabcd"}),
      success:function(response){
       console.log(response);
      }

   });

PHP:

public function reservation()
{

    $Data = json_decode(file_get_contents('php://input'), true);

    $data_share = array(
        'id' => $Data['id'],
        'type' => $Data['type'],
        'data' => $Data['data']);

    $this->db->insert('mytable', $data_share);

    return "200";
}
Riaz Laskar
  • 1,241
  • 9
  • 15