why it says that my var is undefined - javascript

I can't understand why this doesn't work: it should take the text of ("#name") and write in another html page that I open on click on the button, but when I open the other page it says that the "username" is undefined, how can I pass the value of that?
username = [];
$("#main_page").ready(function() {
$("#name").focus();
$("#name").keydown(function(e) {
if (e.which === 13) {
console.log("ok");
$('#login').click();
}
});
$("#login").click(function() {
username[0] = $("#name").val();
console.log(username);
window.location.replace("chat");
});
});
$("#chat").ready(function(){
console.log(username[0] + " recived");
$("#username_title").append(username[0]);
});
Is it wrong to use $('#chat').ready? Because it runs the code filled in it in the main_page too.
In the two file html i gave an id to the body for use .ready, but I think it's wrong

You could put "username" in a cookie, and get "username" from the cookie in the next page "chat". You also could use localStorage or sessionStorage instead of cookie.

Its all about page load and page unload
the scope of a variable is just inside these events means that no jq js or any web code(client side) will work before or after that
Means you cant write a code and expect it to work even after page reload its a whole new start then although you can pass the username as a querystring and fetch it after page is reloaded

Related

Script to automate the passing credentials to next page

I have one URL which asks me to " click here to login" then the next page loads.
once the next page loads I need to pass the credential. tried below script but didn't work
document.getElementsByClassName('click_hereTo_login')[0].click();
$( document ).ready(function()
{ if document.location.href=="https://example.com/secondpage"
then {
document.getElementById('id').value="12322";
document.getElementById('password').value="4444";
document.getElementsByClassName('login')[0].click();
}})
First of all your if is not written correctly. It should be:
if (document.location.href=="https://example.com/secondpage"){
document.getElementById('id').value="12322";
document.getElementById('password').value="4444";
document.getElementsByClassName('login')[0].click();
}
The another problem here is, that your script runs from scratch on both pages. If you want to pass data from page to page without backend, you can use either query string or localstorage to store the data somewhere and then access it from another page.
let id = localStorage.getItem('id');
// get the input element
let idInput = document.getElementById('id');
// check if we are one second page
if(idInput) {
document.getElementById('id').value = id;
}
// Save id on login click
document.querySelector('.login').addEventListener('click', () => {
localStorage.setItem('id', 1234);
});

document.getElementById(..) gives null even though element is present

I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
e.preventDefault();
var search=document.getElementsByClassName("search")[0].value;
$.ajax
({
type: 'POST',
url: 'usernamesearch.php',
data:
{
search:search
},
success: function (response)
{
window.location.href="usernameSearchResults.php";
response = JSON.parse(response);
var array_length = Object.keys(response).length;//getting array length
for(var i=0;i<array_length;i++){
if(i==0){
document.getElementById("searchResults").innerHTML=""+response[0].username+"<br>";//i=0
}else{
document.getElementById("searchResults").innerHTML+=""+response[i].username+"<br>";
}
}
window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
})
});
This is usernameSearchResults.php(inside tags):
<h1>Username Search Results</h1>
<p id="searchResults"></p>
But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?
I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As #Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.
I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
//execute code here
});
Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page

Page redirect in jQuery fails randomly. Race condition?

Elaborating on an example from the very good post by Felix Kling I wrote some jQuery code to authenticate a user. If the authentication is successful the window.location object should be assigned/replaced to a new URL.
The redirection occasionally fails, even though the user is authenticated correctly: based on the values of sessionStorage('Auth') the looks of the menus for an authenticated user are modified by some other JS code, so I know when the credentials were entered correctly.
Here is my code.
$(document).ready(function() {
$('#submit').click(function() {
var webServiceHref = window.location.href;
var webServicePath = webServiceHref.slice(0,webServiceHref.lastIndexOf("/"));
var serviceUrl = webServicePath + "/login.php";
$.post(serviceUrl,
{
Email: $("#Email").val(),
Password: $("#Password").val()
}).done(function(data, status) {
var json = JSON.parse(data);
if (json.valid == true){
sessionStorage.setItem('Auth', true);
sessionStorage.setItem('FirstName', json.FirstName);
sessionStorage.setItem('Email', json.Email);
$("#messageLine").val("Authentication succeded");
$(location).attr('href', webServicePath + "/welcome.html");
// window.location.href = webServicePath + "/welcome.html";
} else {
sessionStorage.clear();
$("#messageLine").val("Incorrect Username or Password");
}
});
}); // click
}); // ready
This behavior does not depend from the way the redirection is called:
I left in my code, commented out, some of the JS and jQuery
combinations of methods (window.location.assign, window.location.replace etc.) suggested in numerous posts on SO.
I have even tried .reload() without success.
In Chrome inspector I can even see the callback statements being executed, the assignment of the new URL being made, but when the function returns the window object sometimes does not change, and sometimes ... it does.
Perhaps the assignment of the URL is queued after other event which causes the original login.html page to be reloaded?
What am I missing? Am I using the deferred object incorrectly?
Thank you in advance for your help.
If your "#submit" element is actually submitting a form (e.g. it is an input of type "submit" within a form), that could cancel the page redirection. E.g. when no action is specified on the form, it just reloads the same page, preventing your modification of window.location.href from having any effect.
See also that post: javascript redirect not working anyway
You have 3 easy possible solutions:
Turn your element/button into a normal one (not a submit).
Prevent the element/button from submitting the form (function (event) { event.preventDefault(); /* rest of your code */}).
Attach your main callback on the form submit event. The user is then able to trigger the action by hitting "Enter", not just by clicking on the submit button.

How do I refresh a value in php from javascript?

I have a form that I'm submitting using javascript. However, one of the checks it does uses a php script that queries an API and gets a user's password. This is for the purposes of form validation (i.e. if password doesn't match what we have on file..)
I'm using a php script to decode the password like this
function submitForm() {
var options = {
decoded_password: '<?php echo abc_decode($contactInfo['Password'])?>',
}
if (jQuery('#current_password').val() != options.decoded_password && $psc('#current_password').val()) {
render_alert('Your current password does not match what we have on file.');
return false;
} else {
$psc('#account-information').submit();
document.getElementById("account-information").reset();
}
Page loads, great, submit form, great. However, the variable is remembered from the first page load, so if I try to change the password again, it says my password doesn't match what is on file. If I reload the page, no problem.
Is there any way to change the value of $contactInfo['Password'] in javascript without a page reload?
You could try making an AJAX call instead. This won't require a page reload, but will still give you the opportunity to send the data back to the server. If you store the data in the $_SESSION variable it will persist across multiple calls.

How to perform a javascript action right after redirect?

After a user creates an account on my website, I want to redirect the user to the home page and display a twitter style message bar on top. This is how I have it:
success: function (response) {
if (response.Success) {
location.href = response.ReturnUrl;
}
ShowMessageBar(response.Message);
},
The message bar does appear but it gets displayed only for a second as it gets canceled by the redirect. What can I do to display the message right after the redirect has completed? Is there a complete event for the location.href? Thanks.
You need to pass it through a cookie, the quesrystring, or localStorage.
Something like this using localStorage or cookies (localStorage is available in IE8+ and most other browsers):
on the current page:
if('localStorage' in window)
localStorage.setItem('message', response.Message);
else // use cookie
On the new page:
$(function(){
if('localStorage' in window && !!localStorage['message']) {
ShowMessageBar(localStorage['message']);
localStorage.removeItem('message');
}
else // use cookie
});
If you are uncomfortable with these techniques there are jquery plugins that wrap this functionality. I would recommend jstorage.
This will need the Cookie plugin for jQuery:
http://plugins.jquery.com/project/Cookie
Put this somewhere in the header of your homepage:
jQuery(function($){
if($.cookie("message")) {
ShowMessageBar($.cookie("message"));
$.cookie("message", "any_value", { expires: -1 });
});
And in your success function:
success: function (response) {
if (response.Success) {
$.cookie("message", response.Message);
location.href = response.ReturnUrl;
}
},
Once the url of a page changes all execution stops and is transferred to the new page. Pass a parameter to the new page that triggers the event you want instead.
Sounds to me like you would need to call ShowMessageBar() from the redirected URL.
You could send a parameter and check for its existence on document ready. Probably the easiest way of achieving the desired effect.
If you REALLY wanted to show the message, you could always throw it in an alert before you redirect them, which would halt execution until they clicked 'ok'.

Categories