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);
}
});
Related
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
I have a registration form. The register.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 Location:index.php (good)
register.php
The problem is, if there is any error, the user will be redirected to register.php
and the echo alert shows there (on white page)
AJAX
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 the msg div(same page 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 echo errors (register.php) to be handled by AJAX
Please understand that im new & learning, i spent a week in this.
If you choose to resolve this, please fix based off register.php and ajax code
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
}
})
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.
I am building an online calculator and tried to send the values through AJAX to process them by a php script. The response from the server is set to the div but that div immediately disappears after showing. My ajax code is:
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // calls the function for the XMLHttpRequest instance
// gets data from form fields, using their ID
var c1 = document.getElementById('c1').value;
var c2 = document.getElementById('c2').value;
var c3 = document.getElementById('c3').value;
var c4 = document.getElementById('c4').value;
var c5 = document.getElementById('c5').value;
var c6 = document.getElementById('c6').value;
// create pairs index=value with data that must be sent to server
var the_data = 'c1='+c1+'&c2='+c2+'&c3='+c3+'&c4='+c4+'&c5='+c5+'&c6='+c6;
request.open("POST", php_file, true); // sets the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // sends the request
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById("ajaxform").submit();
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
Please note that I am using bootstrap CSS framework for the actual site and not applying any classes on the response div.
Thanks
In your onreadystatechange handler, you're submitting a form, which is causing the page to submit (and therefore the page to change).
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById("ajaxform").submit(); // <-- ?
document.getElementById(tagID).innerHTML = request.responseText;
}
}
The fact you're seeing the same page again means the form ajaxform has no action set.