duanshan1856 2013-11-19 13:53
浏览 59
已采纳

在jQuery函数中将结果返回给AJAX中的PHP变量

So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.

The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......

Main PHP Page:

$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
    var selr= null;
    if(rowid != null){ 
        selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
        $.ajax({ // I believe I need to use AJAX so here is my attempt
            type: "POST",
            url: "getId.php", //This is another PHP page for the reuslt. See below
            dataType: "json",
            data: {selr:selr},      
            success: function(data) { 
                alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.

            }
        });
    }
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call

getId.php

<?php
$rId = $_POST["selr"];
echo $rId;
?>

Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?

Thank you, I love you all.

  • 写回答

1条回答 默认 最新

  • douyi1966 2013-11-19 13:55
    关注

    By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.

    It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.

    Example of how you can send that data to another PHP page

    //Your existing jQuery
    success: function(data) { 
     // alert (data); 
     var result=data;
     $.ajax({
     type: "POST",
     url: "anotherpage.php",
     data: { data: result }
    });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?