one php file for all jquery post requests? - php

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)

Related

Wrong request url with ajax?

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.

What is the best method to pass ID with Ajax call?

I'm New in AJAX.
When passing ID to update product. Any explanation for this. Thank you in advance.
This
$.ajax({
type: 'post',
url: 'my_controller/update_product_exe/' + id, //This line
dataType: 'json'
});
to this...
$.ajax({
type:'post',
url: 'my_controller/update_product_exe',
dataType: 'json',
data: {id: id} // this line
});
The difference is the url itself. Appending id to the first url will change it and therefore send the request to that specific url. But, it's not sending any data during request. Example:
// let's say id = "1234"
$.ajax({
type: 'post',
url: 'my_controller/update_product_exe/' + id, // This will be 'my_controller/update_product_exe/1234'
dataType: 'json'
});
And for the second one:
$.ajax({
type:'post',
url: 'my_controller/update_product_exe',
dataType: 'json',
data: {id: id} // This will be {id: "1234"}
});
On the second one, you are passing data; on the first one, you are just modifying your url by appending some string to it.
If you just want to know about the difference in both ajax requests than:
In first request, you are not passing the data in ajax request but sending an ID in URL, in CI controller, you will get this id by using URL Segments.
In Second request, you are sending the data in ajax request, so you can get the data in controller by using $_POST
Now, which one is the better, both of them having difference, when you need to pass some input values using ajax than you can choose second one. You can send multiple data in this request.
You can also use second request for achieving the first request target, in this case you can just pass the ID in ajax data. You can send multiple data but you must need to take of segement URLs.
Conceptually you are using a GET in the the first example and a POST for the second. HTTP verbs have a meaning and POST is meant to send information to a server. Even if you can get the id by using a GET this does not make it semantically correct. For the moment you only have an id which is limited in size and is only one parameter, but even in a small application one usually sends to a server several parameters and maybe some kb of data. GET parameters are limited in size and POST is better suited for this.
For all this reasons the second version that is using POST is the correct one.
Here are some extra resources on the differences between GET and POST.
http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post
http://www.diffen.com/difference/GET-vs-POST-HTTP-Requests
What is the difference between POST and GET?
When should I use GET or POST method? What's the difference between them?

Equivalent of ajax petition in PHP

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.

Refer jQuery .ajax Post to function

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'];
}

Calling methods or functions with Jquery

So I can call a php page using jquery
$.ajax({ type: "GET",
url: "refresh_news_image.php",
data: "name=" + name,
success: function(html) {
alert(html)
$('div.imageHolder').html(html);
}
});
However this getting a bit messy, I have a few .php files that only really preform very simple tasks. If I want to call a method
$images->refresh_image();
is this possible. Failing that I could just create a big file with lots of functions in it?
Thanks,
Ross
Well, depends on what the intention is, of course, but if you really only want to run the refresh_image function, you don't need to pass any data, you don't have to handle success etc, then this isn't messy:
$.ajax({
url: "refresh_news_image.php",
});
You could also create a general function, such as:
function php_func(name){
$.ajax({
data: { name: name }
url: "background_functions.php",
});
}
And then background_functions.php:
switch($_GET['name']){
case 'refresh_image':
$images->refresh_image();
break;
case 'something else':
something_else();
break;
}
In javascript, whenever you need it (perhaps on an onclick) then you'd simply invoke:
php_func('refresh_images');
Be careful not to use the GET-parameter to run whatever function is passed, as that's obviously a huge security risk. :-)
You cannot call php functions directly from jQuery because jQuery knows nothing about php. You could create a file that based on a given request parameter calls the respective function and returns the result.

Categories