Makop
Makop

Reputation: 35

No data response when sending ajax request to php

i want to send a json data to my php but there is no response when i access it to my php.

this is my ajax request

    var project = {project:"A"};

 var dataPost = JSON.stringify(project);

     $.ajax({
     url: 'fetchDate.php',
     data: {myData: dataPost},
     type: 'POST',
     datatype:'json',
     contentType: "application/json",  
     success: function(data) {
         alert(JSON.stringify(data));
     }
 });

});

and this is my php where i process the request and return back the data to test

<?php header("Content-Type: application/json; charset=UTF-8");
  $objProject = json_decode($_GET["myData"]);
  echo json_encode($objProject->project); ?>

i'm new to ajax so please i need your help

Upvotes: 0

Views: 65

Answers (2)

Meraki
Meraki

Reputation: 125

you don't need to add the content type on your ajax since you're not actually sending json to the server.

     $.ajax({
     url: 'fetchDate.php',
     data: {myData: project},
     type: 'POST',
     datatype:'json',
    // contentType: "application/json",  
     success: function(data, status, jqXHR) {

         console.log(data,status,jqXHR);
          alert(JSON.stringify(data));
     }
});

no need to stringify project object, in your php just encode it to json

<?php  header("Content-Type: application/json; charset=UTF-8");
 $obj = $_POST['myData'];
 echo json_encode($obj); ?>

you should get json string on alert

Upvotes: 3

verejava
verejava

Reputation: 17

Please try change

$objProject = json_decode($_GET["myData"]);

to

$objProject = json_decode($_POST["myData"]);

because ajax type : 'POST'

$.ajax({
 url: 'fetchDate.php',
 data: {myData: dataPost},
 type: 'POST',
 datatype:'json',
 contentType: "application/json",  
 success: function(data) {
     alert(JSON.stringify(data));
 }

Upvotes: 0

Related Questions