javascriptphpjqueryajax

How to request PHP file with JavaScript and pass parameters


I need to run a PHP function in a page, after the user clicks on something, in this case, a link.

First I was using onclick to run a JavaScript AJAX to request a PHP file with the function in it. The thing is, I need to pass a parameter to the function, and I can't seem to be able to do it with AJAX.

If it was a PHP include, it would behave like it 'appended' the other file to the current file, so this way, the included file could reference variables in the current file. Apparently, AJAX is just taking the file I need, running it's code, and displaying the results. So yeah, doesn't work for me.

So basically. I need an exact replica of PHP's 'include', on JavaScript. OR any other workaround.

My current code:

<br> <div id="seeMore"> </div> <br>

<ul> <li style="float: left"> <a href="#" onclick="loadMore();">Ver Mais</a> </li> </ul>

<script type="text/javascript">
function loadMore()
{ $("#seeMore").load("feedP.php"); }
</script>

This is the part of the code in the main page that im needing help with, you can see it's loading a page called feedP.php, here's it's code:

<?php

echo 'test';
require_once('functions.php'); loadFeeds($urls, 5);

?>

As you can see, I have to run a function called loadFeeds, and it requires a parameter, $urls which is created back on the main page.

EDIT:

I CAN'T reload the page, or redirect the user, that's why I'm trying to 'append' the file here.


Solution

  • You can use the second parameter of the load function which takes parameters that can be posted to the file in question:

    $("#seeMore").load("feedP.php", {
        url: 'url'
    });
    

    Then, in your PHP you can make use of $_POST to access the posted data.

    data

    Type: PlainObject or String

    A plain object or string that is sent to the server with the request.

    Reading Material

    .load