Question

I use this simple javascript code to call a php function from javascript.

var a = new XMLHttpRequest();
        a.open("GET","save.php");
        a.onreadystatechange = function() {
        if( a.readyState == 4) {
            if( a.status == 200) {
                alert("Worked");
            }
        else alert("HTTP error "+a.status+" "+a.statusText);
        }
        }
        a.send();

In this example I have a php function save() contained into save.php file. I have some questions:

1) How can I call a php function that it is located into the same file where there is the javascript function? (I would to call a php method declared into the same file where there is the javascript caller)

2) Is possible to pass also an php array as parameter?

Was it helpful?

Solution 2

You have to use ajax call as described manner--

On javascript side on save.php page-

$.ajax({
    type:"POST",
    data:'demodata',                                                      
        url:"save.php?action=php_function",  // place your php function name here
        dataType: "html",
    success:function(response){
            alert(response);       // It will alert value returned by php function
    },

    failure:function(response){
            alert("there is an error.");
    },

});

On PHP side on save.php page-

<?php

  if(function_exists($_GET['action'])) 
  { 
     $_GET['action'](); 
  }
  else
  {
        echo 'There is some error.';
  }

  function php_function()
  {
     // some code
     echo "result";
  }

 ?>

OTHER TIPS

First: You are not "calling a function". You are making a request to a server. The request is "interpreted" in php, and php has a function defined that is called. Js never calls php directly (one is front side, one is back).

To answer your questions:

  1. You need to make the request to the same page you are displaying, but your js will also be executed.

  2. Yes, but I suggest a post not a get for this (use var_name[] for array, where var_name is the name of the array).

As side notes: Having both php and js in the same file is usually a bad idea. Try to isolate the front-end from the back-end as much as possible (it may be hard at first, but it will save you from huuuge headaches).

The script you are using is fine for simple things, but lacks lots of things (what if destination was moved and you get a redirect state, what if is unreachable, what if you need a callback, etc.). You are also limited at GET, and for some thing you may prefer POST method. I suggest using js lib for your requests (like jQuery ajax, prototype ajax, etc.) that take care of this things. Or you can extend your script of course.

In general, passing an array between PHP and Javascript is better done using a JSON document as interchange format.

You would have to detect the request was made via ajax so that you can run the save() function, or if not then output the page normally, with the JavaScript caller included.

There are a number of ways to detect ajax, one would be to set the X-Requested-With header, which you can check on the PHP side.

save.php

function save(){
    // some PHP code here
}

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
    // request was made via ajax, call the function
    save();
    exit(); // exit so no page content is sent via ajax
}

// output the page content including JavaScript caller

JavaScript:

var a = new XMLHttpRequest();
a.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // set the header
// continue with your XHR code

The best way to send an array would be to JSON encode it before sending via POST, then JSON decode on the PHP side.

JavaScript:

a.open("POST","save.php");
a.send('json=' + encodeURIComponent(JSON.encode(myArray)));

PHP

function save(){
    $myArray = json_decode($_POST['json']);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top