how to call jquery function after php if condition? - javascript

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')");
?>

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>

Jquery Ajax Post data on multiple pages running on background

How to execute Jquery Ajax post data on multiple pages.
For Example, I am using three pages named Page1,Page2,Page3. I need to post data from Page 1 -> Page2 and,from Page2 -> Page 3. User initiates only on Page1, all other function should performed in background. Is that possible?
This is the code used.
Page1.php:
<html>
<head><title>Page1</title></head>
<script src="/path to/jquery.min.js"></script>
<body>
<button type="button" class="btn" id="bt">SEND</button>
<script>
var a1="Hello";
var b1="Testing Ajax";
$(function(){
$('#bt').click(function(){
$.ajax({
url: 'Page2.php',
type: 'POST',
data: {'w1': a1,'w2':b1},
alert("Data Sent...");
},
error: function() {
alert("Unable to send data now.");
}
});}); });
</script>
</body>
</html>
Page2.php:
<html>
<head><title>Page 2 </title></head>
<body>
<?
$r1 = $_POST['w1'];
$r2 = $_POST['w2'];
?>
<div id="dom1" style="display: none;">
<?php
$r1 = $_POST['w1'];
echo htmlspecialchars($r1);
?>
</div>
<div id="dom2" style="display: none;">
<?php
$r2= $_POST['w2'];
echo htmlspecialchars($r2);
?>
</div>
<script>
var div1 = document.getElementById("dom1");
var m1 = div1.textContent;
//alert(m1);
var div2 = document.getElementById("dom2");
var m2 = div2.textContent;
//alert(m2);
$.ajax({
url: 'Page3.php',
type: 'POST',
data: {'x1': m1,'x2':m2},
alert("Data Sent...");
},
error: function() {
alert("Unable to send data now.");
}
});
</script>
</body>
</html>
Page3.php:
<html>
<head>
<title>Page3</title></head>
<body>
<div id="dom3">
<?php
$r1 = $_POST['x1'];
echo htmlspecialchars($r1);
?>
</div>
<div id="dom2">
<?php
$r2 = $_POST['x2'];
echo htmlspecialchars($r2);
?>
</div>
</body>
</html>
There are several ways you can solve your problem.
PHP Sessions
You can easily start a session in every of your pages and post
<?php
// every page needs to start the session
session_start();
// after submission or posting
$_SESSION['data'] = $your_data;
?>
So on your next page you can easily access your data via session.
<div>
<?= $_SESSION['data']['var1'] ?>
</div>
Use Forms and send them via jQuery ajax requests and put the form values on the next page into hidden input elements.
<!-- example for page 2 -->
<form id="your_form" method="post" action="">
<input type="hidden" name="var1" value="<?= $var1 ?>">
<input type="hidden" name="var2" value="<?= $var2 ?>">
<input type="submit" id="submit" name="submit" value="submit">
</form>
<script type="text/javascript">
$('#submit').on('click', function( event ) {
event.preventDefault();
$.ajax({
url : your_url,
type : 'POST',
data : $('#your_form').serialize();
});
});
</script>
Just don 't use ajax. You really don 't need it, wenn you jump from page to page. Look the example below.
<!-- on page1.php just a quick form -->
<form id="form1" method="post" action="page2.php">
<label for="var1">Var 1</label>
<input type="text" name="var1" id="var1" value="">
<input type="submit" name="submit" value="submit">
</form>
<!-- on page2.php just another quick form with hidden elements -->
<form id="form2" method="post" action="page3.php">
<label for="var2">Var 2</label>
<input type="text" name="var2" id="var2" value="">
<input type="hidden" name="var1" value="<?= $_POST['var1'] ?>">
<input type="submit" name="submit" value="submit">
</form>
In every 3 given examples you should consider the securty stuff like escaping post vars, etc.

Do not refresh page on submit PHP

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>

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>

Standard form submit render page, but passing data to server by $.post() not render page

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);
});

Categories