Getting Javascript to talk to PHP
On my page I have a table, and this table has a list of items plus an edit button.
When the edit button is clicked, I want to fill the form with the information specific to that entry in the table. All the information is stored in a mySQL database and can be accessed by PHP.
I need my javascript on the edit button to get the table row identifier to PHP, which will query the database, returning the correct values and then the javascript needs to receive these entries and fill the form.
How do I do this?
I can cause a PHP mock "event" by filling a variable and then chec开发者_如何学编程king:
if($variable){
[do query]
}
But how do I fill that variable from Javascript bearing in mind that the HTML, JS and PHP are nested in the same page?
The HTML, JS and PHP are not really "in the same page", and it helps if you don't think about it that way.
You have a PHP program that outputs an HTML document to the browser. That document has embedded JS in it.
In order to send a message from the JS to the PHP you need to make an HTTP request. This could be done by generating a form and submitting it, using XMLHttpRequest, or a few other methods.
XMLHttpRequest is the most common and allows you to do this without leaving the page. This is known as Ajax. You can find some suggestions on how to get started with this technique in this question.
You should probably separate out the database accessing PHP into a reusable chunk that gets shared between the URL used for generating the page in the first place, and a URL used to generate a snippit of data to update it with late (formatting this data using JSON is probably a good idea).
How do I do this?
The normal way to go about this, would be to have a hyperlink in your index-page that refers to a page which shows an edit-page. So you would have url's like: index.php
and edit.php?id=42
. Is there any reason why you don't want to do this?
It looks like some good ole ajax will do you good. A jQuery implementation will go something like this
$('.button-class').click(function(){
$.ajax({
url: 'your-php-page.php?id=xxx', //Call your php page here
success: function(data) {
$('.table-row').html(data); // Update your page with the data returned
}
});
});
PHP runs when the page loads, and can't be access again until the page is reloaded. Your solution would be to put the script that will update, or run what ever query you need, and access it with Jquery Ajax
You do that by making an asynchronous call to the server and waiting for the server response. This is known as AJAX (asynchronous Javascript and XML).
Here is a basic tutorial: http://www.w3schools.com/ajax/default.asp
There are also many JS library (es. JQuery et Co.) that may make your life easier if you want to use AJAX
Use AJAX to pull in the data, check out Jeditable.
精彩评论