简体   繁体   中英

Post variables to php file and load result on same page with ajax

I have tried searching quite a bit but can't seem to make anything work.

I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.

What I have so far:

HTML:

    <html>
      <form id="form">
        <input id="info" type="text" />
        <input id="submit" type="submit" value="Check" />
      </form>
      <div id="result"></div>
    </html>

JS:

<script type="text/javascript">

var info= $('#info').val();
var dataString = "info="+info;

$('#submit').click(function (){
     $.ajax({
        type: "POST",
        url: "/api.php",
        data: dataString,
        success: function(res) {
            $('#result').html(res);
                }

  });

});
</script>

PHP:

<?php

  $url = '/api.php?&info='.$_POST['info']; 

  $reply = file_get_contents($url); 

   echo $reply;

?>

When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.

I cannot get any solutions to work.

Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:

$('#submit').click(function (){
 $.ajax({
    type: "POST",
    url: "/api.php",
    data: dataString,
    success: function(res) {
        $('#result').html(res);
    }
 });

 return false;

});

Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(

Thanks everyone for your help, I have it working now.

I was doing a few things wrong:

  1. I was using single quotes in my php file for the URL and also for the $_POST[''] variables.

  2. I needed to add return false; as Steve pointed out.

  3. I did not have a "name" for the input elements, only an ID.

I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax . The code below.

/* ... */

$('#submit').click(function (){
    $.ajax({
        var info= $('#info').val();
        var dataString = "info="+info;

/* ... */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM