简体   繁体   中英

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;
?>

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.

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

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'] .

替换这个data: desc, ajax中的字段到data:{data: desc}, ,这就是你在php代码中没有得到数据的原因

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM