简体   繁体   中英

Pass Query into Function using AJAX (Javascript)

I'm trying to pass PHP Function parameters using Javascript (not JQuery) AJAX.Do I somehow add it to the javascript AJAX function send()? Also i'm POSTing it to my PHP file.

The main thing is how do I use the XMLhttp.send() function to asynchronously call a PHP function while add parameters to the function.

PHP will receive the request from JavaScript in the form of a POST or GET. Use the standard $_POST and $_GET superglobals to access the values.

edit - sorry, misunderstood the question

Yes, use XMLHttpRequest's send() method. Ex:

var xhr = new XMLHttpRequest();
// ...
xhr.send("x=y&foo=bar");

Then, in PHP:

echo( $_POST['foo'] ); // echos "bar"

It's not possible to call a specific PHP function from Javascript. The client doesn't know anything about the server side functions, and and the server side doesn't know anything about the client. jimbojw 's answer explains how to pass parameters into PHP and handle them in PHP. If you want to call a specific PHP function and return the results to the client, then you're going to have to have code to figure out which function to call on the server, or make a separate php file for each function you want to call.

If you want to go the first route, then you'd pass in something like an 'action' parameter, and then do this in your PHP file that contains the functions you want to call:

switch($_POST['action']) {
   case 'foo':
       foo($_POST['bar']);
       break;
   case 'foo2':
       foo2($_POST['bar']);
       break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM