MK3007
MK3007

Reputation: 107

How to post value from one php page to another using ajax

I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.

Here is my code:

$("#requirementtable tbody tr").on("click", function(){
                        desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
        type:"POST",
        url:"get_diagnosis.php",
        data: desc,
        success: function (data, textStatus, jqXHR)
        {
            alert(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {      
            alert("some error occured->" + jqXHR.responseJSON);
        }
    })
  })

this is my php code:

<?php 
    $data = $_POST['data'];
    echo $data;
?>

Upvotes: 2

Views: 1563

Answers (4)

uneeb meer
uneeb meer

Reputation: 973

here is a simple example that contains your code and solution

//Data Object        
var obj={
           name:"uneeb",
           city:"gujranwala",
           state: "punjab"
        };  
//Data Object   

//Ajax Request to Server
     $.ajax({
          type: 'post',
          url: 'someFile.php',
          data:object,
          success: function (data) {
                  //do something here
              }
          });
//Ajax Request to Server

//PHP

echo $_POST['name']; //prints uneeb
echo $_POST['city']; //prints gujranwala
echo $_POST['state']; //prints punjab

//PHP

Upvotes: 3

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Replace the followings:

desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
//        remove ^^^^^^^^^^ since you're currently in tr click
desc =  $(this).find("td:nth-child(4)").text().trim();

And replace to:

data: desc,

With:

data: {data:desc}, //to pass data as object as you don't have serialized data

And inside your php code, you can get data using $_POST['data'].

Upvotes: 2

Rohan Kumar
Rohan Kumar

Reputation: 40639

Check the desc variable has some value in it and you have to post data like,

data: {data:desc},

AJAX Code,

$.ajax({
    type:"POST",
    url:"get_diagnosis.php",
    data: {data:desc},
    success: function (data, textStatus, jqXHR) {
        alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {      
        alert("some error occured->" + jqXHR.responseJSON);
    }
});

And in PHP use isset() to prevent undefined errors like,

<?php 
    $data = isset($_POST['data']) ? $_POST['data'] : 'Not defined';
    echo $data;
?>

If you want JSON response format then use dataType:'json' in $.ajax, and use json_encode() in PHP to respond it.

Upvotes: 3

RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

replace this data: desc, field in your ajax to data:{data: desc},, this is the cause you are not getting data in your php code

Upvotes: 1

Related Questions