0

I'm trying to make a javascript alert box popup inside some PHP code.

<html>
<body>
<a href=http://localhost/myPage/Index.html><button type=“button” />HOME</button></a>
<br><br>
<form name="SaveNewMember" method="post" >
Add New Member <br><br>
Member ID &nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="ID" value="">
<br>
Member Name <input type="text" name="name" value="">
<br><br>
<input type="reset" style="height:50px; width:80px"  value="CLEAR ">
&nbsp;&nbsp;
<input type="submit" value="ADD" style="height:50px; width:80px" action="<?php  storeMemberData();?>">
</form>
<?php
function storeMemberData()
{
    if((isset($_POST["ID"]))&(isset($_POST["name"])))
    {
        $newID      = $_POST["ID"];
        $newName    = $_POST["name"];

        if((strlen($newID)==5)&(strlen($newName)>=6))
        {
            $con=mysqli_connect("localhost","root","","membersdb");
            mysqli_query($con,"INSERT INTO members 
                        (ID,Name) 
                        VALUES ('$newID','$newName')");
        // Echo result
        echo '<script type="text/javascript"> alert("Successful log"); </script>';
        }
        else
        { 
            echo "<script type=\"text/javascript\">"; 
            echo "alert(\"Invalid please try again.\")"; 
            echo "</script>"; 
        }
    }
}
?>

I have two examples in there. Neither one works. The rest of the code is executing OK (via a submit button on a form). What gets printed to the webpage after submitting is literally the text

alert("Invalid please try again.")">

Any help appreciated, it must be something stupid and basic I'm doing wrong.

EDIT : In trying to keep the question brief I didn't print all my code. That was obviously wrong. Have updated the above to include the html form data above the php code too. This is the complete code.

And this is what prints on my page when it is run (reputation too low to add images)

https://i.stack.imgur.com/ucG4z.jpg

1 Answers1

0

The reason it prints as text is because you are putting the output of the storeMemberData(); inside the button "action" attributes. First, the PHP code will run on the server before any of the HTML output reach the browser, so your HTML will look like

<input type="submit" value="ADD" style="height:50px; width:80px"
action="<script type="text/javascript">alert("Invalid please try again.")</script>">

which creates the error you see.

First, you'll need to remove the action part out of the button. Add a name to your submit button so you can check if the form was submitted.

After that, in your PHP code, check if the submit button was posted and call the storeMemberData();

e.g.

<input type="submit" name="my_submit_button" />

<?PHP
if (isset($_POST['my_submit_button'])){
    storeMemberData();
}
?>
NoGray
  • 1,149
  • 7
  • 9
  • Thank you so much! That was exactly it. I appreciate such a detailed answer, now I know exactly why and where I was going wrong. Thanks! – robotmonkey Jul 22 '14 at 21:52