Refer jQuery .ajax Post to function - php

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

Related

one php file for all jquery post requests?

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)

obtaining PHP variable in jQuery AJAX

In my php file 'login_success.php', I have a the variable $_COOKIE["user"]
Would it be possible to return that variable within a jQuery Ajax statment such as this one. ive made a guess with Var UserName =:
function StartAjax(NameID){
$.ajax({
type: "POST",
url: "login_success.php",
cache: false,
data: "name=Peter&location=Sheffield",
success: function(html, status){
$("#"+NameID).append(html);
//$('#status').append(status);
var userName =
}
});
login_success.php:
echo $_COOKIE['user'];
Ajax asks for the page, returns the output/content (what is echoed). Please note: Javascript is client side. PHP is server side. So you can't directly access PHP variables, but as done above, PHP can "give" the client the info it needs. If you're sending a lot of data, you can json_encode it for the ajax request. (you can learn about JSON on your own)
Also note, Javascript can access cookies, but I'm assuming this is just a sample question.

Posting Ajax data to Controller function?

In my PHP/jQuery application, I have a javascript file, in which I can call an external PHP file (post_data.php) like this:
$.ajax({
type: "POST",
data: "some data",
url: "post_data.php",
Now, instead of calling php file, i would like to call a CodeIgniter contoller function Data/post_data, so how can I call that function instead of post_data.php?
The javascript file in which i would like to call is located:
root/js/test.js
while the function is located here:
root/application/controllers/data/post_data
The ajax need to have a full url:
$.ajax({
type: "POST",
data: "some data",
url: "http://www.yourdomain.com/urpath/post_data"});
The reason is the Javascript file that call the Ajax is not aware of the server location of the .php file. So, by using the absolute path you make sure that your call will be done. Also, to test it before using the Javascript file, copy and paste the url into your browser. If no 404 error is displayed, than you have your good path.
To add to Doaks response, you can also do it like this
$.ajax({
url: "<?php echo site_url('data/post_data'); ?>",
type: "POST",
data: data,
You can use $.post() JQuery function it's more simple and optimized for POST request. Also for routing, you can set just controller and method. It's enought.
$.post("admin/newphone", {
phone: $('input[name="phone"]').val()
},
And link to JQuery docs http://docs.jquery.com/Post

How can I implement a jquery ajax form which requests information from a web api via a php request?

I'm trying to implement a simple api request to the SEOmoz linkscape api. It works if I only use the php file but I want to do an ajax request using jquery to make it faster and more user friendly. Here is the javascript code I'm trying to use:
$(document).ready(function(){
$('#submit').click(function() {
var url=$('#url').val();
$.ajax({
type: "POST",
url: "api_sample.php",
data: url,
cache: false,
success: function(html){
$("#results").append(html);
}
});
});
});
And here is the part of the php file where it takes the value:
$objectURL = $_POST['url'];
I've been working on it all day and can't seem to find the answer... I know the php code works as it returns a valid json object and displays correctly when I do it that way. I just can't get the ajax to show anything at all!!
...data: 'url='+encodeURIComponent(url),

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