如何从javascript发送的PHP中接收数据[重复]

This question already has an answer here:

I am sending some data from my pain page to app.php using javascript

$(document).on('click', '.app' , function(){
        var data=$(this).attr("id");
        window.location="application/app.php?data="+data;   //data send in this statement
    });

my php code is this :

<?php
if($_GET['data'])
{
    echo $app_id=$_GET["data"]; receiving data 

}
?>

It works sometime but now it is giving Notice in an alert box: Undefined index data in app.php. But it is showing the echo.


I want to know how I can receive the data I need using $_POST or $_GET. like we receive by making an Ajax call. But I haven't specified something like this in Javascript. is there any way to this?

I want to clarify that the data exists and it is non empty because echo is successfully printing that on the page

</div>

Try this:

<?php
if(!empty($_GET['data']))
{
    $app_id = $_GET['data']; // receiving data 
}
?>

Please be aware that passing data without validation is not secure. Reccomended reading: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project

use isset() to first check if the key exists. data won't exist in $_GET when it's not passed via a parameter in the url

you probably want some logic that looks like this:

if (isset($_GET['data'])) {
    if (!empty($_GET['data'])) {
        $appId = $_GET['data'];
    }
    else {
        // data exists, but it's empty
    }
}
else {
    // data does not exist
}

and maybe you even want to check if it's a valid id, like being numeric or something