Skip to content Skip to sidebar Skip to footer

Execute Php From Javascript

I'm having some trouble getting some php code working in my app. The setup is rather easy: 1 button, 1 function and 1 php file. script.js $(document).ready(function () { $('#b

Solution 1:

$.get('script/SQL/testConnection.php', function(data) {
  alert(data)
});

You need to process Ajax result


Solution 2:

You need to do something with the response that your php script is echoing out.

$.get("script/SQL/testConnection.php", function(data){
    alert(data);
});

If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.


Solution 3:

Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.

I see you are using jQuery - it has pretty nice API for such calls. It is documented: here

In your case the js should be rather like:

$(document).ready(function ()
{
   $("#btnTestConnectie").click($.ajax({
       url: '/testConnection.php',
       success: function(data) {
          //do something
       }
   }));
});

[EDIT] Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.

In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.


Solution 4:

You may have a look on the load() of jQuery http://api.jquery.com/load/


Solution 5:

You should place all of your functions in the document ready handler:

$(document).ready(function(){
    function testConnectie() {
        $.get("script/SQL/testConnection.php");
    }

    $("#btnTestConnectie").click(function(e) {
        e.preventDefault();
        testConnectie();
    });
});

You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.

One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.


Post a Comment for "Execute Php From Javascript"