How do I refresh the page after ajax call success. The page doesn't refresh even thought I have put window.location.reload(true). It only displays the echo message but doesn't refresh it
$("#update-btn").click(function() {
var token = document.getElementById('tokenAmount').value;; //Place the token here
var master = currentUserID;
var lastUser = lastNode.info.id;
$.ajax({
type : "POST",
url : "update.php",
data : {'master': master,
'token' : token,
'user_id': lastUser
},
success : function(data) {
alert(data);
window.location.reload(true);
}
});
});
update.php
$master=$_POST['master'];
$user = $_POST['user_id'];
$token = $_POST['token'];
if(condition)
{
$result = $MySQLi_CON->query($secondToken);
if($result == false)
$response['msg'] = "Not Enough";
else
{
$response['msg'] = "Successful";
}
}
else
{
$response['msg'] = "Not enough";
}
echo json_encode($response['msg']);
Please try below code :-
location.reload();
Edited :-
success : function(data) {
alert(data);
location.reload();
}
Other ways :-
location.reload()
history.go(0)
location.href = location.href
location.href = location.pathname
location.replace(location.pathname)
location.reload(false)
Please have a look on below link :- There are 534 other ways to reload the page with JavaScript :-
http://www.phpied.com/files/location-location/location-location.html
.ajaxStop() callback executes when all AJAX call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
The source is from here
The next statement wont execute unless you click Ok on alert().
So use console.log(data) instead.
success : function(data) {
console.log(data);
window.location.href=window.location.href;
}
Try this:
location.reload(true);
In your ajax success callback do this:
success: function(response){
setTimeout(function(){
location.reload()
}, 5000);
}
As you want to reload the page after 5 seconds, then you need to have
a timeout as suggested in the answer.
Related
I want to know that how to redirect url after login successful via Ajax call in php? Kindly check my code what I am doing wrong.
Below is the registration.php file on url http://localhost:8080//myproject/adminseller/registration.php:
<script>
function createLogin () {
//alert("Hello! I am an alert box!!");
var data = {
'email' : jQuery('#email').val(),
'password' : jQuery('#password').val(),
}; // data obect End
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/login.php',
method : 'POST',
data : data,
success : function(data){
//alert(data); // For checking Code in alert
if (data != 'passed') { // passed is else statement in
check_address.php when no errors are showing
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//alert('passed!');
//clear the errors if any
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Below is the Login.php File
<?php
if (isset($_POST['email'])) {
$email = sanitize($_POST['email']);
}
if (isset($_POST['password'])) {
$password = sanitize($_POST['password']);
}
// echo $email; // Output x2a0889#gmail.com
// echo $password; // 123456
// Email and password matched and no erros so I am removing validations code from here, So else condition will execute here
// Check for Errors
if (!empty($errors)) {
echo display_errors($errors);
}else{
// Assume here login is successful
echo 'passed';
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is: http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
}
?>
My problem is that after successful login the url is not changing it still
http://localhost:8080//myproject/adminseller/registration.php
And I want to redirect my page http://localhost:8080//myproject/adminseller/index.php
After successful login.
Any idea or suggestion would be welcome.
You need to use window.location.href not location.reload();
<script>
function createLogin () {
//alert("Hello! I am an alert box!!");
var data = {
'email' : jQuery('#email').val(),
'password' : jQuery('#password').val(),
}; // data obect End
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/login.php',
method : 'POST',
data : data,
success : function(data){
//alert(data); // For checking Code in alert
if (data != 'passed') { // passed is else statement in
check_address.php when no errors are showing
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//alert('passed!');
//clear the errors if any
jQuery('#modal_errors_1').html("");
window.location.href = "http://localhost:8080//myproject/adminseller/index.php";
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Below is the Login.php File
<?php
if (isset($_POST['email'])) {
$email = sanitize($_POST['email']);
}
if (isset($_POST['password'])) {
$password = sanitize($_POST['password']);
}
// echo $email; // Output x2a0889#gmail.com
// echo $password; // 123456
// Email and password matched and no erros so I am removing validations code from here, So else condition will execute here
// Check for Errors
if (!empty($errors)) {
echo display_errors($errors);
}else{
// Assume here login is successful
echo 'passed';
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is: http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
}
?>
You are currently redirecting the AJAX request.
You cannot redirect from the PHP side on a successful AJAX request.
You can catch the returned value from Javascript however and redirect from there.
Rather than calling the header location within your PHP script, put this within the if statement checking if the response was passd
window.location.href = 'index.php';
This will cause the browser to go to index.php.
You are redirecting in Ajax call, which should not be the case. Please remove this line from PHP code:
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is:
http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
And then replace your following JS code:n.
//clear the errors if any jQuery('#modal_errors_1').html("");
location.reload();
With Following code:
//clear the errors if any jQuery('#modal_errors_1').html("");
window.location.href = 'index.php';
I have a PHP project that I'm using AJAX in to refresh a part of the page, part of that page grabs options from the URL on what it's going to show. On load and refresh this works perfectly. When AJAX is introduced to reload the php file inside of the div, the only part that doesn't work is the $_GET.
I really don't know anything about AJAX and am trying to learn, but can not figure this out for the life of me. And Google searches haven't lead me in the right direction.
AJAX:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
$('#footer-holder').html( data );
$('#authCheck').load('authentication.php');
},
error : function(){
alert('Something wrong');
}
});
return false;
});
});
authentication.php has some $_GET commands, the page executes perfectly on refresh and everything else executes perfectly with this AJAX call except the $_GET requests.
Sample authentication.php
if(isset($_GET['test'])){
echo $_GET['test'];
}else{
echo "nothing in GET";
}
Sample index.php
echo "<div id='authCheck'>";
include 'authentication.php';
echo "</div>";
If I could understand your question then , you are trying to authenticate user. Using GET method for login is never ever a good way of doing it, even if you are using ajax,
This may help you
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : '/authentication.php',
type : 'POST',
data : $(this).serialize(),
success : function( data ) {
if(data == 'success')
//Successfully authenticated
} else {
console.log('Invalid Credentials')
}
},
error : function(){
alert('Something wrong');
}
});
return false;
});
});
in PHP
//Check username and password, Checking isset POST is not enough for security
if($_POST['username'] != '' && $POST['password'] != ''){
//Do you logic to check password id correct or not
//if true
//echo success
//else
//echo 'fail'
}else{
echo "Invalid credentials";
}
hope this will help you
I built a vote system with ajax and php, and I send data to php page for saved data in db.
I tried to send data with ajax post and php.
My problem is the data is not send to the page.
My js code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
url: 'vote.php',
type: 'POST',
cache: 'false'
});
$('.vote').click(function(){
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var imgid = <?=$array['id'];?>;
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('#image-like').addClass('disabled_up');
$.ajax({data: {'imgid' : imgid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('#image-dislike').addClass('disabled_down');
$.ajax({data: {'imgid' : imgid, 'action' : 'down'}});
};
parent.addClass('.disabled');
};
});
});
</script>
and my html code:
Use post method. This is not the correct code, but it's an idea, always works for me.
$('.vote').click(function(){
//Your vars
var data='voteup';
//Your actions... ddClass/removeClass...
$.post('vote.php',data,function(data){
//On your vote.php use "if($data=='voteup') else ;"
//And show message here...
alert(data);
});
return false;
});
example of vote.php
<?php
$data=$_POST['data'];
if($data=='voteup')
echo "You voted up!";
else echo "You voted down!";
?>
It's just an idea (:
You can try changing this:
if (!parent.hasClass('.disabled')) {
to this:
if (!parent.hasClass('disabled')) {
Some Notes:
From the docs:
For $.ajaxSetup()
Description: Set default values for future Ajax requests. Its use is not recommended.
Try using .post() function, you can set a callback when your action is done
jQuery.post(URL_TO_REACH, {ID_VALUE1 : 'my value' , ID_VALUE2 : 'my second value' })
.done(function( data_ajax ) { // data_ajax : Your return value from your php script
alert( data_ajax );
})
});
Hope this will help you
Official documentation : http://api.jquery.com/jQuery.post/
Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?
Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);
Is there any way to implement a callback for a page refresh function, check if the page is ready after it is refreshed and then print a message? I'd like to show refresh the page and show a certain message after clicking a button, however, I need to stay within my code in order to know what message to show. Anything similar to the next code would be great:
location.reload(function(){
alert ('done refreshing and document is ready');
});
On page reload, your JS application gets re-initialized and starts all over again, so you cannot have a callback.
However, what you can do is add a hash fragment to the URL before reloading.
window.location = window.location.href + "#refresh";
window.location.reload();
Then, on page load, check if the hash fragment exists. If it does, you'll know you just refreshed the page.
If you want to user window.location.reload() you have to use Browser's sessionStorage. Here is my code, I use this for saving data.
window.onload = function () {
var msg = sessionStorage.getItem("nameShah");
if (msg == "Success") {
sessionStorage.setItem("nameShah", "");
alert("Saved Successfully");
}
}
$("#save").click(function () {
$.ajax({
url: "/AspNetUsers/SaveData",
type: "POST",
async: true,
data:{userName: "a"},
success: function (data) {
if (data.Msg == "Success") {
sessionStorage.setItem("nameShah", "Success");
window.location.reload();
}
}
});
});
Server Side:
public ActionResult SaveData(string userName)
{
return Json(new { Msg = "Success" }, JsonRequestBehavior.AllowGet);
}
The way to go is using
$(document).ready(function(){
alert('done refreshing and document is ready');
});
But it doesn't differentiate a first load from a refresh. But you could achive that using sessions. For example, using PHP:
<?php
session_start();
$showJs = false;
if( !isset($_SESSION['loaded_before']) ) {
$showJs = true;
$_SESSION['loaded_before'] = true;
}
?>
...
<?php if($showjs) { ?>
<script type="text/javascript">
$(document).ready(function(){
alert('done refreshing and document is ready');
});
</script>
<?php } ?>
If you really want to go javascript side, you can use sessionStorage.varName before reloading, and then you check that var and continue.