PHP Redirect and Ajax - javascript

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

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.

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

call js function from form action then call php from js

We can call php directly from form action in html:
<form name='x' action = "filename.php">
in this case, php will receive all inputs in the form even we don't pass them.
Can we call js function from form action in html?
<form name='x' action = "javascript:jsFunction();">
Then, call the php from the js function?
jsFunction()
{ var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Hint
I cannot use onsubmit because it log me out from the platform. in other words, it reload the platform from the beginning of the login page.
I am working on integration and I don't have a clear idea about the platform.
Edit 1:
Now, in the HTML file:
<form enctype='multipart/form-data' id = "myform">
<input type='submit' value='Basic search' onclick = "i2b2.BLAST.jsFunction();">
JS file:
i2b2.BLAST.jsFunction = function ()
{
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(event)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", blastresult.php, true);
xhttp.send();
event.preventDefault();
});
}
it reloads the platform from the beginning of the login page!
Edit2:
I put some alert to see if the button call the javascript.
i2b2.BLAST.jsFunction = function ()
{
alert('hi');
this.yuiTabs = new YAHOO.widget.TabView("BLAST-TABS", {activeIndex:1});//this two lines navigate to second tab
this.yuiTabs.set('activeIndex', 1);
alert('hi');
myForm.addEventListener('submit', function()
{
alert('hi');
preventDefault();
The button call the js and display first 'hi' then navigate to second tab then reload the page. It stop at the second 'hi'.
Any help is highly appreciated.
Thanks.
Yes you can, First give your FORM an id
<form id="myForm"></form>
then in javascript try this:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
e.preventDefault();
});
Instead of:
<form name='x' action = "javascript:jsFunction();">
Use:
<form name='x' onsubmit="jsFunction();">
You can POST via AJAX as you have shown in your code:
function jsFunction(event) {
// prevent default event from taking place (submitting form to file)
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Though you will need to serialize your data and pass it to xhttp.send(), it will need to be form url encoded like: key1=value1&key2=value2. You are probably better off using jQuery in the manner #mmm suggests.

How to make formData object from image URL

I want to make image upload from url for example: http://.. ../logo.png
I need to make formData object from image url but it doesn't work:
HTML:
<form id="form-url">
<input type="text" class="image" id="textarea" placeholder="URL" />
<button>UPLOAD</button>
</form>
Javascript:
$("#form-url").submit(function(e) {
if ($(".image").val() != "URL" && $(".image").val() != "") {
//I also tried this:
var data;
var img = new Image();
img.src = $(".image").val();
img.load = function(){
data = getBase64Image($(".image").val());
};
//but it send undefined
//and this:
var data = URL.createObjectURL($(".image").val()); //dont work
//error: TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL.
//Upload process working on normal input type file uploading but no on URL image
var formData = new FormData(data);
formData.append("fileToUpload", data);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_ajax.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
data = xhr.responseText;
datas = data.split("_");
if (datas[0] != "true") {
alert(data);
} else {
alert('YES');
}
} else {
alerter('An error occurred while uploading this file! Try it again.');
}
};
xhr.send(formData);
} else { alerter("Your file must be an image!"); }
return false;
});
My php script for debug:
<?php
if (isset($_POST)) {
var_dump($_POST);
if (empty($_FILES['fileToUpload']['tmp_name'])) {
echo "Your file must be an image!";
} else {
echo $_FILES['fileToUpload']['name'];
echo $_FILES['fileToUpload']['size'];
}
}
?>
Thanks for all help and your time..
and sorry for my bad english (student)
If getBase64Image is from here, or is similar to it.
Then you are using it wrong. You need to pass it the image node itself. Also the image onload event is async, and as such you have to wait for it to be done to get the data and send it.
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open('POST', "upload_ajax.php", true);
...
var img = new Image();
img.onload = function(){
var data = getBase64Image(this);
formData.append("fileToUpload", data);
xhr.send(formData);
};
Also note on the server side you will need to decode it from the base64 encoding, as it is being sent by string, it is going to be in $_POST not $_FILE
var rawContents = base64_decode($_POST['fileToUpload']);
Note you could also just send the url to the php script and just have php get the image data
var rawContents = file_get_contents($_POST['imageurl']);

Categories

Resources