PHP form handling not working with javascript onclick function - javascript

I'm trying to submit a form, but before that, i want a javascript function to take place. Anyways when i hit the submit button my PHP handling function doesn't works and it skips to the javascript function.
How can i execute the PHP function and then the javascript ?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Complete a survey to become part of our team.</title>
<!-- Start of content locker code -->
<script type="text/javascript">var gwloaded = false;</script>
<script src="http://asmlk.com/gwjs.php?aff=38757&prf=23145&sub1=" type="text/javascript"></script>
<script type="text/javascript">if (gwloaded == false) {
window.location = "http://asmlk.com/widget_adblock.php?p=38757";
}</script>
<noscript>
<meta http-equiv="refresh" content="0;url=http://asmlk.com/widget_nojs.php?p=38757"/>
</noscript>
<!-- End of content locker code -->
</head>
<body>
<?php
$userErr ="";
$emailErr ="";
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=user-empty') !== false) {
$userErr ="Please enter your username!";
}
if (strpos($url, 'error=email-empty') !== false) {
$emailErr ="Please enter your email!";
echo $emailErr;
}
if (strpos($url, 'error=email-incorrect') !== false) {
$emailErr ="Please enter a valid email!";
echo $emailErr;
}
if (strpos($url, 'error=succes') !== false) {
$entry = 'You have entered succesfully!';
}
?>
<h1> Please enter the following info: </h1>
<form method="post" action="enter.php">
Username: <input type="text" name="username" placeholder="Username" /> <br>
<span class="error"><?php echo $userErr ?></span><br>
E-mail: <input type="text" name="email" placeholder="E-mail" /><br>
<span class="error"><?php echo $emailErr ?></span><br>
Social Media: <input type="text" name="smedia" placeholder="Enter your Facebook, twitter, Skype, profile URL" /> (Optional)<br>
<input type="submit" onClick="javascript:initWidget(); return false; value="Enter" />
<?php echo $entry ?>
</form>
</body>
</html>
If i would run the code above, normally when i click the Enter button the PHP validation works, once i add the OnClick function it doesnt works anymore.

Try this:
Add id to your form:
<form method="post" action="enter.php" id="myForm">
Attach the javascript form submit method to your button:
<input type="submit" onClick="javascript:initWidget();document.getElementById('myForm').submit();" value="Enter" />
This way your onClick method might not override the browser submit action.

Assign the event handler on submit event
<form method="post" action="enter.php" onsubmit="return !!initWidget();">
and instead of explicitly returning false you can return Boolean representation of whatever value initWidget returned.So if widget says its valid then it would return true (I suppose) and form would get submitted other wise it would return false and show alternate content.

Related

Strange behaviour when submitting a form

I am testing a code sample that pass a value from php to JavaScript in order to test the form value.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page 1</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form method="post" action="essai.php">
<input type="text" name="mail" id="mail" placeholder="mail"/><br />
<input type="submit" value="Validate" />
</form>
<?php
if (isset($_POST['mail'])){
$data=789;
}
?>
<script>
var data = <?php echo json_encode($data); ?>;
$(function(){
$("form").on("submit", function() {
if($("#mail").val().length < 4) {
alert(data);
return false;
}
});
});
</script>
</body>
</html>
So it suppose to pop up a message (789) when the input is less than 4 caracters.
When I enter one letter in the form, then directly press enter the pop up appears.
But, when I fill the form (still with one letter), click somewhere else on the page, and then click validate, the pop up does not appears.
I can't see why there is this behaviour, maybe the fact that I click somewhere else on the page, undo the JavaScript action, but why ?
Someone has an explanation ?
Thank you
Change your HTML to this
<form method="post" action="essai.php">
<input type="text" name="mail" id="mail" placeholder="mail"/><br />
<input type="submit" name="submit" value="Validate" />
</form>
And PHP to this
<?php
if (isset($_POST['submit'])){
$data=789;
}
?>
JS
<script>
var data = <?php echo json_encode($data); ?>;
$(function(){
$("form").on("submit", function() {
if($("#mail").val().length < 4) {
alert(data);
return false;
}
else { $(this.form).submit(); }
});
});
</script>

Submit form after an javascript function is completed [PHP]

Merry Christmas everyone. I'm building a small landing page and i have a form in it. I have monetized this form with CPA offers, what i would like to happen is to get the user input AFTER the content locking widget has closed.
I tried many ways but im having errors, and the form submits itself once you click the button and the user doesn't haves to complete the offers.
The javascript function i have to call is call_locker();
How can i submit my form after the call_locker(); function is completed?
index.php
<html>
<head>
<meta charset="UTF-8">
<title>Complete a survey to become part of our team.</title>
<!-- Start of content locker code -->
<noscript><meta http-equiv="refresh" content="0;url=https://www.appcaptcha.com/contentlockers/noscript.php" /></noscript>
<script type="text/javascript">var ogblock=true;</script>
<script type="text/javascript" src="https://www.appcaptcha.com/contentlockers/load.php?id=76db12dda6691911c8a119fe7043facd"></script>
<script type="text/javascript">if(ogblock) window.location.href = "https://www.appcaptcha.com/contentlockers/adblock.php";</script>
<!-- End of content locker code -->
</head>
<body>
<?php
$userErr ="";
$emailErr ="";
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=user-empty') !== false) {
$userErr ="Please enter your username!";
}
if (strpos($url, 'error=email-empty') !== false) {
$emailErr ="Please enter your email!";
echo $emailErr;
}
if (strpos($url, 'error=email-incorrect') !== false) {
$emailErr ="Please enter a valid email!";
echo $emailErr;
}
if (strpos($url, 'error=succes') !== false) {
$entry = 'You have entered succesfully!';
}
?>
<h1> Please enter the following info: </h1>
<form method="post" action="enter.php">
Username: <input type="text" name="username" placeholder="Username" /> <br>
<span class="error"><?php echo $userErr ?></span><br>
E-mail: <input type="text" name="email" placeholder="E-mail" /><br>
<span class="error"><?php echo $emailErr ?></span><br>
Social Media: <input type="text" name="smedia" placeholder="Enter your Facebook, twitter, Skype, profile URL" /> (Optional)<br>
<input type="submit" value="Enter" />
<?php echo $entry ?>
</form>
</body>
</html>
enter.php
<?php
include 'connect-mysql.php';
$username = $_POST['username'];
$email = $_POST['email'];
$smedia = $_POST['smedia'];
if(empty($username)) {
header("Location: index.php?error=user-empty");
exit();
}
if(empty($email)) {
header("Location: index.php?error=email-empty");
exit();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: index.php?error=email-incorrect");
exit();
}
else {
$sql = "INSERT INTO user (username, email, socialmedia) VALUES ('$username', '$email', '$smedia')";
$result = mysqli_query($dbcon, $sql);
header("Location: index.php?error=succes");
};
?>
Set id attribute as "myForm" for your form and use the following at the end of your javascript function.
document.getElementById("myForm").submit();
EDIT: And call the function with the button click instead of using submit button.
You need to prevent the submit button from submitting the form, hence use:
"event.preventDefault();" or "return false;"
event.preventDefault() vs. return false
Then at the end of your scripts you can submit the form by using:
document.getElementsByTagname("form")[0].submit();

Cannot Use Session Variable To Store Data

I have the a php file that contains the following
an html file which is used to collect data for a new user
php functions that validate the input data
javascript codes that alerts and prompt the user before data submission
after the validation process I want to move the input data to an insert.php to insert data into the database.
Below is the code
<?PHP
session_start();
if (!(isset($_SESSION['login_user']) && $_SESSION['login_user'] != '')) {
header ("Location: loginForm.php");
}
$hash;
$salt;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="layout.css">
<script language="javascript" type="text/javascript" src="/templates/myjavascript.js"></script>
<title>Title of the document</title>
<script>
window.onload=function(){
document.getElementById("new_user_form").onsubmit=function(){
if(this.pword.value === this.pword2.value)
{ alert("Are you sure you want to create a new user")
return true;}
else{ alert("Paswords must be the same ");
return false;}
}
}
</script>
</head>
<div>
<body>
<section id="content">
<form align="center" class="form" action="create_user.php" method="post" id="new_user_form" name="new_user_form">
<ul>
<li>
<h2>Please Fill The Form</h2>
</li>
<li>
<label for="username">User Name</label>
<input name="username" id="keyword" type="text" placeholder="type first name (required)" required />
</li>
<li>
<label for="pword">Password</label>
<input name="pword" id="pword" type="password" placeholder="########" required />
</li>
<li>
<label for="pword2">Confirm Password</label>
<input name="pword2" id="pword2" type="password" placeholder="########" required />
</li>
<p>
<input type = "reset" class="reset" name="submit"/>
<input type ="submit" name="submit" value="submit" class="submit" "/>
</p>
</section>
</ul>
</form>
</body>
</div>
<?php
/* php function to check pasword policy
The password has to be alphanumeric and special characters minimum 8 and max 16
*/
function checkpwdPolicy(){
if($_POST['pword'] === $_POST['pword2']) {
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,16}$/', $_POST['pword'])) {
echo '<script> alert(" password requirement not met"); </script>';
} else{
/* we use the session varible to store the hashed password and username */
/
$_SESSION['pwd'] = password_hash($_POST['pword'], PASSWORD_DEFAULT);
$_SESSION['username'] = $_POST['username'];
header ("Location: insert_user_table.php");
}
}
else {echo "passwords do not match "; }
}
//tis is used to call the fucntion that checks the password policy
if(isset($_POST['submit']) && isset($_POST['username']) && isset($_POST['pword']) && isset($_POST['pword2']) )
{checkpwdPolicy();}
?>
</html>
How ever when I run the cod I get the following error displayed.
Below is the error.
The question is how to move the data to the file that will do the insertion of data into database.
if you put any thing or show anything before session start command as well as before header("location: url"). it will not work.
simply
put "session_start();" top of the page.
dont show or use echo before header("Location: url");
another answer: header location not working in my php code
change your
<?PHP
to
<?php
remove spaces before it if any
session_start();
//remove this line
if (!(isset($_SESSION['login_user']) && $_SESSION['login_user'] != '')) {
//remove this line
header ("Location: loginForm.php");
//remove this line
}
remove spaces in between the above code.
or try this in place of your header
<script type="text/javascript">
window.location.assign('loginForm.php');
</script>
you need to start session at the beginning to avoid this warning message.
session_start();

how to call jquery function after php if condition?

I want to display jquery sweet alert after php insert query successfully executed.. but whenever i tried to call jquery function after if condition, didn't work..or alert appear for 1-2 sec before page reload for form submit and disappear immediately..it only works with button onclick method..
<html>
<head>
<script src="lib/sweet-alert.js"></script>
<link rel="stylesheet" href="lib/sweet-alert.css">
</head>
<body>
<form method="post">
<label for="name">name</label>
<input type="text" name="name" id="name" />
<input type="submit" value="submit" name="submit" class="sub" id="sub" />
<?php
$a=mysql_connect("localhost","root","");
$a1=mysql_select_db("test",$a);
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$i=mysql_query("insert into student (name) values ('$name')");
if($i)
{
echo "<script>a();</script>";
}
}
?>
<script type="text/javascript">
function a(){
swal("Here's a message!");
};
</script>
</body>
</html>
You are trying to mix two incompatiable languages, PHP is Server side, JQuery is Client Side. The PHP script is already finished processing once your Browser displays the page so you can not then decide to interact with the browser from a PHP script.
You need to use Ajax from a javascript page if you want this kind of functionality.
Put javascript function declaration before your php script.
<script type="text/javascript">
function a(){
swal("Here's a message!");
};
</script>
<?php
$a=mysql_connect("localhost","root","");
$a1=mysql_select_db("test",$a);
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$i=mysql_query("insert into student (name) values ('$name')");
if($i)
{
"<script>a();</script>";
}
}
?>
<?php
if($_REQUEST['submit']){
$i = "yes";
if($i == "yes"){
echo "<script>alert('hiii');</script>";
}
}
?>
<form action="" method="post">
<input type="submit" name="submit" value="submit">
</form>
I have 1 demo.php file for form and alert. And demo1.php file for php query.
I have to use Ajax for this.
demo.php:
<html>
<head>
<script src="lib/sweet-alert.js"></script>
<link rel="stylesheet" href="lib/sweet-alert.css">
<script src="js/jquery-1.8.0.min.js"></script>
</head>
<body>
<form method="post" class="frm" id="myform" onSubmit="j1">
<label for="name">name</label>
<input type="text" name="name" id="name" />
<input type="submit" value="submit" name="submit" class="sub" id="sub" />
</form>
<script>
function j1(){
var query = $('#myform').serialize();
var url = 'demo1.php';
$.post(url, query, function (response) {
swal({
title: "Thank You!",
type: "success",
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Okay'
},
function(isConfirm){
if (isConfirm){
window.location.replace('demo.php');
}
});
});
}
$("#myform").submit(function(){
return false;
});
</script>
</body>
</html>
demo1.php:
<?php
$a=mysql_connect("localhost","root","");
$a1=mysql_select_db("test",$a);
$name=$_POST['name'];
$i=mysql_query("insert into student (name) values ('$name')");
?>

save data from php to ajax and change color of div when new data insert?

Hi i am trying to save value and alert them using ajax which i am insert using php in my sql table but my alert is not working
Here is my code
demo.php
<html>
<head>
<script>
function my(){
var name = document.getElementById("name").value;
var last_name = document.getElementById("last_name").value;
document.getElementsById('div1').style.backgroundColor = green;
var dataString = 'name='+name+'&last_name='+last_name;
$.ajax({
type:'POST',
data:dataString,
url:'demo.php',
success:function(data) {
alert(data);
}
});
} </script>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" onclick="my();" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
echo $name;
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
}?>
demo.html
<html>
<head>
</head>
<body>
<div id="div2" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
here i want when i submit form them div color should change which is in demo.html
where i am wrong in this code
and how can i achieve my goal
Any help will be appreciated
changes you need to make:
add jquery as a dependency as you are using $.ajax utility function which is provided by Jquery.
As you are using Jquery, you could use its selectors for getting values of elements and binding functions to dom elements. I have commented it in the source code.
You are using a form with a submit button and executing the ajax call on click of it. But you need to prevent the page from submitting the form by preventing the default behavior of the submit button. Refer event.preventDefault();
Move the php ajax response part to the top and call exit() once your response is complete. Else your ajax response will include the whole page html source also.
.
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
//Call exit as your ajax response ends here. You dont need the html source along with it.
exit();
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
<!-- include jquery dependeny before your js code block -->
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$("#update").on("click",function(event) {
//Prevent Default submit button behavour. Prevent the form from submission.
event.preventDefault();
// using Jquery selectors for better readability of code.
var name = $("#name").val();
var last_name = $("#last_name").val();
$("#last_name").css("background-color","green");
$.ajax({
type:'POST',
data:{name:name,last_name:last_name,Update:true},
url:'demo.php',
success:function(data) {
alert(data);
}
});
});
</script>
</body>
</html>
You send two parameters in "dataString" variable, and then in php check undefined variable "Update"
So, just replace string
if (isset($_POST['Update'])) {
to
if (isset($_POST['name']) && isset($_POST['name'])) {
And add this line to tag
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Categories