Pure Javascript Ajax request after submitting a form - javascript

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

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

resubmitting form not working after reload

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.

Calling JavaScript function after updating table with PHP

I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.
Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.
This is what AJAX request looks like:
function ajax_post(){
if (typeof featureId !== 'undefined') {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "parse_file.php";
var fn = featureId;
var vars = "featureId="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
hilites.destroyFeatures();
featureId = undefined;
}
else {
window.alert("Select polygon first");
}
}
What is the best way to do this? Some examples would really help.
Looking at your code, you simply need to call the function around this part:
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
// CALL YOUR FUNCTION HERE
}
}
The best solution is to use a Promise. However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.
Here is an example using jQuery.
// This is the function you want to call after the script succeeds
function callbackSuccess() {
console.log('Done!');
}
// This is the data you want to submit to the PHP script
var myData = {
hello: "world"
};
// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
callbackSuccess();
});
Add this to the end of your php save-function:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));
Making the call:
$.getJSON('url_to_your_php_file.php', function(data) {
if (data.status == 'SUCCESS') {
console.log('Save complete');
}
else {
console.log('oops, something went wrong!!');
}
});
It's possible to return something like ERROR, this will return:
console.log('oops, something went wrong!!');
You may try the following:
In php you can use return code from sql statement
echo $sqlResult = $conn->query($sqlStatement);
On Javascript, you can try the following
$.ajax({
url: 'file.php',
type: 'POST',
data: {
data1 : data1,
data2: data2
},
success: function(data){
if(data == success_code){
alert("Success")
}
}
Hope this helps!
Completing ajax request without errors does not mean that the data is saved to DB without errors.
Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.
If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.
If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).
Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).
Maby you have to try this:
setTimeout(function(){
//your function here...
}, 500);

how to handle php echo'ed message in ajax.

I am creating an AJAX+PHP submit form, for example purposes. For this, I will need Ajax, PHP and index.html file to write into the inputs. The problem is that, when I submit I have no way of redirecting a page, so I created this hack. (since page redirect get permission from the PHP script first) otherwise show error.
AJAX
function submit_form(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success'){
location.href = '/success';
}
//
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
And this is my PHP.
<?php
echo "/success";
if($_GET){
}else{
echo "error, no value found";
}
as you can see, this allows me to redirect the page, as the javascript will read the "/success" and redirect the document, but one problem with this is that, I don't like using echo, because the page actually shows "success" before redirect. I don't want it to show anything to the page.
Change your echo statement to return json_encode(), then in your JS code, you can parse it using JSON.parse();
In your PHP removes the slash of this line: echo "/success";
And in your java script code, add a else sentence before print error:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success') {
location.href = '/success';
}
else {
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
}

Making sure request will be completed after changing page

The problem is: I have custom analtyics engine that sends log using JavaScript. I want to send log after user submits a form. The log is send using AJAX. Now the problem is, form submission is not AJAX, it is normal request that refreshes the page.
I already learned that you can force the script executions even if client aborted connection
Does php execution stop after a user leaves the page?
What I want to learn is how to be sure that server recives request and headers if form is submited almost instantly after AJAX call is send?
var url = "...";
var my_form = document.getElementsByTagName("form")[0];
var request_received = false;
my_form.addEventListener("submit", function(e) {
if (!request_received) {
e.preventDefault(); // prevent the form from submitting
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState >= 2 && !request_received) {
request_received = true;
my_form.submit(); // submit the form only if the request has been received
}
};
xhr.open("GET", url, true);
xhr.send();
return false;
}
}, false);
Lets say that this is your form with submit button:
<form id="myForm" action="/myAction.html" method="POST">
<!-- form inputs -->
<input type="submit" value="submit me!" />
</form>
With JavaScript you can bind to the submit event of your form, do your ajax call and then return true to continue submiting your form to the server:
<script type="text/javascript">
document.getElementById('myForm').addEventListener('submit', function(e){
// do your ajax call here and when you finish, return true from
// this function (in the ajax success callback)
return true;
});
</script>

Categories

Resources