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>
Related
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.
I would like to achieve that when I click on submit button, it doesn't refresh the page.
My submit button only calls set of codes if is submitted.
But when it is submitted, it refreshes the page and my variables lose its values.
I know this can be achieved with java-script or ajax but this is where I have no knowledge yet. Need to start learning it.
I have tried to use some other suggestion with JavaScript but it didn't work for me as the JavaScript code was build for most advance form not only one submit button.
My Button:
<form action='{$_SERVER['PHP_SELF']}' method='post'>
<input type='submit' class='submit' name='confirm_points' value='Confirm Points' />
</form>";
My code which executes when submit button is pressed:
if(isset(&_POST['confirm_points'])) {
// my code is here
}
Thanks for any help
Here's a simple example:
<?php
if (isset($_POST['points'])) {
echo "I'm AJAX and I have " . $_POST['points'];
exit();
}
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
$.ajax({
type: $(this).attr('method'),
data: $('form').serialize(),
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
</head>
<body>
<form method="POST">
<input type="text" name="points" placeholder="Some data" value="25 points"/>
<input type='submit' class='submit' name='confirm_points' value='Confirm Points' />
</form>
<div id="result"></div>
</body>
</html>
Page with the form that should submit by ajax
<html>
<head></head>
<body>
<form id="my-form">
<input type="text" name="username" /> <br/>
<input type="submit" value="Save" />
</form>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function () {
$('#my-form').submit(function (e) {
var $data = $(this).serialize();
var $url = 'path_to_processing_script';
$.post($url, $data, function ($response, $status ) {
if ( $status == 'success' ) {
alert($response);
}
});
e.preventDefault();
});
});
</script>
</body>
</html>
The processing script
<?php
var_dump($_POST);
?>
First to stop refreshing, change your form header to:
<form action='{$_SERVER['PHP_SELF']}' method='post' onsubmit="javascript:return false;" id="myform">
Next, to submit form using ajax:
<script src="path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit(function(){
var elem1=$("#elem1").val(); //get values of inputs for validation
if(elem1.length<5){alert("Length too short!");}//Sample Validation
else{
$.ajax({
url:"verify.php",//link to your submission page
type:"post", //change to your needs
data:{"elem1":elem1}, //add all variable
success:function(response){alert(response);} //Manage Response
});
});
});
</script>
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')");
?>
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>
My problem is that this code is display "blablabla" when I push 'submit':
<html>
<head>
</head>
<body>
<?php if (isset($_POST["text"])):{
echo $_POST["text"];
}else: ?>
<form action="" method="post" id="testform">
<input type="text" value="blablabla" name="text"/>
<input type="submit"/>
</form>
<?php endif ?>
</body>
</html>
but this second code continue to display the form even after clicking on the button and does not show "blablabla":
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(function (){
$('#testbtn').click(function() {
$.post('',{text:'blablabla'});
});
});
</script>
</head>
<body>
<?php if (isset($_POST["text"])):
echo $_POST["text"];
else: ?>
<form action="" method="post" id="testform">
<input type="button" id="testbtn"/>
</form>
<?php endif ?>
</body>
</html>
Why?
Logic, if we do an ajax post, just send the content we want to show inside the body, else show the entire page like if it was a normal form submit. The success callback inside the ajax call, will replace the body with innerHTML
<?php
function getBody() {
if (isset($_POST['text'])) {
// normally I would htmlspecialchars() this variable to disallow HTML injection
echo $_POST['text'];
}
}
if (isset($_POST['ajax'])) {
getBody();
exit();
}
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(function (){
$('#testbtn').click(function() {
$.post('',{text:'blablabla', 'ajax':1}, function(bodyData) {
document.body.innerHTML = bodyData;
});
});
});
</script>
</head>
<body>
<?php if (isset($_POST["text"])):
getBody();
else: ?>
<form action="" method="post" id="testform">
<input type="button" id="testbtn"/>
</form>
<?php endif ?>
</body>
</html>
give the page url in post
$.post(window.location, {tetx: 'blablabla'}, success: function(data) {
alert('successful.the response from server is' + data);
});