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.
Related
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)
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'];
}
EDIT : Found the solution to my problem below. See it here -> IE must close for event with jQuery to work
I've been asking around, trying to figure this one out. If there are any other way to do a mySql query in PHP by an event .. other than $.get.
I've previously posted this one other problem just in case somebody could help out ->
$.get not working in IE
Now I'm trying to find a way around the problem I previously posted cause if $.get is not going to happen in IE for me then there has to be another way with this. Maybe not with jQuery
Perhaps you could try the longhand syntax (as $.get is a shorthand alias of $.ajax)
function getbillinfo(tbl) {
$.ajax({
type: "POST",
url: "getbillno.php",
data: "tbl=" + tbl,
success: function(bill){
$("#billno").val(bill); });
}
});
}
See http://api.jquery.com/jQuery.ajax/
Edit: with regard to your problems with IE, there could be a couple of reasons
Possibility One
IE caches the results of Ajax calls to the same resource even if you
tell it not to in your HTTP headers. So if you make a request to
getbillinof.php?tbl=table over and over again, IE will make the
request once and then stop making it in the future and simply return
the result of the first request. To circumvent this you can call getbillinof.php?tbl=table&random_string_here
It may also be worth setting cache: false in the ajax() options and having a look into the isModified option.
Possibility Two
A Race Condition is causing the IE render action to run before
any data was returned. This however is unlikely as the success()
function is only supposed to run once the data has been received. A
race condition becomes far more likely if you're doing something like
function getbillinfo(tbl) {
$.ajax({
type: "POST",
url: "getbillno.php",
data: "tbl=" + tbl,
success: function(bill){
var mydata = bill;
}
});
$("#billno").val(mydata);
}
I am using a javascript function to generate a random string:
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
/*$.ajax({
type: "GET",
url: "uuid.php",
cache: false,
success: function(html){
return html;
}
});*/
return (S4()+S4()+S4()+S4());
}
And I want to make it utilize a php uuid library that I've found, the problem is I need it to run in javascript. I use the guid() function a lot and I've been trying to think of an elegant way of grabbing the uuid, that I request using the ajax object (commented out above). The uuid page that just prints random uuids each time is sitting locally next to this page. I would not like to make the request synchronous because, like I said, I use it quite a bit and would prefer to not have everything halt every time this thing makes a request. Or perhaps there's a method I could use of jQuery that be as fast and not hinder performance?
I'm not adverse to changing things up a bit, like would the best practice here to acquire a uuid on load? But the number of UUIDs I generate is completely dynamic, and dependent upon the user.
Thank you!
Check the uniqid() function from phpjs.org.
How about adding a callback argument to the guid() function, wherein you can assign a value to something:
function guid(callback) {
$.ajax({
type: "GET",
url: "uuid.php",
cache: false,
success: function(html){
callback(html);
}
});
}
var value;
guid(function (result) {
value = result;
});
I have seen some answers to this question in previous posts, but no one has given a real working example, just psuedo code. Has anyone ever done this before?
Basically, what i have is a variable in javascript (jquery), and i want to use this variable to drive a query (for an overlay window) i am going to run in php.
From what i have read you can do this using an ajax call to the same page so it doesnt refresh itself, but i must be missing something because i can't get it working...
Any examples out there?
Thanks.
UPDATE 6/21/2010:
Ok, i tried to work through but still having some problems...here is what i have. The page I am working on in edit_1.php. Based on Firebug console, the page (edit_1.php) is receiving the correct 'editadid'.
When i try to echo it out though, i get an 'Undefined variable' error though...anything y'all can see i missed here?
Here is the javascript:
var jsVariable1 = $(this).parent().attr('id');
var dataString = 'editadid=' + jsVariable1;
$.ajax({
url: 'edit_1.php',
type: 'get',
data: dataString,
beforeSend: function() {
},
success: function (response) {
}
});
Here is my php:
if(isset($_GET['editadid']))
{
$editadid = (int)$_GET['editadid'];
}
echo $editadid;
It's hard to help without seeing the code you're currently using.
In jQuery:
var jsVariable1 = "Fish";
var jsVariable2 = "Boat";
jQuery.ajax({
url: '/yourFile.php',
type: 'get',
data: {
var1: jsVariable1,
var2: jsVariable2
},
success: function (response) {
$('#foo').html(response);
}
});
Then your PHP:
<?php
$jsVariable1 = $_GET['var1'];
$jsVariable2 = $_GET['var2'];
// do whatever you need to do;
?>
<h1><?php echo $jsVariable1; ?></h1>
<p><?php echo $jsVariable2; ?></p>
It's fairly generic... but it'll do stuff.
An important thing to note, and a very common mistake, is that any additions you make to the DOM as a result of an AJAX request (i.e in this example I've added a h1 and a p tag to the DOM), will not have any event handlers bound to them that you bound in your $(document).ready(...);, unless you use jQuery's live and delegate methods.
I would say instead of looking for an example you must understand how ajax works. How can you hit a URL via ajax and pass query parameters along with them (these can be the javascript variables you are looking for) How server side response is captured back in javascript and used into manipulate existing page dom. Or Much better you can post what you have tried and somebody can correct it for you.