How to call a PHP file from HTML or Javascript

I looked around for a long time, and I can not find anywhere that answers this seemingly basic question. I don't care if the page will reload or display the results immediately; I just want a button on my website to run a PHP file. It. And I found that all websites either tell you how to directly run PHP code in your HTML code, or tell you to use ajax. I will use ajax if necessary, but there was a time before the ajax used by PHP existed, so I think there is an easier way. If I can write the code inside the HTML just fine, why can't I just link to the file for it there or make a simple call to it in Javascript?

If it turns out that ajax is the only way forward, what do I need to know about it in order to call a PHP file that will create a text file when a button is clicked? I make a simple blog site for myself and I have code for the site and javascript that can take the message that I write in textarea and display it right away. I just want to link it to a PHP file that will create a permanent blog entry on the server so that the message is still there when the page reloads.

Thanks for taking the time to read and respond.

+7
javascript jquery html ajax php
source share
4 answers

How to make PHP button call?

I don't care if the page reloads or displays the results right away;

Good!

Note. If you do not want to refresh the page, see "Okay ... but how can I use Ajax?" below.

I just want a button on my website to run a PHP file.

This can be done with a single button:

 <form action=""> <input type="submit" value="my button"/> </form> 

What is it.

To a large extent. Also note that there are times when ajax is really a way to go.

It depends on what you want. In general, you only need ajax if you want to avoid loading the page. However, you said that you do not care.


Why can't I call PHP directly from JavaScript?

If I can write the code inside the HTML just fine, why can't I just link to the file for it there or make a simple call to it in Javascript?

Since the PHP code is not in HTML just fine . This is an illusion created by the fact that most server-side scripting languages ​​work (including PHP, JSP, and ASP). This code exists only on the server, and it is not accessible to the client (browser) without any remote call.

This can be seen if you ask your browser to show the source code of the page. You will not see the PHP code there, because the PHP code is not sent to the client, so it cannot be executed with the client. To do this, you need to make a remote call in order to be able to initiate the client starting PHP code.

If you are not using a form (as shown above), you can make this remote JavaScript call using the little Ajax thing. You might also wonder if you can do what you want to do in PHP, in JavaScript.


How to call another PHP file?

Use the form to make a call. You can force him to direct the user to the member file:

 <form action="myphpfile.php"> <input type="submit" value="click on me!"> </form> 

The user will be on the page myphpfile.php . To make it work for the current page, set the action to an empty line (this is what I did in the example I gave you earlier).

I just want to link it to a PHP file that will create a permanent blog entry on the server so that when the page reloads, the message is still there.

You want to do the operation on the server, you must make your form the fields you need (even if type="hidden" and use POST ):

 <form action="" method="POST"> <input type="text" value="default value, you can edit it" name="myfield"> <input type="submit" value = "post"> </form> 

What do I need to know about this in order to call a PHP file that will create a text file with the click of a button?

see How to write a file in PHP .


How do you get data from POST on the server?

I'm glad you ask ... Since you're a newb begginer, I will give you a small template that you can use:

 <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { //Ok we got a POST, probably from a FORM, read from $_POST. var_dump($_PSOT); //Use this to see what info we got! } else { //You could assume you got a GET var_dump($_GET); //Use this to see what info we got! } ?> <!DOCTYPE html> <html lang="en"> <head> <meta char-set="utf-8"> <title>Page title</title> </head> <body> <form action="" method="POST"> <input type="text" value="default value, you can edit it" name="myfield"> <input type="submit" value = "post"> </form> </body> </html> 

Note: you can remove var_dump , this is just for debugging purposes.


How do I...

I know the next step, you will be asking how:

  • How to transfer variables from a PHP file to another?
  • how to remember user / make login?
  • How to avoid this anonymous message appears when the page reloads?

There is one answer for this: sessions.

I will give a more extensive template for Post-Redirect-Get

 <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { var_dump($_PSOT); //Do stuff... //Write results to session session_start(); $_SESSION['stuff'] = $something; //You can store stuff such as the user ID, so you can remeember him. //redirect: header('Location: ', true, 303); //The redirection will cause the browser to request with GET //The results of the operation are in the session variable //It has empty location because we are redirecting to the same page //Otherwise use `header('Location: anotherpage.php', true, 303);` exit(); } else { //You could assume you got a GET var_dump($_GET); //Use this to see what info we got! //Get stuff from session session_start(); if (array_key_exists('stuff', $_SESSION)) { $something = $_SESSION['stuff']; //we got stuff //later use present the results of the operation to the user. } //clear stuff from session: unset($_SESSION['stuff']); //set headers header('Content-Type: text/html; charset=utf-8'); //This header is telling the browser what are we sending. //And it says we are sending HTML in UTF-8 encoding } ?> <!DOCTYPE html> <html lang="en"> <head> <meta char-set="utf-8"> <title>Page title</title> </head> <body> <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>; <form action="" method="POST"> <input type="text" value="default value, you can edit it" name="myfield"> <input type="submit" value = "post"> </form> </body> </html> 

Please look at php.net to call any function that you do not recognize. Also - if you haven't done it yet - get a good HTML5 tutorial.

Also, use UTF-8 because UTF-8 !


Notes

I make a simple blog site for myself, and I have code for the site and javascript that can take the post that I write in the text box and display it right away.

If you use CMS (Codepress, Joomla, Drupal ... etc.)? This puts some restrictions on how you should do something.

In addition, if you use the framework, you should look at their documentation or ask on your forum / mailing list / discussion page / contact or ask the authors.


Ok ... but how can I use Ajax?

Well ... Ajax is simplified by some JavaScript libraries. As you begin, I recommend jQuery .

So, send something to the server via Ajax using jQuery, I will use $. post instead of $. ajax for this example.

 <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { var_dump($_PSOT); header('Location: ', true, 303); exit(); } else { var_dump($_GET); header('Content-Type: text/html; charset=utf-8'); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta char-set="utf-8"> <title>Page title</title> <script> function ajaxmagic() { $.post( //call the server "test.php", //At this url { field: "value", name: "John" } //And send this data to it ).done( //And when it done function(data) { $('#fromAjax').html(data); //Update here with the response } ); } </script> </head> <body> <input type="button" value = "use ajax", onclick="ajaxmagic()"> <span id="fromAjax"></span> </body> </html> 

The above code will send a POST request to the test.php page.

Note. You can mix sessions with ajax and more if you want.


How do I...

  • How to connect to the database?
  • How to prevent SQL injection?
  • Why shouldn't I use the Mysql_ * functions?

... for these or any other questions, please ask another question. This is too much for this.

+41
source share

I just want a button on my website to launch a PHP file

 <form action="my.php" method="post"> <input type="submit"> </form> 

In general, however, if you are not sending new data to the server that you want to save, you simply use the link.

 <a href="my.php">run php</a> 

(Although you should use link text that describes what happens from the perspective of the user, not the servers)


I make a simple blog site for myself, and I have code for the site and javascript that can take the message that I write in the text box and display it right away. I just want to link it to a PHP file that will create a permanent blog entry on the server so that the message is still there when the page reloads.

This is a trick.

Firstly, you need to use the form and POST (since you are sending data for saving).

Then you need to save the data somewhere. This is usually done using a database. Read the PDO library for PHP. This is the standard way to interact with databases.

Then you need to pull the data again. The easiest way here is to use a query string to pass the primary key for the database row with the record you want to display.

 <a href="showBlogEntry.php?entry_id=123">...</a> 

Make sure you also read SQL Injection and XSS.

0
source share

As you said in your question, you have several options. A very simple approach is to use a tag that refers to your PHP file in the method attribute. However, as esoterically as possible, AJAX is a more complete approach. Given that calling AJAX (in combination with jQuery) might be as simple as:

 $.post("yourfile.php", {data : "This can be as long as you want"}); 

And you will get a more flexible solution, for example, starting a function after completing a server request. Hope this helps.

0
source share

You just need to send the form data to the php function of the insert file, see below :)

 class DbConnect { // Database login vars private $dbHostname = ''; private $dbDatabase = ''; private $dbUsername = ''; private $dbPassword = ''; public $db = null; public function connect() { try { $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "It seems there was an error. Please refresh your browser and try again. ".$e->getMessage(); } } public function store($email) { $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?'); $stm->bindValue(1, $email); return $stm->execute(); } } 
0
source share

All Articles