Jquery Ajax Post data on multiple pages running on background - javascript

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.

Related

Jquery AJAX shows webpage when form is submitted successfully

I have a form in PHP am sending via AJAX Jquery. The form is sent successfully via AJAX JQuery but the webpage is shown when the success message shows or the form is sent. What might be the exact problem causing this.
<? php include_once 'config.php'; if(isset($_POST) && !empty($_POST)) { $staff_number=$ _POST[ 'staff_number']; $department=$ _POST[ 'department']; $stmt=$ link->prepare("INSERT INTO `staffs` (`staff_name`,`department`) VALUES (?,?)"); $stmt->bind_param('ss',$staff_name, $staff_number, $designation, $department); if ($stmt->execute()){ echo "<span style='background-color:#69d052;
padding:6px;
color:white; font-size:13px;border-radius:5px;'>Staff created
successfully. </span>"; } else{ echo "
<p align=center>Error inserting data.</p>"; echo mysqli_error($link); } } ?>
<!DOCTYPE html>
<body>
<div class="container">
<div class="col-md-7 col-md-offset-3">
<form action="" method="post" autocomplete="off" id="my_form">
<div class="form-group">
<label>Staff Name</label>
<input type="text" required="true" name="staff_name" class="form-control" value="">
</div>
<div class="form-group">
<label>Department</label>
<input input="text" name="department" class="form-control" value="">
</div>
<div class="message_box" style="margin:50px 0px;">
</div>
<br>
<input type="submit" class="btn btn-success" value="Add">
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.message_box').html('Processing...');
$.ajax({
type: 'post',
data: $('form').serialize(),
success: function(data) {
$('.message_box').html(data).fadeIn('slow');
$("#my_form")[0].reset();
}
});
});
});
</script>
</body>
</html>
You might be Redirecting the request after success from the server side (PHP). That's why a page is showing.
In you ajax call you are not setting your url property, by default this will be set to the current page, that is why you might be getting the page instead.
try adding your url, to your ajax...
$.ajax({
url: '..my ajax url.....',
type: 'post',
data: $('form').serialize(),
success: function(data) {
$('.message_box').html(data).fadeIn('slow');
$("#my_form")[0].reset();
}
});

PHP Prevent Re submission for multiple forms on same page

Hi have checked answer from this page: But it uses action="" is it vulnerable to XSS attacks? If yes then without such solution what are my options?
I tried using header redirect. But as I have 2 forms,(in some pages 4-5 forms) header re direction is not working for me with errors.
Here is my code: (Simplified)
1st form: works ok with a redirect.
<form name="ip_block" method="post" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-default"
name="ip_block_add">Submit</button>
</div></div>
</form>
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
header("refresh:5;url=./admin-security.php");// avoiding form
resubmission
echo 'Added successfully';
}
else {
echo 'failed to insert';
}
}
?>
Form 2:
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<button type="submit" class="btn btn-warning">Clean Data</button>
</form>
<?php
if(isset($_POST['data_clear'])){
if($mysqli->query("CALL clear_old_data")){
header("refresh:5;url=./admin-security.php");// avoiding form resubmission
echo 'operation successfull';
}
else
{
echo 'database failure';
}
}
//----
?>
For Second form I get error like this
Warning: Cannot modify header information - headers already sent by
For 2nd form I am using header before echo still it doesn't work.
reference, I tried with javascript too but that failed.
echo "<script>setTimeout('window.location.href='./admin-
security.php';',4000);</script>";
Updated with Dainis Abols idea: but form re submit option is still showing on page refresh
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<?php
$var=111;
$_SESSION['var']=$var;
?>
<input type="hidden" value="<?php echo $var; ?>" name="varcheck"
/>
<button type="submit" class="btn btn-warning">Clean
Data</button>
</form>
<?php
if(isset($_POST['data_clear']) &&
($_POST['varcheck']==$_SESSION['var'])){
// Some code
}
I'd rather use ajax to send data to the database, without form submiting, and on success I would use js to redirect to /admin-security.php. In this case it's not possible to send the data twice.
Here is the PHP Code:
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
echo 1;
}
else {
echo 0;
}
exit;
}
?>
HTML:
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="button" onClick="send_form()" class="btn btn-default"
>Submit</button>
</div></div>
</div>
And AJAX written with JQuery
<script>
function send_form() {
$.ajax({
url: "./admin-security.php",
type: "POST",
data: {
ip: $("#ip").val()
},
success: function(response) {
if(response==1) {
alert("Done");
location.href = "./admin-security.php";
}
else alert("Fail!");
}
});
}

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>

jQuery Mobile popup only works on initial page load

I've got a really simple form that displays a single field. When you punch in a value and hit submit, it gives you a list of checkboxes. You check some and then click another button below and it displays a success/failure message.
I'm trying to convert this to a jQuery mobile app but am having nothing but problems. For example, I can pragmatically call a popup using $("#element").popup("open"); when the page first loads, but after the post when I call the popup open like above I see the URL change but no popup is visible and it's pretty much the exact same page. I also tried just posting the checkboxes to a secondary URL (/update) and then use an HTTP redirect back to the original page, but somehow jQuery Mobile is breaking that.
I've pasted the majority of the code below. If anyone can point me in the correct direction, that's all I'm looking for.
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.2/jquery.mobile.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.2/jquery.mobile.min.js"></script>
<script type="text/javascript">
$(document).on("pagecreate", function() {
$(document).on("click", "#button", function(e) {
// Do ajax stuff here
$("#popupBasic").popup("open");
});
});
</script>
</head>
<body>
<div id="lookup" data-role="page">
<div data-role="header">
<h1>Lookup Order</h1>
</div>
<div data-role="content">
<?php if (validation_errors()): ?>
<div class="errors"><?=validation_errors()?></div>
<?php endif; ?>
<?php if ($this->session->flashdata('error')): ?>
<div class="errors"><?=$this->session->flashdata('error')?></div>
<?php endif; ?>
<form method="post" id="search_form" action="/search">
<label for="term">Term:</label>
<input type="number" data-clear-btn="true" name="term" id="term" value="<?=set_value('term')?>" />
<input type="submit" value="Search" />
</form>
<?php if (!empty($fish) && $fish->num_rows()): ?>
<form method="post" action="/update">
<br /><strong>Species:</strong> <?=$species?><br />
<hr />
Uncheck All / Check All<br />
<?php foreach ($fish->result_array() as $k => $f): ?>
<fieldset data-role="fishgroup">
<?php if (!$f['is_deleted']): ?>
<input type="checkbox" name="fish[]" id="checkbox-<?=$f['id']?>" value="<?=$f['id']?>" checked="checked" />
<?php else: ?>
<input type="checkbox" name="fish[]" id="checkbox-<?=$f['id']?>" value="<?=$f['id']?>" checked="checked" disabled="disabled" />
<?php endif; ?>
<label for="checkbox-<?=$f['id']?>">
<?php if ($f['type']): ?>
<?= $f['1'] ?> <?= $f['2'] ?> Attr: <?= $f['3'] ?> Attr: <?= $seat['4'] ?>
<?php else: ?>
<?= $f['3'] ?> <?= $f['4'] ?>
<?php endif; ?>
</label>
</fieldset>
<?php endforeach; ?>
Uncheck All / Check All<br /><br />
<input type="button" value="Update Fish(s)" id="button" />
</form>
<?php endif; ?>
<div data-role="popup" id="popupBasic">
<p>This is a completely basic popup, no options set.</p>
</div>
</div> <!-- end content -->
</div><!-- end page -->
</body>
</html>
Using the following prevents the click handler from being called twice but I still don't get the actual popup after the initial page load:
$(document).off("click").on("click", "#button", function() {
$(" #popupBasic").popup("open");
});
All I'm getting is #&ui-state=dialog added to the URL, and calling $("#button").popup("close"); removes that.
It might be that youre attaching same handler multiple times add
<script type="text/javascript">
$(document).on("pagecreate", function() {
$("#button").off();
$(document).on("click", "#button", function(e) {
// Do ajax stuff here
$("#popupBasic").popup("open");
});
});
</script>

Categories