views:

38

answers:

2

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

A: 

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.

Darin Dimitrov
+1  A: 

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. :-)

Jonatan Littke