Ahmad Gulzar
Ahmad Gulzar

Reputation: 363

php post not working using header and ajax

i am sending a post request using jquery $.post to another domain. every thing works fine but i am not getting the posted data in the requested page please check my code

jquery code

    var data = {mydata: 'testing'};
      $.post("http://anyurl/file.php",data,function(info){
        alert(info);
    });

and here is php code

<?php

header('Access-Control-Allow-Origin: *'); // this is to allow another domain

$data = $_POST[“mydata”]; // assigning data to variable
echo $data; // sending back to jquery

?>

it does not return the data please check anyone.

Thanks in advance

Upvotes: 0

Views: 87

Answers (3)

GautamD31
GautamD31

Reputation: 28753

Try to get the POST variable with single quotes and better to put exit after echoing it like

$data = $_POST['mydata'];
echo $data; 
exit;

And make sure that it is posting to the given URL or not through console.

Upvotes: 1

Zjmainstay
Zjmainstay

Reputation: 123

OK,It walk well when I test it.In order to reappear the error you've got,I'm trying to set the file.php into a BOM-UTF8 file and it got error in the end.So,please check your file.php if it got a BOM before header().

Another suggess,you can use firebug to test your ajax post process.The link in the console will show you the ajax process,such as what you've post and what is feedback.Just use console.log() instead of alert().

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Use proper quotes and use isset() to check the data set or not like,

<?php
    header('Access-Control-Allow-Origin: *'); // this is to allow another domain    
    print_r($_POST);// to check the post data
    $data = isset($_POST['mydata']) ? $_POST['mydata'] : "No Data";
    echo $data; // sending back to jquery
?>

Upvotes: 3

Related Questions