Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call php function from JavaScript

Is there a way I can run a php function through a JS function?

something like this:

<script type="text/javascript"> function test(){ document.getElementById("php_code").innerHTML="<?php  query("hello");       ?>";     } </script>  <a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"      onclick="test(); return false;"> test </a> <span id="php_code"> </span> 

I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.

like image 531
Jason Russell Avatar asked Aug 23 '11 17:08

Jason Russell


People also ask

Can Javascript call PHP function?

The reason you can't simply call a PHP function from JavaScript has to do with the order in which these languages are run. PHP is a server-side language, and JavaScript is primarily a client-side language.

How do you run a PHP function when a button is clicked?

Create a button with the name Click using the button tag. Specify the onclick() function as an attribute with the clickMe() function as its value. Write the function clickMe() inside the script tag. Create a variable result and call the php_func() in it inside the PHP tags.

Can I use PHP in jQuery?

We can help you with jQuery. You need to configure your PHP server to allow you to use PHP in your JS files. It is not configured for this by default.

How do I pass variables and data from Javascript to PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];


1 Answers

This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

Plain Javascript

In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

The javascript

// handles the click event for link 1, sends the query function getOutput() {   getRequest(       'myAjax.php', // URL for the PHP file        drawOutput,  // handle successful request        drawError    // handle error   );   return false; }   // handles drawing an error message function drawError() {     var container = document.getElementById('output');     container.innerHTML = 'Bummer: there was an error!'; } // handles the response, adds the html function drawOutput(responseText) {     var container = document.getElementById('output');     container.innerHTML = responseText; } // helper function for cross-browser request object function getRequest(url, success, error) {     var req = false;     try{         // most browsers         req = new XMLHttpRequest();     } catch (e){         // IE         try{             req = new ActiveXObject("Msxml2.XMLHTTP");         } catch(e) {             // try an older version             try{                 req = new ActiveXObject("Microsoft.XMLHTTP");             } catch(e) {                 return false;             }         }     }     if (!req) return false;     if (typeof success != 'function') success = function () {};     if (typeof error!= 'function') error = function () {};     req.onreadystatechange = function(){         if(req.readyState == 4) {             return req.status === 200 ?                  success(req.responseText) : error(req.status);         }     }     req.open("GET", url, true);     req.send(null);     return req; } 

The HTML

<a href="#" onclick="return getOutput();"> test </a> <div id="output">waiting for action</div> 

The PHP

// file myAjax.php <?php   echo 'hello world!'; ?> 

Try it out: http://jsfiddle.net/GRMule/m8CTk/


With a javascript library (jQuery et al)

Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

// handles the click event, sends the query function getOutput() {    $.ajax({       url:'myAjax.php',       complete: function (response) {           $('#output').html(response.responseText);       },       error: function () {           $('#output').html('Bummer: there was an error!');       }   });   return false; } 

Try it out: http://jsfiddle.net/GRMule/WQXXT/

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

If this is all you need to do, write the plain javascript once and you're done.

Documentation

  • AJAX on MDN - https://developer.mozilla.org/en/ajax
  • XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
  • XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
  • jQuery - http://jquery.com/download/
  • jQuery.ajax - http://api.jquery.com/jQuery.ajax/
like image 94
Chris Baker Avatar answered Sep 28 '22 01:09

Chris Baker