2017-06-19 41 views
-2

模態的按鈕,一個jQuery值包含的帖子ID:存放在一個PHP變量

<button onclick='getValue("<?=$id?>");' data-toggle="modal" name="submit" data-target="#squarespaceModal">Purchase Now</button>

當我使用alert它表明這個ID正常,但我需要將此ID存儲在PHP可變

   `function getValue(id){ 
         alert(id); 
        // i am trying this but not done 
       // <?php $xyz = ?> id ; 

       }` 

我也嘗試使用$.post但在模式中的數據是不是來 像

$.post("<?=$current_url;?>", function(id) { // $("#div1").html(id); //alert(id); });

我怎麼能存儲在一個PHP變量一個jQuery價值?我見過的大多數例子都是相反的,例如var x =<?php echo $y;?>,但我需要相反的方式。

+0

你從'警報(ID)得到什麼結果;'? – josephting

+0

我的帖子id喜歡1/2 –

+0

我只是想要在任何PHP變量這個id –

回答

0
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<Script> 
getValue(5); 
function getValue(id){ 
alert(id); 
// i am trying this but not done 
$.ajax({ 
type: "POST", 
data: {id:id}, 
url: "http://localhost/key/index2.php/", 
success: function(data){ 
alert(data); 

} 
}); 

} 
</script> 

in index2.php 

<?php 
session_start(); 
$_SESSION['id']=$_POST['id']; 
echo $_SESSION['id']; 
?> 

在這裏,我做了Ajax調用PHP文件,並在該文件中,我已經儲存的已發送的會話ID,所以現在你不得不在PHP變量,該ID在會話

+0

謝謝索尼婭,ajax警報即將到來,但php後數據不會來臨會議數據不會來 –

+0

<?php session_start();如果(isset($ _ SESSION ['id'])){ \t echo $ _SESSION ['id']; }?>將這段代碼寫在你想打印session存儲id的php文件中,把這段代碼寫在文件的頂部 –

0

你不能做到這一點單獨使用jQuery;你需要結合使用Ajax和PHP文件。例如: HTML

<button onclick='getValue("<?=$id?>");' data-toggle="modal" name="submit" data-target="#squarespaceModal">Purchase Now</button> 

jQuery的

function getValue(id) { 
     // Send Ajax request to ajax_file.php, with id as POST data 
     $.post("ajax_file.php", {'id': id}, function(result){ alert(result)}); 
} 

ajax_file.php

<?php 
    session_start(); 
    if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
     $_SESSION['id'] = $_POST['id']; 
     echo $_SESSION['id']; 
    } 
?>