why when i reload a page using AJAX the data disappears - javascript

Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.

I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>

Related

how to echo the ajax data with the help of php?

I trying to print the data which was entered by the user, and transfer that through ajax and trying to print or echo it with the help of php code, but I could not do that. enter code here
this is my code:
<html>
<head>
<title>
test ajax
</title>
<script src="jquery.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<script>
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
</script>
</body>
</html>
<?php
extract($_POST);
if(isset($_POST["c"])) {
echo $_POST["c"];
}
?>
I think that, I have the problem with the php code. please give me any solution.
Try it like this
This is your Html
<html>
<head>
<title>
test ajax
</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type = "text" id = "a" > <br>
<input type = "button" id = "b" value = "display" >
</form>
</body>
</html>
<script>
$(document).ready(function(){
$('#b').click(function() {
let a = $('#a').val();
//alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {c: a},
success: function(response) {
alert(response);
}
});
});
});
</script>
This is your same_file.php
<?php
//extract($_POST); code works even without this
if(isset($_POST["c"])) {
echo $_POST['c'];
}
?>
Not sure if your jquery library call is ok so I called the one on the web instead. Also your success:function() was not doing anything which is why you didn't receive anything.
Also always format your code with some indention so that it can be easier to read and comprehend by others.
You probably want to echo before the body is rendered.
But in true, unless you need to process the data the user sends, you don't need PHP at all.
And in truth, you probably don't need jQuery as well, fetch() works just fine.
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
<?php
if (isset($_POST["c"]))
{
// print/echo user data send from form.
echo $_POST["c"];
// stop the script from rendering the html below.
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<!-- add script element with js code here -->
</body>
</html>

How to refresh a div every X seconds which reads data from file?

I need to refresh a div every few seconds on my below index.php page.
<?php
session_start();
if (! check_write()) {
redirect('testlogin.php');
return;
}
if (file_exists('lmt.json')) {
$lmt = json_decode(file_get_contents("lmt.json"), true);
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Website Title</h1> Logout </div>
<div>
<p>Welcome back,
<?= $_SESSION['user_id'] ?>!</p>
</div>
<!-- How can I refresh below div every x seconds? -->
<div>
<?php if (isset($lmt)) { ?>
<p>Last modified by <?= $lmt['fname']; ?> at <?= $lmt['ts']; ?></p>
<?php } ?>
</div>
<form method="post">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" name="submit" value="Save Data"> </form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(function() {
$('form').submit(function(e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
response = JSON.parse(response);
if(response.message) {
alert(response.message);
}
});
});
});
</script>
</body>
</html>
Below is the div I want to refresh every X seconds. As of now it just gets the value from $lmt variable and show it to the user but I want to refresh that div every X seconds by reading from lmt.json file and then show fname and ts variable.
<!-- How can I refresh below div every x seconds? -->
<div>
<?php if (isset($lmt)) { ?>
<p>Last modified by <?= $lmt['fname']; ?> at <?= $lmt['ts']; ?></p>
<?php } ?>
</div>
How can I do this efficiently?
Write two seperate files index.php (It contains the div that you want to refresh) and filehandle.php(file contents that you should recieve).
index.php
<?php
session_start();
if (! check_write()) {
redirect('testlogin.php');
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Website Title</h1> Logout </div>
<div>
<p>Welcome back,
<?= $_SESSION['user_id'] ?>!</p>
</div>
<!-- How can I refresh below div every x seconds? -->
<div class="update_content"></div>
<form method="post">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" name="submit" value="Save Data"> </form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
var update_time = 1000;
$.get('filehandle.php', function (data, status){
$('.update_content').html(data);
});
setInterval(function(){
$.get('filehandle.php', function (data, status){
$('.update_content').html(data);
});
}, update_time);
$(function() {
$('form').submit(function(e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
response = JSON.parse(response);
if(response.message) {
alert(response.message);
}
});
});
});
</script>
</body>
</html>
filehandle.php
<?php
if (file_exists('lmt.json')) {
$lmt = json_decode(file_get_contents("lmt.json"), true);
}
if (isset($lmt)) {
echo "<p>Last modified by ".$lmt['fname']." at ".$lmt['ts']."</p>";
}
?>
change the value of update_time value in index.php to your desired value (it refers to update every update_time seconds).
Note: update_time = 1000 -> 1sec, 2000 -> 2sec, ...
If you're just looking for a quick way to get this done and over with I would implore you to check on w3schools.com. Here's an interesting look into what you might want from your site. It's an insight on the setTimeout() and setInterval() function from vanilla JS. Happy coding!
JS Timing

Sending data using Ajax to PHP

I am trying to send a string via ajax using the GET method but whenever that string contains some punctuation characters those characters do not appear when I use the echo in php.
For example if I send a string "sub + 12" the php will echo "sub 12"
If I send "&()*", php will echo an empty string.
Why does this happen?
Are there any special characters that the string cannot contain?
you encodeURIComponent(). this is demo code which you can check
something like this encodeURIComponent(yourtext)
first this html code . in text filed enter your text and check this output, this is onkeyup so enter text and check result
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search demo</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input").keyup(function () {
$('#results').html('');
var searchString = $("#search_box").val();
var data = 'search_text=' + encodeURIComponent(searchString);
if (searchString) {
$.ajax({
type: "GET",
url: 'edit.php',
data: data,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#results').html(result);
//window.location.reload();
}
});
}
});
});
</script>
</head>
<body>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button"/><br/>
</form>
</div>
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
</body>
</html>
then create edit.php file
<?php
$searchquery = $_GET['search_text'];
echo $searchquery;
?>
then check result . which is working
Output is
Search results :
&()*
Use encodeURI() before sending the request.

PHP Header redirect issue

I have this code that works well and can actually insert data. My problem is in the redirecting back to the page I was from. I have an index.html and add_cars.php
The index.html is like so:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('#search').keyup(function(){
var search = $('#search').val();
$.ajax({
url:'search.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$('#result').html(data);
}
}
});
}); // Search function end
$("#add-car-form").submit(function(evt){
evt.preventDefault();
var postData = $(this).serialize();
var url = $(this).attr('action');
$.post(url, postData, function(php_table_data){
$("#car-result").html(php_table_data);
});
}); // add car function end
}); // Document ready function end
</script>
<div id="container" class='col-xs-6 col-xs-offset-3'>
<div class="row">
<h2 >Search the Database</h2>
<input type="text" name="" class='form-control' name='search' id='search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="bg-success" id="result">
</h2>
</div>
<div class="row">
<form id="add-car-form" class="col-xs-6" action="add_cars.php" method="post">
<div class="form-group">
<input type="text" name="car_name" placeholder="Car name" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Car" name="">
</div>
</form>
<div class="col-xs-6">
<div id="car-result">Sometkasdf</div>
</div>
</div>
</div>
</body>
</html>
and my add_cars.php is like so:
<?php
include("db.php");
if(isset($_POST['car_name'])){
$car_name = $_POST['car_name'];
$query = "INSERT INTO cars(car) VALUES ('$car_name')";
$query_car_name = mysqli_query($connection, $query);
if(!$query_car_name){
die("QUERY FAILED");
}
header("Location: index.html");
exit;
}
?>
When I redirect back to my index.html, I am getting two forms. It's like the first form is copied at the end of it. To be exact, the first form is copied to the #car-result div. What should happen is; it should go back to my index.html and the input box should only have the placeholder value. What am I doing wrong here or what should I do? All help is appreciated.

AJAX PHP LOGIN Page is not redirecting correctly

Basically I've got a AJAX Login page that is working and everything but when I successfully login I want it to redirect to a page without it reloading I'm not sure how its done as I am very new to langauge. Many thanks
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<title>Popup Login</title>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='1')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else
{
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){
?>
<a href='logout.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<div class="err" id="add_err"></div>
<form action="login.php">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
$mysqli=mysqli_connect('');
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row >=1 ) {
echo '1';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>
When I successfully login I want it to redirect to a page without it reloading
As long as the page to be redirected to is on the same domain, or you can set CORS headers properly, and you can deal with relative links, then in your success callback you can replace the entire page's HTML with that of the new page.
You can start another ajax call for your new page, and use document.write() to obliterate the existing HTML like so:
...
success: function(html){
if(html=='1') {
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut(400, function(){
// Completely replace the page's HTML
$.ajax({
type: 'GET',
url: 'http://example.com/logged-in',
async: false, // You want this synchronous
success: function(data) {
// This code block replaces your current page seamlessly
document.open();
document.write(data);
document.close();
},
error: function(e){
alert(e.message);
}
});
});
}
...
Here is a demo:
$("#bye").fadeOut(1400, function(){
$.ajax({
type: 'GET',
url: 'http://enable-cors.org/',
async: false,
success: function(data) {
// This is a quick-n-dirty hack
// to get the relative links working for the demo
var base_href = '<base href="http://enable-cors.org/">';
document.open();
document.write(base_href + data);
document.close();
},
error: function(e){
alert(e.message);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="bye"><h1>Logged in Successfully</h1></div>

Categories

Resources