Sydcpt
Sydcpt

Reputation: 139

AJAX Submit to PHP file not returning the data

When I try to submit data via AJAX to a PHP file, the submit works, and I can echo back a message from the PHP file. However, when I try to echo back the data I am submitting, or, echo back a message confirming that the data matches another variable in the PHP file(which it does), I still get a success message, but it says the data is not the same.

I am new to development and struggling a bit. Any help would be super.

The AJAX

$.ajax({
    type: "POST",
    url: "/check-cust.php",
    data: "1234",
    success: function(data) {
        if (data == "") {
            console.log("success, but no return");
        } else {
            alert(data); // show response from the php script.
        }
    },
    error: function() {
        alert("not working");
    }
});

The PHP

$temp_cust_id = "1234";

$data = $_POST['data'];

if ($data == $temp_cust_id) {
    echo "it works";
} else {
    echo "it doesnt work";
}

Is it maybe because I am submitting a JSON array, which is different to the string variable? That's just a guess though!

Upvotes: 1

Views: 68

Answers (4)

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

the way you are sending data is wrong,

data: {"data","1234"}
        ^      ^
        name    value

To put it all togeather,

$.ajax({
    type: "POST",
    url: "/check-cust.php",
    data: {data:"1234"},// this the line in which you have error.
    success: function(data) {
        if (data == "") {
            console.log("success, but no return");
        } else {
            alert(data); // show response from the php script.
        }
    },
    error: function() {
        alert("not working");
    }
});

Then in php file,

$temp_cust_id = "1234";

$data = $_POST['data'];

if ($data == $temp_cust_id) {
    echo "it works";// it will echo this for current output.
} else {
    echo "it doesnt work";
}

Upvotes: 2

Niraj Karmick
Niraj Karmick

Reputation: 154

post_data='1234';

 $.ajax({
    type: "POST",
    url: "/check-cust.php",
    data: "post_data="+post_data, //-------->>>Pass the data like this
success: function(data) {        
  if (data == "") {  
  console.log("success, but no return");


   } else {


  }

And in php file use:

$_POST['post_data'];

Upvotes: 1

Man Programmer
Man Programmer

Reputation: 5356

For comparing the string strcmp

AJAX

data: {"data":"1234"}

PHP

if (!strcmp($data,$temp_cust_id))
    echo "it works";

Upvotes: 1

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

This false data: "1234",, should be :

data: {
 data : 1234
}

Or give a better name :

data: {
  myData : 1234
}

And in server side :

$_POST['myData'];

Another way by using query string like so :

data : 'myData=Hello',
// or data : 'firstParam=Hello&secondParam=Mate',

Upvotes: 2

Related Questions