I'm just starting to learn javascript today and I was wondering how to call on a javascript function in PHP after it is done submitting a form to the database. My javascript code is basically an alert box saying that your account has been created. Any response wold help. Here is the section of the PHP code that I want to insert the function into (everything else really doesn't matter) and javascript code insert, if you require anything else please tell me. Thanks a lot!
PHP:
<?php
class Registration
{
**FORM VALIDATION AND SUBMISSION NOT INCLUDED**
if ($query_check_user_name->num_rows == 1)
{
$this->errors[] = "Sorry, that user name is already taken. Please choose another one.";
}
else
{
// write new users data into database
$query_new_user_insert = $this->db_connection->query("INSERT INTO users (user_name, user_password_hash, user_email) VALUES('" . $this->user_name . "', '" . $this->user_password_hash . "', '" . $this->user_email . "');");
if ($query_new_user_insert)
{
$this->registration_successful = true;
$this->messages[] = "Registration successful! Please go back to the login page and login in with your new username and password.";
echo "<script type='text/javascript'>myFunction()</script";
}
else
{
$this->errors[] = "Sorry, your registration failed. Please go back and try again.";
}
}
}
else
{
$this->errors[] = "Sorry, no database connection.";
}
}
}
else
{
$this->errors[] = "An unknown error occurred.";
}
}
}
?>
Javascript:
<script>
function myFunction()
{
var r = confirm("Registration Successful!\nYou will now be redirected to the login page");
if(r == true)
{
location.assign("http://yhsaa.org/members/index.php");
}
}
</script>
2 Answers 2
Try this:
echo "<script type='text/javascript'>window.onload = function()
{
myFunction();
}
</script>";
What is happening is that this code creates and event on window object called onload. This event will be fired when your html has finished loading. Then it will call your function myFunction(). This behaviour will make sure that your function was declared before its called, so its avoids not declared exception for your function.
Its like changing this:
myFunction(); // At this time JS doesn't know that you have an function called myFunction()
function myFunction() {};
to this:
function myFunction() {};
myFunction(); // At this time JS already know your function myFunction() and it will call it.
4 Comments
Your script contains an error, you don't close the script tag correctly !
myFunction()been defined in your page somewhere BEFORE where you output your<script>myFunction()</script>text? If not, then you're just going to get a "call to undefined function" error.>in this: echo "<script type='text/javascript'>myFunction()</script";