简体   繁体   中英

Using jquery to load external php file?

Forgive me for asking such a basic question, but I have tried and failed many times trying to figure out what's wrong. I have a very simple html form consisting of one checkbox. I would then like to use jquery to load an external php file onto the same page as the form in the 'content' div, so that the form is clearly updateable. The php file is simply a check to see whether the checkbox was checked and to return the result on screen. Here is the html:

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#submitbutton").click(function(){
    $("#content").load("loadedpage.php");
    return false;
  });
});
</script>
</head>

<body>
<form id="testform" action="" method="post">

<input type="checkbox" id="checkbox1" name="checkbox1" value="testcheckbox">Check this box:</input>
<input type="submit" id="submitbutton" name="submitbutton" value="Submit">
</form>

<div id="content">

</div>

</body>
</html>

And here is the external php file:

<?php

    if(empty($_POST["checkbox1"]))
    {
        echo "box wasn't checked";
    }
    else
    {
        echo "box was checked";
    }

?>

My problem is that no matter whether the checkbox is ticked, the php will return "the box wasn't checked", however, when I have passed this form to the php file through the 'action' attribute everything works as it should, therefore I know the error is probably in the jquery. If anyone could shed some light I would be very grateful.

Your approach is wrong. You can do that using Jquery.

$(document).on("click", "#submitbutton", function(e){
    e.preventDefault(); // To stop form from submitting
    if($('#checkbox1').is(":checked")){
        $("#content").html("Checkbox is checked");
        $("#testform").submit();
    }else{
        $("#content").html("Checkbox is not checked");
    }
});

You need to send checkbox value in the request that is being made in .load() like this:

$(document).ready(function(){
  $("#submitbutton").click(function(){
    $("#content").load("loadedpage.php", {checkbox1: document.querySelector('#checkbox1').checked });
    return false;
  });
});
$("#submitbutton").click(function(event){
    if ($("#checkbox1").is(':checked') === false) {
      $("#content").load("loadedpage.php");
    } else {
      $("#content").load("loadedpage.php", { checkbox1: true });
    }

    return false;
  });

or

$("#submitbutton").click(function(event){
    $("#content").load("loadedpage.php", { checkbox1: $("#checkbox1").is(':checked') ? true : null });
    return false;
  });

You're checking for empty in your loadedpage.php instead you can check for true and false.

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