开发者

Assign Javascript variable to PHP with AJAX

I understand...

  • the disparity between PHP being server-side and Javascript being client-side.
  • AJAX can patch this iss开发者_JAVA技巧ue.
  • the XMLHttpRequest object is significant.

However, I still can't work out how to pass the variable between the two languages.

Any assistance would be much appreciated!

EDIT: Thanks for your replies so far, I should clarify that I would like to do this without loading a new page.


You need to send an AJAX request containing the value of the variable in the query string or POST body.

The PHP script at the other end of the URL can read the value from the query string or POST body.


you could use JSON with JS and decode it with php, but as the post above states, it involves ajax.


UPDATE: Tutorial found at link

You should give a more detailed example of what you want to accomplish. But if I understand correctly, you want to use a value from your JavaScript code in your PHP code?

You should try using POST or GET parameters to pass values into PHP. For PHP to be able to do anything, you will have to load a new page.

Lets say you have list.php serving a list of posts. You want to "like" a post. Your JavaScript is on this page. When you click "like", an AJAX POST is sent to like.php with POST parameter id=123.

In like.php, you get the value from the request (using $_POST['id'] or something more appropriate), do your magic (save to db) and echo some result, json_encode(array('success' => true)) for example.

The JavaScript-code that called like.php can then use it's callback to check if the "like" was a success or not and display feedback. The like.php could be any page, you could use list.php if you'd want. I used like.php for clarity.

If this is not at all what you wanted, please provide more information.


If you haven't looked at jQuery framework for javaScript, do it.

If you have a variable called city in JS, you can pass it to the file.php by using

var city = "London";
$.get("file.php", {location:city} );

Which is a HTTP GET request.

In PHP(file.php), you then grab it by using

$city = $_GET['location'];

echo $city; //London
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜