How to call included php file with AJAX?

那年仲夏 提交于 2021-02-08 10:24:44

问题


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?


回答1:


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);
?>



回答2:


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



来源:https://stackoverflow.com/questions/30428961/how-to-call-included-php-file-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!