Viewed   119 times

I have been trying to retrieve JSON data from my php file.Its giving me a hard time.This is my code

Code in my VIEW:

var productDetails = {'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle};

        var base_url = '<?php echo site_url() ?>';
        $.ajax({
            url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart",
            type: 'POST',
            data:productDetails,
            dataType:'JSON',
        });

Trying to retrieve in my Controller:

echo $this->input->post("productDetails");

Outputs Nothing.

Here are my headers:

Remote Address:[::1]:80
Request URL:http://localhost/CI/index.php/user/Add_to_cart/addProductsToCart
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Content-Length:52
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:ci_session=3E5SPro57IrJJkjs2feMNlmMrTqEXrTNN8UyEfleeothNnHwNxuCZDSx4a7cJZGjj7fyr2KLpj%2BPNJeGRSzSPVmcFHVEdhSk4D47ziOl4eZcTUAZlQrWa3EYIeQJVWxMpiGZS26MEfbSXNmfel9e8TcsJTreZHipvfisrJovbXEAW4Uv%2BwrJRep1KCi1MMaDCVJb9UEinRVcDtYe%2F86jhn7kOj4kraVmVzx%2FsOaO0rAxLyAUtez%2Feaa4zBwpN3Td153sAoIb3WxVHoEj2oKyH5prVHigbIhIBR6XZqjBkM6hjBuoD2OSZ2wgLbp9DEENMoqui4WYyHROBuS2DYiJajblcS0KiFga5k%2FQOODvE7p6n%2BozN5ciDliVjJ4PnJ5PD1GaPEmec5%2FbQSlOHYWZk%2F2Blzw3Nw0EtLL7wKDzzQY%3Df645c36bb3548eb8de915b73f8763d97a47783ce
Host:localhost
Origin:http://localhost
Referer:http://localhost/CI/index.php/user/view_available_books/viewAvailableBooks/5
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
X-Requested-With:XMLHttpRequest
**Form Dataview** sourceview URL encoded
id:234
qty:1
price:0.00
name:dasdadsd2q3e!@!@@

My Response which I can See in Developer tools:

    Array
(
    [id] => 234
    [qty] => 1
    [price] => 0.00
    [name] => dasdadsd2q3e!@!@@
)

But in browser, the output is nothing. I am trying to solve it for more than 4 hours now but in vain.

print_r($_POST); // outputs nothing
echo $data = file_get_contents('php://input'); //outputs nothing
echo $id    = $this->input->post('productDetails');// outputs nothing

My View Code:

<script>
    $('#addtoCart').on('click',function(event){
        event.preventDefault();
        $(this).attr('disabled',"disabled");
        finalprice = $.trim($('#price').val());
        finalqty = $.trim($('#quantity').val());

        var productDetails = JSON.stringify({'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle});

        var base_url = '<?php echo site_url() ?>';
        // console.log($);
        $.ajax({
            url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data:productDetails,
            dataType:'html',
        });


    });
</script>

Controller Code:

function addProductsToCart(){
        var_dump(json_decode(file_get_contents("php://input")));
        print_r($_POST);
        // $data = json_decode($_POST["productDetails"]);
        // var_dump($data);
        // echo $data = file_get_contents('php://input');
// print_r(json_decode($data));
        // $id    = $this->input->post('id');
        // $qty   = $this

    }

 Answers

4

General method I use for my Ajax Calls in CI :

JS :

post_array =
{
    "myvar" : "value1",
    "myvar2": "value2"
} 

$.post(baseUrl + "/AjaxController/my_function", post_array,
    function(data)
    {
        var res = jQuery.parseJSON(data);
        alert(res.property);
    }  

Controller :

public function my_function()
{
    $myvar = $this->input->post('myvar');
    $myvar2 = $this->input->post('myvar2'); 

    //Stuff

    echo json_encode($myobject);
}
Friday, October 21, 2022
3
var title = $(this).text();

$.post( // you can simply send json from post method of jquery
    "<?php echo site_url('faq/get_faq_data') ?>", // try to use full url
    {
        title : title
    },
    function( data ) {
        console.log( data );
    },
    "json"
);
Saturday, September 17, 2022
 
jacobj
 
1

Try this:

$(function(){ // start of doc ready.
   $(".faq_title").click(function(e){
      e.preventDefault();  // stops the jump when an anchor clicked.
      var title = $(this).text(); // anchors do have text not values.

      $.ajax({
        url: 'faq/get_faq_data',
        data: {'title': title}, // change this to send js object
        type: "post",
        success: function(data){
           //document.write(data); just do not use document.write
           console.log(data);
        }
      });
   });
}); // end of doc ready

The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().

Tuesday, December 27, 2022
 
leo_nix
 
5

Instead of:

data:{user_id:userId}

try:

data: JSON.stringify({user_id:userId})

The reason for this is that you specified a request content type of application/json so you need to send JSON. In your code you are not sending a JSON request - you are sending a simple application/x-www-form-urlencoded POST request. And since you have already passed the userId in the POST body you probably don't need to repeat it in your url. Use either one or the other method to send this information to your server.

Also in order to more easily debug javascript errors I strongly suggest you to use FireBug. Among many things it allows you to see the exact requests/responses being sent during an AJAX call and analyze the exact error message you are getting from the server. It makes debugging problems much easier.

Monday, August 1, 2022
 
5

Posting javascript object:

  1. pass the plain object to the data option,
  2. leave the contentType option alone. The default option is perfect.

Then you can access the property values of the object in the Request collection as if you have posted a form.

server side:

   string input;
    using(var reader = new StreamReader(Request.InputStream)){
            input = reader.ReadToEnd();
        }

Posting Json:

  1. data: JSON.stringify(person),
  2. contentType: "application/json"

server side:

string json;
using(var reader = new StreamReader(Request.InputStream)){
        json = reader.ReadToEnd();
    }
var person = Json.Decode(json);

Referenced from: http://www.mikesdotnetting.com/article/220/posting-data-with-jquery-ajax-in-asp-net-razor-web-pages

Sunday, September 11, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :