简体   繁体   中英

How to return check value from a php script to the calling page?

Hi: I'm very new to the whole web scene. I'm trying to do a page where the user has to enter some information and then what I want to do is check its format and if it is correct added to a database. If it is not, an error message has to be shown.

My code is essentially this, so far (in a file newtask.php):

<form action="addtask.php" method="post" name="newtaskform">

<!-- The form itself, a bunch of fields -->

<input type="submit" value="Agregar nueva tarea">
</form>

When I click submit it calls the addtask.php script that modifies the database. This is already working. I want to add the code to check the format of the data submitted in the form. However I want the error message to appear in newtask.php (the user input webpage). My problem is that if I check the data with a javascript function I have to use ajax to call addtask.php (which I want to try to avoid, if possible) and if I do the checking in the addtask.php script I don't know how to convey the error message back to the newtask.php webpage.

Any help or suggestions?

you can do two layers of checks. you can use javascript to validate the form first and if it passes then you can use $('#'+formid).submit() to submit the form as per usual (Note, give your an ID property). Then you can check the backend as well and if something goes wrong you can send an error back to the page.

Now, the problem with sending the error back to the page is how do you get back to the previous page with the inputs all still in place, as a typical form submission would actually send the request to the processing page. One trick i learned was that you can submit the form to an iframe which will submit the page to the backend without reloading the front end page

<FORM name='iform' id='iform' method='POST' action='addtask.php' TARGET='submitiframe' accept-charset='UTF-8'>

and have this code at the bottom of your page

<IFRAME STYLE='border:0px;display:none;' id='submitiframe'></iframe>

In the backend, you process as normal but rather than echo'ing a status back to the browser, you can do something like this. In this example, if the processing was successful i send back a "status" of "1"

    echo "<!DOCTYPE HTML>
        <HTML>
        <HEAD>
            <script type='text/javascript' src='/js/jquery-1.10.2.min.js'></script>
            <script type='text/javascript'>
                $(document).ready(function() {
                    $(window).load(function() {
                        var r = $('#response').html();
                        parent.getresult(r);
                    });
                });
            </script>
        </HEAD>
        <BODY>
        <DIV ID='response'>".json_encode(Array("status"=>$status))."</DIV>
        </BODY>
        </HTML>";
exit();

On the front end page you would have corresponding javascript code to capture this request and process the success or failure

        function getresult(text) {
        try {
            var rc = $.parseJSON(text);
            if(parseInt(rc.status)  == 1) 
                location.reload();
            else
                alert (rc.msg);
        }
        catch(e) {
            alert('Something went wrong!')
        }
    }

The easiest KISS solution would be to keep the code responsible for adding tasks (and validating the form) in same file as the form. This will also make it easy for you to keep all the form elements filled with submitted data if the task couldn't be added.

You can check if form was submited by naming the submit button (adding name attribute) and then checking, if it's set in $_POST array.

Make a single PHP file. This is for your demonstration only.

<?php

if(isset($_POST['submit'])) {
//IF FORM IS SUBMITTED
if($_POST['name'] == '') {
//NAME IS BLANK
$flag = 0;
}
else {
// SQL QUERY TO INSERT DATA
$flag = 1;
}

}

?>

<?php

if(isset($flag)) {

if($flag == 1) {
echo "Data inserted successfully";
}
else {
echo "Name is blank";
}

}

?>

<form action="" method="post" name="newtaskform">
<!-- The form itself, a bunch of fields -->
<input type="" name="name">
<input type="submit" value="submit" name="submit"> 
</form>

Create a function for adding record to the database in addtask.php file may be addRecord(). Include that file in newtask.php file. Do a post of the form on newtask.php instead of addtask.php on form submit do the validation of fields, if validation passes call the function addRecord() with POST data, or else if validation fails show the validation errors above the form.

Validation can be done using your custom code or may be you can use some class from phpclasses.org

Hope it helps

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