refresh Page after logged in - ajax

in the index Page, the user needs to login..
after login,
<?php
include("dbinit.php");
$text="";
$eadd = $_POST['eadd'];
$pass = $_POST['pass'];
if (filter_var($eadd, FILTER_VALIDATE_EMAIL)) {
$result = mysqli_query($link,"SELECT * FROM account WHERE Eadd='".$eadd."'");
if (mysqli_num_rows($result)<=0){
$text = "<font color=red>Invalid Emailaddress and Password Combination!</font>";
}
else
{
while($row = mysqli_fetch_array($result)){
$passH = $row['Pass'];
$passS = $row['hash'];
}
if(md5($pass.$passS) == $passH){
$_SESSION['account'] = $eadd;
$text = "<font color=red>Login Successful!</font>";
}else{
$text = "<font color=red>Invalid Emailaddress and Password Combination!</font>";
}
}
mysqli_free_result($result);
} else {
$text = "<font color=red>Invalid Emailaddress!</font>";
}
mysqli_close($link);
echo $text;
?>
in the index Page,
function login(){
var eadd = $('#eadd').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url: "login.php",
data: {eadd:eadd, pass:pass}
}).done(function( result ) {
$("#loginMsg").html(result);
});
}
how can i redirect or refresh the Page after he logged in?
after loggedin, the index page must refresh..
do i need to Put window.history.pushState("", "", '/newpage');?
how to use it?

window.top.location.reload();
Use that in your ajax success callback
To redirect instead to a differnt page use:
window.top.location = '/some/page/withcats';
Use:
function login(){
var eadd = $('#eadd').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url: "login.php",
data: {eadd:eadd, pass:pass}
}).done(function( result ) {
$("#loginMsg").html(result);
//you may want to check result has no errors or something
window.top.location.reload();
});
}
Error handling:
You might want to check for an error, so that if the login is unsuccessful you do not want to refresh the page. To do that relies on knowing what you php function will return E.g.:
function login(){
var eadd = $('#eadd').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url: "login.php",
data: {eadd:eadd, pass:pass}
}).done(function( result ) {
//this will make sure the page only refreshes if login is succesful, if not display error
if(result === "<font color=red>Login Successful!</font>"){
window.top.location.reload();
}else{
$("#loginMsg").html(result);
}
});
}

how can i redirect or refresh the Page after he logged in?
by using a regular form submission instead of Ajax.

Related

Wordpress Ajax call returns empty

I have a trouble with wordpress ajax call.
Action for admin-ajax.php has been defined correctly.
It returns correct result when user logged in, but it returns empty when user didn't log in.
Here is code for it.
add_action('wp_ajax_thwepo_calculate_extra_cost', array($this, 'wp_ajax_action_calculate_extra_cost_handler'), 10);
add_action('wp_ajax_nopriv_thwepo_calculate_extra_cost', array($this, 'wp_ajax_action_calculate_extra_cost_handler'), 10);
public function wp_ajax_action_calculate_extra_cost_handler() {
$return = array(
'code' => 'E001',
'message' => ''
);
echo json_encode($return);
exit;
}
And here is javascript code.
var data = {
action: "thwepo_calculate_extra_cost",
price_info: JSON.stringify(requestData)
};
currRequest = $.ajax({
type: "POST",
url: args.ajax_url,
data: data,
beforeSend: function() {
null != currRequest && currRequest.abort()
},
success: function(rslt) {
if ("E000" === rslt.code) {
var result = rslt.result;
result && display_new_price(args, result.display_price, isVariableProduct)
} else "E002" === rslt.code && display_new_price(args, rslt.result, isVariableProduct)
},
error: function(data) {
console.log(data);
}
});
Here is screenshot of ajax call.
It returns correct result when page loaded first time.
But when select option (i.e. Classes), it returns empty.
Why is this happened?
Is there anyone who have any idea?
Please let me know if needed any other information.
Page url is https://www.ivybound.net/classes/isee-prep-middle-level/
It can be checked by selecting "What do you need?" select option.

Call a prestashop module with ajax

I have a PrestaShop module called 'MyMenu' and I want call this menu with an AJAX call.
My module is displayed in the hookFooter() method:
public function hookFooter()
{
$display = $this->display(__FILE__, 'megamenu.tpl', $smartyCacheId);
Tools::restoreCacheSettings();
return $display;
}
I want display with this script:
<div class="load_menu"></div>
<script>
$(document).ready(function (e) {
$.ajax({
method: "POST",
url: "../modules/MyMenu.php",
data: {},
success: function (data) {
$('.load_menu').html(data);
}
})
});
</script>
The best way is to do it via a front controller linked to your module.
You can call the url like this :
$link->getModuleLink('modulename','controller', $parameters);
// Parameters is an optionnal array, it can be empty
And for the controller, place a file like this ./modules/modulename/controllers/front/ajax.php with this kind of content :
class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$response = array('status' => false);
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
$module = new ModuleName;
if (Tools::isSubmit('action')) {
$context = Context::getContext();
$cart = $context->cart;
switch (Tools::getValue('action')) {
case 'actionname':
$response = array('status' => true);
break;
default:
break;
}
}
// Classic json response
$json = Tools::jsonEncode($response);
$this->ajaxDie($json);
// For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
// $this->context->smarty->assign(array('var1'=>'value1'));
// $this->setTemplate('template.tpl');
// For sending a template in ajax use this method
// $this->context->smarty->fetch('template.tpl');
}
}
If you don't want to pass the url by the module, the js snippet should be like this.
$(document).ready(function(){
$.ajax({
type: "POST",
headers: { "cache-control": "no-cache" },
url : baseDir + 'modules/yourmodulename/yourfile.php',
data: {
token : token
},
success : function(data){
$('.load-menu').html(data)
}
});
});
Where yourmodulename is the name of your module and yourfile.php is the code where you retrieve the menu.
Don't forget to add to your data the token, it's to prevent a CSFR attack, obviously you have to check the token in your server side script as well.
In a new file at the module root, you can create a file "ajax.php"
require_once(MODULE_DIR.'MyMenu/mymenu.php');
if(Tools::getValue('token') !=
$mymenu = Module::getInstanceByName('mymenu');
$menu = $mymenu->hookFooter();
die($menu);
In your js, at the root of your module
<script>
$(document).ready(function (e) {
$.ajax({
method: "POST",
url: "./ajax.php",
data: {},
success: function (data) {
$('.load_menu').html(data);
}
})
});
</script>

How to get current window URI last segment

My current window URL http://192.168.20.2/vtp/attendance/rawAttendance and parameter form submit by this URL "<?php echo base_url(); ?>index.php/attendance/submitParam" in ajax. With this code below
$last = $this->uri->total_segments();
$data['lastSegment'] = $this->uri->segment($last);
I got the last URL segment but this not the current window URL segment, this is parameter form URL segment. How do I get my current window URL last segment in my submitParam controllerwhen I submit the parameter form.
submit param;
$("#submitparam").click(function (e) { // passing down the event
$.ajax({
url: "<?php echo base_url(); ?>index.php/attendance/submitParam",
type: "POST",
data: $("#param").serialize() + '&fromAjax=' + true,
success: function (data) {
$("#result").html(data);
},
error: function () {
alert("Fail")
}
});
e.preventDefault(); // could also use: return false;
});
controller:
public function submitParam() {
//post from view param
$round = $this->input->post('round', TRUE);
$batch = $this->input->post('batchid', TRUE);
$fromdate = $this->input->post('FromDate', TRUE);
$todate = $this->input->post('ToDate', TRUE);
//raw Attendance
$data['IDS'] = $this->AttendanceModel->raw_attendance_TID($batch);
$data['Dates'] = $this->AttendanceModel->raw_attendance_Data($batch,$fromdate,$todate);
//get Batch Attendance
$data['attendance'] = $this->AttendanceModel->get_attendance($batch,$fromdate,$todate);
//pass param to preview as attendance title
$data['batch']=$batch;
$data['fromDate']=$fromdate;
$data['toDate']=$todate;
//get url last segment
$last = $this->uri->total_segments();
$lastSegment = $this->uri->segment($last);
//load view by url last segment
if ($this->input->post("fromAjax")) {
$this->load->view('attendance/'.$lastSegment, $data );
}
}
Add a hidden field in your form with the name url_parameter. set the value of the last paramater which you want in your controller and get that field's value by post/get method.
Try this :
$record_num = end($this->uri->segment_array());

Ajax- doesn't show message of validation during registration

What I am trying to do is to show a validation message when username or email exists while trying to register. I have used json_encode which has a message and status. What is happening is that when I type an username and email that exists it doesn't do anything neither shows a message or register.
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST["password"] !== $_POST["confirmation"])
{
echo json_encode(array('msg'=>"password and confirmation aren't equal.", 'url'=>"", 'status'=>false));
}
else if(($data['username']=== $_POST['username'] )|| ($data['email'] === $_POST['email'] ))
{
echo json_encode(array('msg'=>"Username or email exists.", 'url'=>"", 'status'=>false));
}
else
{
$result = query("INSERT INTO users (username, hash, email) VALUES (?,?,?)", $_POST["username"], crypt($_POST["password"]), $_POST["email"]);
$rows = query("SELECT LAST_INSERT_ID() AS id");
$id = $rows[0]["id"];
$_SESSION["id"] = $id;
echo json_encode(array('msg'=>"Success.", 'url'=>"/kinema/html/index.php", 'status'=>true));
}
}
scripts.js
$('#register_form').on('submit', function(e) {
e.preventDefault();
var name = $('#register_form input[name=username]').val();
var email = $('#register_form input[name=email]').val();
$.ajax({
url: "register.php",
type: "POST",
data: {
username: name,
email: email
},
dataType: 'json',
success: function(response) {
if(response.status){
console.log(response);
window.location = response.url;
}
else
{
$('#invalid_register').html(response.msg);
}
}
});
});
You are not posting a password or confirmation value this wil throw an undefined index error.
And for what I can tell the $data array does not exist or the code you posted is incomplete.

Ajax simple login

I have this simple Ajax code, my question is only, what does data.logged return, and what i need to have in the logged.php file...
I'm new to ajax, sorry for the dumb question...
$.ajax('logged.php', {
data: {
login: login,
pass: pass
},
success: function(data)
{
if (data.logged)
{
setTimeout(function() {
document.location.href = 'index.php'
}, 2000);
}
else
{
setTimeout(function() {
formLogin.clearMessages();
displayError('Utilizador ou password errados');
}, 2000);
}
},
error: function()
{
formLogin.clearMessages();
displayError('Error while contacting server, please try again');
}
});
On the client side, adding dataType : 'json' worked for me.
$.ajax('handler.php', {
data: {
login: login,
pass: pass
},
dataType : 'json',
success: function(data)
{
//code here
}
//more code here
}
And then on the server side:
$user = $_GET['login'];
$pass = $_GET['pass'];
$result = array();
if( /* login logic here */) {
$result['logged'] = 'true';
} else {
$result['logged'] = false;
}
header('Content-type: application/json');
echo json_encode($result);
That's a jQuery AJAX request which will be expecting responseText in JSON format. In this case, it seems like the JSON returned by your PHP file only needs to have a single property logged which will be either true or false depending on whether or not the login was successful.

Resources