How can I pass data between scripts in PHP without $_SESSION? I need to send the information specifying a method, the thing is that this is a script that will run only on the server side, without interaction with user. Right now, I have a view in which the user do the operations, for that I'm using the ajax provided by jQuery, I have:
$.ajax({
url: "action.php",
cache: false,
dataType: "html",
method: "POST",
data: {
method: "sendMessage",
target: target,
message: message
}});
that works pretty well, but I need to remove the view and the interaction with the user, and make that works without JavaScript. So I want to know, which is the equivalent in PHP to call the script action.php and send it all the data whit the specified method?
Write your function as a function.
include() the file containing your function.
Just call the function passing whatever data you like as an argument.
If you also need to present it as a front end view, then you would write a separate wrapper script and put that on a publicly accessible URL.
Related
So, I'm trying to send a post request to a php script of mine.
On the web I'm in a page like: https://yyy.yyy/test-page
My ajax url is set as such:
url: "https://yyy.yyy/test.php"
But then it returns a 404 error with the following url:
https://yyy.yyy/test-page/test.php
And it definitely won't find in the php file in that path, since it is located at root. Moving the php to another folder is not an option.
This website is located in a WordPress server.
Here's the js code:
$.ajax({
url: "https://yyy.yyy/test.php",
method: "POST",
type: "Json",
data: data,
success: function (res) {...}
});
If you're wanting to make use of Ajax and are running WordPress, you should look into writing a plugin and making use of the hooks and functions available to make this easier as WordPress will do a lot of heavy lifting.
I see you mentioned it can't be moved, but if it's at all possible to at least try and replicate the PHP code into a plugin (or a theme although that's less ideal and might not work properly) then it'll make things easier.
Take a look at using Ajax in plugins.
The JavaScript (jQuery) bit:
$.ajax({
data: {
action: 'my_ajax_request'
},
type: 'post',
url: SOWP_AJAX.admin_ajax,
success: function(response) {
console.warn( response );
}
});
The PHP bit (Part 1):
This ensures that the URL that you post your Ajax function to is mapped to an actual URL. In this case, the WordPress Ajax handler at admin-ajax.php.
wp_localize_script(
'sowp_js', // this is the script name that should be used to enqueue the JavaScript code above
'SOWP_AJAX',
array(
'admin_ajax' => admin_url('admin-ajax.php')
)
);
The PHP bit (Part 2):
Put this inside a plugin or theme file that is activated. The hook my_ajax_request must match the request action in the Ajax request and the function name so it's called correctly.
add_action( 'wp_ajax_my_ajax_request', 'my_ajax_request' ); // the hook that is triggered when the request is made
function my_ajax_request() {
echo 'my ajax request works'; // print something out
wp_die(); // stop script execution
}
Once you've got all of the above in place, when the Ajax request is working and runs, you should see my ajax request works printed in your browsers console. If it returns 0 then it means the request failed somewhere. If it does fail, it usually means the action hook has been registered and called so something might be spelt wrong or missing.
I have a lot of jquery ajax methods and for each of them a small php file.
Is it possible to create one single php file and than on jquery side refer to a specific function in the php file?
Like this:
$.ajax({
type: "POST",
url: "functions.php", function01(),
....
next function:
$.ajax({
type: "POST",
url: "functions.php", function02(),
....
And if it is possible - is it maybe a wrong practice for overall performance?
You are looking for routing the requests to the right recipients.
This is a common practice among many MVC frameworks and it does not have notable performance impacts in contrast to maintainability of the code (– if done right).
A very simplified example:
<?php
// request.php
$allowedRequests = [
// these files will correctly handle the specific requests when included
'db' => 'db.php',
'file' => 'file.php'
];
$request = $_GET['request'];
if (isset($allowedRequests[$request)) {
include($allowedRequests[$request]);
}
Then, just pass another GET parameter on the client side:
$.ajax({
type: "POST",
url: "functions.php?request=db"
Depending on the request parameter, the correct file will be chosen and included.
Note: As I already said, this is a very simplified example. For instance, CakePHP supports storing grouped functionality (=controllers) in different files. Anyway, the gist is to redirect the whole request parameters to the correct part of your application.
You can, but not quite like that.
I suggest sending a parameter in the request that tells it what function to run.
$.ajax({
type: "POST",
url: "functions.php",
data: {
method: 'function01'
# and then whatever other data you send
}
});
Then in your PHP, just use the method param to call the right function.
<?php
$funcName = $_POST['method'];
call_user_func($funcName);
function function01(){
}
function function02(){
}
Note: You should probably check $_POST['method'] against a white-list so that your page is secure. Wouldn't want someone to send method=eval.
You could pass a $_POST var along with the rest of the AJAX data and use it to determine the function to run like so:
JS
$.ajax({
type: 'POST',
url: 'function.php',
data: {
action: 'function01',
... // Other Data
}
...
});
PHP
if ($_POST['action'] == 'function01'){
...
}
I hope this helps!
Your right, in fact you should try not to do it in another way. Think about 1 dispatcher file which calls the correct function. You do yourself a favor as you are now able to only define 1 error handler, 1 output handler etcetc.
As for your question: add 'data' to your request so you can identify the type of request. Depending on the type of request you can call the correct method( for example, with a switch to evaluate a $_POST value)
I have one quick question for experienced ones.
I have a page that does a jquery ajax post to another php page with javascript in it.
My question is, will the javascript get executed as well?
Another question.
lets say, that instead of javascript, I have another jquery ajax post request to a third php.
Will any of the 2 work?
Unless the javascript in that "another php page" is actually returned to the client and somehow inserted into the DOM, the JS cannot and will not execute. The resulting output of an AJAX operation is returned as a string to the code that performed the ajax call. It's not interpreted/parsed except in a few very specific cases.
If you're using jQuery's AJAX function to send POST variables to a PHP file, only the backend code will be executed. However, upon success of the AJAX call, you can execute some more JS code as follows
//Define whatever variables you want to pass along to the PHP file
var variable = "";
$.ajax({
url: "file.php",
type: "POST",
data: "variable="+ variable,
success: function(data)
{
//Upon success of the call, you can execute JS code here
}
});
Additional info here
Is it possible to refer an AJAX POST to a specific function within a PHP file?
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: "some data...",
success: function(){
alert('Success!');
}
});
Or is there a way to have functions.php receive data and know what to do with it? If not, are there any other suggestions for getting data over to mySQL (using PHP/jQuery)? Thanks!
The data sent to the php file using POST can be accessed in php using:
$datasent = $_POST['name'];
Given that you sent data as:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
Not directly. You'd need to post certain data, and have PHP check the POST variables to choose the correct function.
Perhaps have a look at some tutorials (unfotunately the jQuery links for php tutorials are broken).
Is it possible to refer an AJAX POST to a specific function within a PHP file?
No. jQuery doesn't know what PHP is, even less what a PHP function is. jQuery talks to server side urls. Whether those urls are static html files, PHP scripts, Java servlets, Python I don't know what, CGI scripts, is not really important.
So you could use the data setting to pass parameters to this server side url which based on the values of those parameters could invoke one or another function.
If you want to call a specific function, change ur jquery:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {function:"doSomething",name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
In your php add:
call_user_func($_POST['function']); // This will call what ever function name is passed as parameter
function doSomething(){
echo $_POST['name'];
}
I just started learning PHP and was wondering if there is a way to trigger a portion (a function really) of a php script when a user clicks on a link/button without redirecting the user to a new php script page?.
Basically, is there a way to invoke php functions through client side user actions like you have in javascript?.
PHP is not client side. It simply generates a page and sends it to the user's browser.
You would need to incorporate javascript into the page you are returning for client side actions. The most common approach is having javascript make AJAX calls to php scripts on the backend.
Here's how you can do it with JQuery using $.ajax() [Docs]
$('#my-button').click(function(){
$.ajax({
url: 'my_php_page.php?route=my_preferred_function',
data: 'foo=bar',
type: 'post',
dataType: 'json',
success: function(data){
alert('Response = ' + data);
}
});
});
Most MVC frameworks - one example being CodeIgniter allow you to execute specific functions in the controller via the URL: http://domain.com/mycontroller/myfunc. If your function takes two arguments, for example:
public function foobar($foo,$bar){
// do something
}
You can access it via http://domain.com/mycontroller/foobar/abc/123 making your ajax calls super easy.