HoodCoderMan HoodCoderMan - 4 months ago 8
jQuery Question

JQUERY return PHP script on button click

Hopefully, this will be a simple question...

Currently, I have a HTML page that includes a php script. Once the user signs in, with the php script included, the data is automatically returned to the page, as follows:

<section class="content">
<?php include("api/qnams_all.php"); ?>
</section>


That script includes a query that returns a table with an ID called #example1.

Using that ID, I am to use jquery datatables to format the data from that script:

$('#example1').DataTable({
{
"dataType": "json",
"iDisplayLength": 25,
"bDestroy": true,
"stateSave": true
});


Now, what I would like to do, is check if a button was clicked via jquery, and if so, run a different php script.

So in that section tag above, I want to do something like this:

<section class="content">
<button type="button" id="buttonSearch">Search</button>
<script type="text/javascript">
if('#buttonSearch').click(function()
{
// return <?php include("api/differentScript.php"); ?>
}
else
{
// return <?php include("api/qnams_all.php"); ?>
});
</script>
</section>


I am sure the syntax is probably wrong in the javascript. I was trying to show an example of what I'm trying to do.

I am not sure if this can even be done. If so, please enlighten me. I would greatly appreciate it.

Answer

I would use an ajax call to the page. Listen to whats been requested in PHP and return it. Then add the result of this to a HTML object on page.

I would approach it similar to this;

<?php 

if(isset($_POST['script1'])){
    include("api/differentScript.php");
    exit;
}

if(isset($_POST['script2'])){
    include("api/qnams_all.php");
    exit;
}

?>

<div id='output'></div>


<script type="text/javascript">

    $("#buttonSearch").on('click', function(){
        $.ajax({
            type:"POST",
            url: "/page_location/",
            data: "script1=true",
            success: function(result){
                $("#output").html(result);
            }
        });
    });

    $("#buttonSearch2").on('click', function(){
        $.ajax({
            type:"POST",
            url: "/page_location/",
            data: "script2=true",
            success: function(result){
                $("#output").html(result);
            }
        });
    });

</script>

I'm not sure how data tables works, if you were to store the data in a variable you could send it with the post data by changing it to:

data: {script1: true, post_data_1: var}, 
Comments