Alan Kis
Alan Kis

Reputation: 1910

How to call included php file with AJAX?

I am not sure if this is best approach, but how to make AJAX call with included file? Let me make working simple example.

I have, main index.php file, with following content, where I want to access all data returned from included file where magic happens. Data is array type in reality.

<?php
require_once('magic.php');
?>
<html>
<body>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="POST">
     <input type="text" name="variable" id="variable" />
     <input type="submit" value="Do magic" name="submit"  />
</form> 
<?php
    echo "<pre>";
    print_r($data);
    echo "</pre>";
?>
</body>
</html>

And "magic.php" file, where all the magic happens.

<?php
$variable = $_POST['variable'];
function doMagic($variable) {
    # do some magic with passed variable ...
    # and return data
    return $data;
}
$data = doMagic($variable);
# now return $data variable so main file can use it
return $data;
?>

What I want to do is to call this function doMagic() with AJAX, but all logic is already included and available in global space, and return $data to modal or pop-up window.

What is best approach, because I am already passing variable to included file?

Upvotes: 0

Views: 993

Answers (2)

Axiom
Axiom

Reputation: 902

Since you have jQuery as a tag...

You could do something like this:

In your index.php:

<input type="text" id="variable">
<div id="#myButton"></div>
<div id="#response"></div>

Then have a Javascript file (or include in your index.php):

$('#myButton').click(function(){
    var myVariable = $('#variable').val();
    $.post( "magic.php",{variable: myVariable}, function(data) {
        $( "#response" ).html( data );
    });
});

This basically means, when you click the item that has the id of myButton, it'll grab the value of what's inside of the input with the id of variable, POST that via jQuery.post() to your magic.php file, and return the data. Then, it replaces the html of the div with the id of response with the data it returns.

Just make sure to include the jQuery library

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30557

Use ajax like the following

$('form').submit(function(){
     $.ajax({url: "magic.php", 
     data: {variable : $'#variable').val()},
     success:function(data){console.log(data);});
});

and in magic.php, use json_encode

<?php
$variable = $_POST['variable'];
function doMagic($variable) {
    # do some magic with passed variable ...
    # and return data
    return $data;
}
$data = doMagic($variable);
# now return $data variable so main file can use it
return json_encode($data);
?>

Upvotes: 1

Related Questions