PHP session lost after redirecting with Javascript? - javascript

So I am grabbing data through AJAX in order to redirect the user to a page , but the PHP session data gets lost after being redirected to the page ... Below is my code , can anyone tell me what might be causing that ... I'm copying the relevant code below
$("#activation").click(function(event){
event.preventDefault();
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var customer_phone = $("#customer_phone").val();
var pin = $("#pin").val();
var carrier_id = $("#selCarrier option:selected").val();
var phone_number = ValidateMobNumber('customer_phone');
$.ajax({
url:"add_customer.php",
data:{first_name:first_name,last_name:last_name,pin:pin,carrier_id:carrier_id,customer_phone:customer_phone},
type:"POST",
success:function(result){
var customer_id = result;
var url ="http://www.example.com/store/activation.php?id="+customer_id;
if(customer_id !=""){
window.location.href = url;
return false;
}
else {
alert("Please enter a first name , last name and pin for activation");
}
}
});
});

I was having the same problem, but changing the absolute path to a relative one fixed it for me.
I changed this
window.location.replace('http://www.example.com/folder/subfolder/subfolder/file.php');
To this
window.location.replace('../../folder/subfolder/subfolder/file.php');
Hope it helps.

Related

create a session using php and ajax

I am beginner in web development so please understand me. I am trying to create a session using php file and call it in javascript using ajax request. but after I input the path of the index.html in address bar, it always shows the index. I want to know how can i possibly do this with javascript and php. restricting the all the pages of the site if there is no user active.
for example logic:
if (userhasValue == true) {
//redirect to index and can access the whole website
} else {
// redirect to login page
}
I have tried the code below but it still redirecting to index.html even if the data recieve in ajax request is empty.
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$temparray = array();
$ses_sql = mysqli_query($db,"select user_id,username,fullname from user where username = '$user_check'");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
if ($row > 0 ){
array_push($temparray, $row); //save your data into array
echo json_encode($temparray);
} else {
echo 'Error';
}
?>
function getUser(){
var user ='';
var fullname ='';
var id ='';
var tempArray = '';
var name = '';
$.ajax({
type:'POST',
url:'../bench/php/session.php',
data:'',
success:function(msg){
alert(JSON.stringify(msg));
let tempArray = JSON.parse(msg)
user = JSON.stringify(tempArray[0]['username']);
fullname = JSON.stringify(tempArray[0]['fullname']);
id = JSON.stringify(tempArray[0]['id']);
document.getElementById('fullname').innerHTML = fullname;
if (msg == 'Error') {
window.location.href = "../pages-login.html";
}
}, error: function(e){
console.log(e);
}, complete: function(c){
console.log(c);
}
});
}
The code above does not restrict the accessibility of the index.html and other pages if the user is not logged in.
I want to restrict the index page and other pages if the user try to redirect to index page without logging in.
Please help me. Any help will much be appreciated! Thanks in advance

UPDATED: redirect url pass parameter from another page

I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'

Parsing URL in Javascript

I have 2 URL like this:
http://localhost/gtwhero/public/users/3/subscribers-lists/1/subscribers
http://localhost/gtwhero/public/users/3/subscribers-lists/
So, URL format is like it:
{baseURL} +"users/{user_id}/subscribers-lists/"+{id}+"/subscribers"
Or-
{baseURL} +"users/{user_id}/subscribers-lists/"
and when I run this JS in this 2 pages, because 1page code is included in other page:
var baseURL = "http://localhost/gtwhero/public/";
$('#subscribers_list tbody').on( 'click', 'button.details', function () //Handeling Edit Button Click
{
var data = dataTable.row( $(this).parents('tr') ).data();
//alert(data['id']); //id = index of ID sent from server
window.location = window.location.href +'/'+data['id']+'/subscribers';
});
So, it is working for the second URL, but bot working for the first URL.
So, I am getting:
{baseURL} +"users/{user_id}/subscribers-lists/"+{id}+"/subscribers"
for the second URL, but getting error like this:
{baseURL} +"users/{user_id}/subscribers-lists/"+{id}+"/subscribers"+{id}+"/subscribers"
for the first URL.
Is there any solution?
I have done it-
var url = window.location.href;
var userId = (url.match(/\/users\/(\d+)\//) || [])[1];
var subscribers_lists_Id = (url.match(/\/subscribers-lists\/(\d+)\//) || [])[1];

How can I change a form submit action from displaying an alert popup to redirecting to a new page?

I'm trying to troubleshoot something someone else created (never a fun prospect) and want to eliminate an alert popup and have the user redirected to another page after form submission ... I've searched the web and found a couple of possible alternatives, but I also don't want to blow up the page, as I'm not all that experienced in PHP troubleshooting ... this is, I'm guessing, a painfully simple 101-level question, but many thanks in advance ... here's the relevant code:
jQuery("form#commentform input#submit").click(function(event) {
event.preventDefault();
var name = jQuery("form#commentform input#author").val();
if(name=="") {
alert("Name cannot be empty!");
jQuery("form#commentform input#author").focus();
return false;
}
var email = jQuery("form#commentform input#email").val();
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var email_test= pattern.test(email);
if (email == "" || email_test == false) {
alert('Valid email address is required!');
jQuery("form#commentform input#email").focus();
return false;
}
var phone = jQuery("form#commentform input#url").val();
var comment = jQuery("form#commentform textarea#comment").val();
jQuery.get('http://theenergyclub.com/wp-content/themes/EnergyClub/formPost.php', {type:'guestpass', name:name, email:email, phone:phone, comment:comment, rnDnum:Math.random()}, function(data) {
alert('We have received your request. Thank you!');
You can try to replace the last line
alert('We have received your request. Thank you!');
with
window.location = "http://example.com/"
You should be able to just change alert('We have received your request. Thank you!'); to window.location = '<URL>'; where <URL> is the URL you want to re-direct the user to.

javascript - redirecting

I can get the code to pop-up both alert but redirecting is not working. After adding an item it should redirect.
<script type="text/javascript" src="/_layouts/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Where to go when cancel is clicked
goToWhenCanceled = '/test/English/YouCanceled.aspx';
// Edit the redirect on the cancel-button's
$('.ms-ButtonHeightWidth[id$="GoBack"]').each(function(){
$(this).click(function(){
STSNavigate(goToWhenCanceled);
})
});
// Edit the form-action attribute to add the source=yourCustomRedirectPage
function setOnSubmitRedir(redirURL){
var action = $("#aspnetForm").attr('action');
var end = action.indexOf('&');
if(action.indexOf('&')<0){
newAction = action + "?Source=" + redirURL;
}else{
newAction = action.substring(0,end) + "&Source=" + redirURL;
}
$("#aspnetForm").attr('action',newAction);
alert(redirURL);
}
/*
// Use this for adding a "static" redirect when the user submits the form
$(document).ready(function(){
var goToWhenSubmitted = '/test/English/ThankYou.aspx';
setOnSubmitRedir(goToWhenSubmitted);
});
*/
// Use this function to add a dynamic URL for the OnSubmit-redirect. This function is automatically executed before save item.
function PreSaveAction(){
// Pass a dynamic redirect URL to the function by setting it here,
// for example based on certain selections made in the form fields like this:
var dynamicRedirect = '/surveys/Pages/ThankYou.aspx';
// Call the function and set the redirect URL in the form-action attribute
setOnSubmitRedir(dynamicRedirect);
alert(dynamicRedirect);
// This function must return true for the save item to happen
return true;
}
function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>
If you set window.location.href = 'SomeUrl' at any point, it should redirect right then. Looking at your code, I dont see that anywhere.
At what point are you trying to redirect?

Categories

Resources