Ryan
Ryan

Reputation: 15

should jquery ajax go to the same page or another php file?

My Current Setup

  1. my sites home page (rankings.php) shows a list of users with a search form at the top to filter users by their gender or city.

  2. I want to use jquery ajax to update the results without reloading the page.

  3. My Question:

    • with either method (load,post,get) you need to enter the url to send the request to but I'm not sure if the url should be the rankings.php page itself or another php file that holds the mysql query to get new results from the database. Which is best? should ajax requests go to another php and then the results sent back to the main php file where the content will be reloaded or should the ajax request go to the same php file it came from and then jquery to replace the content with the returned html data?

shorter version of question: should ajax url point to the page the ajax request comes from or point to another php file and then the data returned back?

Upvotes: 0

Views: 500

Answers (1)

Barmar
Barmar

Reputation: 781130

It should point to the URL of the script that performs whatever function you need the AJAX request to do. It can be the same or a different URL from the page that contains the caller. If it's the same page, you'll need to put conditionals in the script that detects whether it's being used to process an AJAX request or to display the regular page, usually by checking the parameters.

For instance, you might send the AJAX request with:

$.ajax({
    url: '<?php echo $_SERVER['PHP_SELF']; ?>',
    type: 'post',
    data: { action: 'dosomething', ... },
    ...
});

Then in the PHP script, you would do:

if (isset($_POST['action']) {
    // code to process AJAX request
} else {
    // code to display the page HTML
}

I generally find it simpler to put the AJAX code in a separate script, so I don't have to do that.

Upvotes: 2

Related Questions