开发者

Use Javascript variable in PHP

I have seen some answers to this question in previous posts, but no one has given a real working example, just psuedo code. Has anyone ever done this before?

Basically, what i have is a variable in javascript (jquery), and i want to use this variable to drive a query (for an overlay window) i am going to run in php.

From what i have read you can do this using an ajax call to the same page so it doesnt refresh itself, but i must be missing something because i can't get it working...

Any examples out there?

Thanks.

UPDATE 6/21/2010: Ok, i tried to work through but still having some problems...here is what i have. The page I am working on in edit_1.php. Based on Firebug console, the page (edit_1.php) is receiving the correct 'editadid'.

When i try to echo it out though, i get an 'Undefined variable' error though...anything y'all can see i missed here?

Here is the javascript:

var jsVariable1 = $(this).parent().attr('id');
var dataString = 'editadid=' + jsVariable1;
$.ajax({ 
    url: 'edit_1.php', 
    type: 'get', 
    data: dataString, 
    beforeSend: function() {

    },
    success: function (response) { 

    } 
});

Here is my php: if(isset($_GET['editadid'])) { $editadid = (int)$_GET开发者_运维知识库['editadid'];

}

echo $editadid;


It's hard to help without seeing the code you're currently using.

In jQuery:

var jsVariable1 = "Fish";
var jsVariable2 = "Boat";

jQuery.ajax({
    url: '/yourFile.php',
    type: 'get',
    data: {
       var1: jsVariable1,
       var2: jsVariable2
    },
    success: function (response) {
       $('#foo').html(response);
    }
});

Then your PHP:

<?php

$jsVariable1 = $_GET['var1'];
$jsVariable2 = $_GET['var2'];

// do whatever you need to do;

?>

<h1><?php echo $jsVariable1; ?></h1>
<p><?php echo $jsVariable2; ?></p>

It's fairly generic... but it'll do stuff.

An important thing to note, and a very common mistake, is that any additions you make to the DOM as a result of an AJAX request (i.e in this example I've added a h1 and a p tag to the DOM), will not have any event handlers bound to them that you bound in your $(document).ready(...);, unless you use jQuery's live and delegate methods.


I would say instead of looking for an example you must understand how ajax works. How can you hit a URL via ajax and pass query parameters along with them (these can be the javascript variables you are looking for) How server side response is captured back in javascript and used into manipulate existing page dom. Or Much better you can post what you have tried and somebody can correct it for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜