location.href not working after ajax response - javascript

I have an form that when it sumits the data it echo "success", I used the success to trigger a redirect to another page but it is not working. I have tried everything. The else statement works fine but whatever i write in the if(data == "success") is not working including console.log and alert.`
continueBtn.onclick = () =>{
//Ajax code
let xhr = new XMLHttpRequest();// this will create a new XML Object
xhr.open("POST", "php/signup.php", true );
xhr.onload = () =>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
if(data == "success"){
errorTxt.textContent = "Thuinsowofnd wsikenon";
window.location.href = 'users.php';
}else{
errorTxt.textContent = data;
errorTxt.style.display = "block";
}
}
}
}
//let's send form data through Ajax to Php
let formData =new FormData(form);//this will create a new form object
xhr.send(formData);// this will the form data
`
I have tried using windows.location.href = "users.php" but it still doesn't work

Related

PHP AJAX redirect after register

I have a registration form. The PHP is checking for errors such as short password
AJAX gives an alert with the echo error from PHP.
With PHP, after an if else statement,
the user will be registered and redirected successfully to index.php (good)
header('Location:home.php');
exit;
The problem is, if there is any error, the user will be redirected to handler.php and the echo alert shows there (on white page)
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
if (xhr.status >= 200 && xhr.status <= 299) {
var response = JSON.parse(xhr.responseText);
if (response.location) {
window.location.href = response.location;
} else {
xhr.send(form_data);
}
}
Example 2: the alerts will display properly at <div class="msg"></div> position
(But will also throw the index.php on registration form, where the alerts go)
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
xhr.send(form_data);
};
So, i want the user to be redirected to index.php & also the alerts to be handled by AJAX
Regarding responding to AJAX requests with redirects, please see What is the difference between post api call and form submission with post method?. Does a better job explaining than I could.
The basic idea is that when called asynchronously, your PHP should do what it needs to do and respond with either a 200 (success) or an error status like 400 (bad request) + error details.
// make sure nothing is echo'd or otherwise sent to the
// output buffer at this stage
$errors = []; // collect errors in here
// do whatever you need to do with the $_POST / $_FILES data...
// capturing errors example...
if ($_POST['cpassword'] != $_POST['password']) {
$errors[] = "Passwords do not match!";
}
// use content negotiation to determine response type
if ($_SERVER['HTTP_ACCEPT'] === "application/json") {
if (count($errors)) {
header("Content-type: application/problem+json");
http_response_code(400);
exit(json_encode([
"message" => "Invalid form data or something",
"errors" => $errors
]));
}
header("Content-type: application/json");
exit(json_encode(["location" => "home.php"]));
}
// just a normal request, respond with redirects or HTML
// ...
foreach ($errors as $error) : ?>
<div class="error"><?= $error ?></div>
<?php endforeach;
The client can navigate to home on success or display error information otherwise
document.querySelector(".register form").addEventListener("submit", async (e) => {
e.preventDefault()
const form = e.target
const body = new FormData(form)
// fetch is much easier to use than XHR
const res = await fetch(form.action, {
method: "POST",
headers: {
accept: "application/json", // let PHP know what type of response we want
},
body
})
const data = await res.json()
if (res.ok) {
location.href = data.location
} else if (res.status === 400) {
document.querySelector('.msg').textContent = data.message
// also do something with data.errors maybe
}
})

vscode live server extension cuts off JavaScript code

I am trying to make a online booking system. And I am using vscode live server for live web for testing. I noticed that it cuts off a huge chunk of js code. I am using the newest version of vscode and google chrome. If you need any more information, feel free to ask me :).
Expected Behaviour:
<script>
window.addEventListener("DOMContentLoaded", function () {
// get the form elements defined in your form HTML above
var form = document.getElementById("my-form");
// var button = document.getElementById("my-form-button");
var status = document.getElementById("status");
// Success and Error functions for after the form is submitted
function success() {
form.reset();
status.classList.add("success");
status.innerHTML = "Thanks!";
}
function error() {
status.classList.add("error");
status.innerHTML = "Oops! There was a problem.";
}
// handle the form submission event
form.addEventListener("submit", function (ev) {
ev.preventDefault();
var data = new FormData(form);
ajax(form.method, form.action, data, success, error);
});
});
// helper function for sending an AJAX request
function ajax(method, url, data, success, error) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status === 200) {
success(xhr.response, xhr.responseType);
} else {
error(xhr.status, xhr.response, xhr.responseType);
}
};
xhr.send(data);
}
</script>
Actual Behavior:
<script>
window.addEventListener("DOMContentLoaded", function () {
// get the form elements defined in your form HTML above
var form = document.getElementById("my-form");
// var button = document.getElementById("my-form-button");
var status = document.getElementById("status");
// Success and Error functions for after the form is submitted
function succe</script>
Reload the webpage and it should work.

Wordpress ajax request in pure javascript (where to put action?)

WordPress ajax request in jquery.
The ajax request in jquery works but I'm trying to use pure JavaScript.
How can I turn this code into pure javascript?
$('#camitonContactForm').submit(function(event){
event.preventDefault();
isValidationOn = true;
validateInputs();
let formaction = $('#camitonContactForm').data('url');
let forminput = $('#camitonContactForm').serialize();
let noncecheck = $('#camitonContactForm').data('nonce'); ;
let formdata = new FormData;
formdata.append('action', 'contact_message');
formdata.append('nonce', noncecheck);
formdata.append('contact_message',forminput);
$.ajax(formaction, {
type:'POST',
data:formdata,
processData: false,
contentType:false,
success: function(res){
},
error: function(err){
alert(err.responseJSON.data);
}
});
Here I tried to write it in pure javascript but it doesn't work.
form.addEventListener('submit', (e) => {
e.preventDefault();
isValidationOn = true;
validateInputs();
//form action
let formwrapper = document.getElementById('camitonContactForm');
let formaction = formwrapper.getAttribute('data-url');
//form nonce
let noncecheck = formwrapper.getAttribute('data-nonce');
//form
let forminput = serialize(formwrapper);
var formdata = new FormData(form);
/*
formdata.append('action', 'contact_message');
formdata.append('nonce', noncecheck);
formdata.append('contact_message',forminput);
*/
let ajax = new XMLHttpRequest();
ajax.open("POST", formaction, true);
ajax.onreadystatechange = function() {
if(ajax.responseText == 4 && ajax.status == 200){
if(ajax.responseText == "success"){
}else{
statusSection.innerHTML = ajax.responseText;
btnsection.disabled = false;
alert('well something wrong');
}
}
}
ajax.send(formdata);
});
the serialize funcion i found on this link below
form serialize javascript (no framework)

How can Javascript account for returning a 500?

I am using a login form to construct and send a URL (that'd be the "full url" written to storage in the script below) that should return a JSON object.
If the login is correct, the back-end sends me a JSON object with a validation key in it to validate if it cam back successfully. (like this: [{"result":"VALID"}] )
If the login is incorrect, it only provides a 500 error.
Unfortunately, when it gets that 500 error, instead of booting them because the result isn't VALID, the script just gives up because there's no object to validate.
From the Front-End, how can I detect that I have received a 500 error and then trigger "bootThem()"?
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}
Please see below fiddle I have simulated a 500 response from Mock API and handlinkg it:
if (rawFile.readyState === 4 && ((rawFile.status === 200) || (rawFile.status === 500))) {
console.log("fired");
callback(rawFile.responseText);
}
https://jsfiddle.net/asutosh/vdegkyx2/8/
Okay so thanks to Asutosh for the push in the right direction, I was able to adjust my function to boot the user if a 500 error was returned from the JSON call, and allow the user to pass through if there was not.
This was exactly what I needed to handle the 500 error coming back form the JSON:
function bootThem() {
//execute code to reset session and return user to login page.
}
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.addEventListener('error', () => {
console.log("error code");
});
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && (rawFile.status === 500)) {
console.log("500");
bootThem();
callback(rawFile.responseText);
}
if (rawFile.readyState === 4 && (rawFile.status === 200)) {
console.log("200");
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}

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);
}
});

Categories

Resources