resubmitting form not working after reload - javascript

In this simple app the unauthenticated user searches for restaurants with the city name,
and when the user chooses a restaurant, he can click on going but he needs to login with twitter first,
now when the user is back after authentication I want to resubmit the term the user inserted so he won't have to search again.
this is what I tried
form.addEventListener('submit', (e) => {
e.preventDefault();
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200) {
//format the data for the user interface
const businesses = JSON.parse(xhttp.responseText);
formatData(businesses);
}
}
xhttp.open("post", "http://localhost:3000/api/", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(`location=${input.value}`);
//save searched term in a session
sessionStorage.setItem('autosave', input.value);
sessionStorage.setItem('refreshed', false);
});
//
//if the term is saved and the page is refreshed
//(will happen only when page is refreshed)
if (sessionStorage.getItem("autosave") && sessionStorage.getItem("false") == 'false') {
//restore the contents of the text field
input.value = sessionStorage.getItem("autosave");
//then submit
document.forms["myForm"].submit();
}else{
console.log('no item')
};
This works but the problem is when the form is submitted automatically it redirects again to "http://localhost:3000/?location=new+york"
which results in data not displaying.
I don't know how to stop it from doing that.

I think (I'm not an expert with xhr) if you don't specify
window.location //or
window.redirect
Your browser "reload" the last URL you have. When you submit automatically, try to add a redirection to your desired link.

Related

Trouble with PHP form and Ajax

I’m trying to submit a form with data to a php file without reloading the page. I also have some js code that changes the form name and values when the next btn is clicked. I had 10 questions all on 1 page and I got it to work with PHP but now I’m trying to get 1 question per page. I looked in the network tab and it looks like the xhr requests are being sent but in my database.php file I wrote $user_anwser = $_POST[‘quiz_1’]; and var dumped it and I get a NULL value. Here is the ajax code.
form.addEventListener("submit", function(e){
if (ind < 10){
e.preventDefault();
} else {
form.setAttribute("action", "results.php");
}
let data = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', '../private/database.php');
xhr.onload = function() {
if (xhr.status === 200) {
// if the response is json encoded
let response = JSON.parse(xhr.responseText); // i get a parse error there
if (response.message == 'valid') {
// redirect here
}
}
// }
xhr.send(data);
}
});

Using Ajax to run a php script to change a session variable for a Login System

I am creating a website with a login system for a university assignment. the method to do this i have created is have a a php page (the main page) have a section on the top that checks for a session variable for the user:
<?php
// open the session
session_start();
header('Access-Control-Allow-Origin: *');
// check for existing user
if(isset($_SESSION['User'])){
$isUser = true;
$userName = $_SESSION['userName'];
}else{
$isUser = false;
}
?}
There is more to this but the rest is just functions that use the session to add appropriate fields (login section/logged in confirmation) this works fine.
In order to change the session variable a login confirmation function is used (very long script to check against database, also works perfectly) and at the end of the login check if correct changes the session variable like so:
//Start the session
session_start();
$arrUser = $result[0];
$_SESSION['User'] = $arrUser[0];
$_SESSION['userName'] = $arrUser[1];
return true;
this works, if loaded in a separate page (changes the session variable and adjusts adjusts the page to confirm session has changed, only if url in manually opened with variables). however by attempting to run the php using ajax:
function Login(){
var Username = document.getElementById("Username");
var Password = document.getElementById("Password");
if(Username.value != "" && Password.value != ""){
URL = "https://localhost/CAB230/Login.php?username=" + Username.value +
"&password=" + Password.value;
httpGetAsync(URL, function(response){
if(response){
location.reload();
} else {
document.getElementById("Username").style.background = "red";
document.getElementById("Password").style.background = "red";
}
});
} else {
window.alert("Username and Password fields must both be filled out");
}
}
function httpGetAsync(theUrl, callback){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
results in true being return and the page being reloaded, but the session variable don't change as the login section loads instead of the logged in confirmation section.
This is very confusing because running this ajax on my laptop changes the session variable, however on my PC this doesn't work.

Pure Javascript Ajax request after submitting a form

I'm not very good at programming, I'm trying to make a contact form and send the information with a response in the same page.
<form id="contact_form" method="post" action="send.php">
// fields
</form>
send.php contains a PHPMailer function to send the mail and other controls, so if js is disabled the user will be redirected to index.php with a success or error message.
But when js is active a validate function checks if all fields are filled and then start an ajax request, this is the code inside js.js file
function validate(e) {
if (error_type === 1) {
e.preventDefault();
// display errors for every fields
} else {
var url = "send.php";
var params = fileds_value;
xhttp = new XMLHttpRequest();
xhttp.open("POST", "url", true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.onload = function() {
if (xhttp.readyState == 4 && xhttp.status === 200 && xhttp.responseText) {
//display success message
}
else if (xhttp.status !== 200 || !xhttp.responseText) {
//display error message
}
};
xhttp.send(JSON.stringify(params));
}
}}
window.onload = function() {
document.getElementById("contact_form").addEventListener("submit", function(e){
validate(e);
});
};
I need to send the form data with the request to prevent the page to being refreshed, right?
and in send.php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'XMLHttpRequest') {
header('Content-Type: application/x-www-form-urlencoded');
echo $ajax_message;
}
// else just display the message
else {
redirect_to($message);
}
But after pressing the submit button the page is realoaded and I see the PHP success message, my goal is to make the page display the success message using ajax, without reloading the page.
EDIT: #IncredibleHat I edited the code to show how the event is handled, so I have to always prevent the default behavior and send the form data like that, then in php I can get the post variables like always?
use event.preventDefault(); , at the top of your event handler, instead of wrapping it within a condition.
if your form is inside other html elements, try also event.stopPropagation(); , as it stops the event from bubbling up and being handled by listeners from parent elements
in the end you would have something like:
form.addEventListener('submit',function(){
event.preventDefault();
event.stopPropagation();
if (error_type === 1)
//doWhatever
//..... perform ajax request
})

PHP redirect user another page in a downloaded Ajax XmlHttpRequest [duplicate]

This question already has answers here:
Page redirect with successful Ajax request
(10 answers)
Closed 5 years ago.
I have a login page. When the user enters username, password, and click the LogIn button, the button calls an Ajax XmlHttpRequest, which send the username and password to the process.php. The php process the data, and return if username or password is not correct. But when correct, I want to redirect the user to the session.php. Php header doesn't work because it takes the page code, and JavaScript doesn't work too, because doesn't run the code. How can I do it?
Here is the Ajax:
function logIn() {
var loader = document.getElementById('loaderParent');
var form = document.getElementById('formI');
form.style.display = "none";
loader.style.display = "block";
setTimeout(function() {
var xhttp = new XMLHttpRequest();
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// console.log(4);
document.getElementById("form").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "class/process.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("zone=LogIn&section=2&username="+username+"&password="+password);
}, 500);
}
what you need is a javascript redirect. For example, use this to redirect to Google main page:
location.href = 'http://www.google.com';
By the way, I recommended you use a library like JQuery to simplify your Ajax call.

what causes the URL to change upon form submissions

I often seen websites with a search function and when they search for something, the web page often changes the url to something along the lines of
search.php?q="searchquery"& etc , i have a search page on my site and i use ajax to submit a form that has a search input and sends to a php page which searches through my database and returns data to a specific div on the original page via echo.
function getdata() {
var str = document.getElementById("searcb");
document.getElementById("demo").innerHTML = "You are searching for: " + str.value;
document.getElementById("searchresults").style.display="block";
if (str == "") {
document.getElementById("demo").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("searchresults").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getuser.php?q=" + str.value, true);
xmlhttp.send();
return false;
}
}
HTML
<form onsubmit="return getdata()">
<input type="search" id="searcb" name="searchBar"></br></br>
</form>
My question is what am i doing differently that causes my url to remain the same compared to a common search engine
In general the url change because a post that reload the page is performed. Your url will not change because you call make an ajax call that will not reload your corrent page .

Categories

Resources