Hello I managed to get my submit to send a post request via ajax, but I want to make this asynchronous in case my php-file takes longer to process.
I can't seem to wrap my head around the way to async the ajax part. Here is my function so far:
submitForm(e) {
console.log(e);
e.preventDefault();
/* to prevent double submitting the form after the first submit*/
/* submitBtn.disbabled = true; */
this.isDisabled=true;
this.submitStatus = 'Successfully send!';
/* append form-values to the formdata s i can push it to my .php file */
const formData = new FormData();
formData.append('user_name', this.user_name);
formData.append('user_email', this.user_email);
formData.append('user_message', this.user_message);
/* async function should probably start here..*/
/* object of my http request */
const ajax = new XMLHttpRequest();
/* opneing my connection */
ajax.open('POST', this.url);
ajax.onreadystatechange = function() {
/* if state is send and status is ok */
if(ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText === "success") {
/* contactForm.innerHTML = `<h2>Thank you, ${contactName}, your message has been send.</h2>` */
}else {
this.submitStatus = ajax.responseText;
this.isDisbabled = false;
}
}
}
/* function-call of my promise function */
/* send the request with the appended form data.
executing the load event */
ajax.send(formData);
/* resetting the input-fields to blank after the submit is done. */
this.user_name="";
this.user_email="";
this.user_message="";
}
I appreciate the help!
You could always wrap the AJAX call in an async function like so:
async function ajaxRequest() {
//ajax call here (pass in anything you need)
return result;
}
and then in your main function just await the result:
let ajaxResult = await ajaxRequest();
so the rest of your code won't execute until the ajax call has finished and the result has been received :)
Related
Why isn't the form submitted the first time?
What have I done wrong?
If I click submit, the console will display the output (Event check # 0. Event check # 1.)
If I click on the submit button again, the console will display the output (Event check # 0. Event check # 1. Event check # 2.)
And after that the message will be sent to the mail.
".button-f" and "# send-btn-form" are the same button!
//#1grn --- Submitting the form without reloading the page
let sendBtn = document.querySelector(".button-f");
sendBtn.onclick = function(e) {
e.preventDefault(); // Cancels the default browser action
console.log("Event check №0.");
let formName = document.querySelector('#main-form'); // Find our shape
let formData = new FormData(formName); // Create a new FormData-object. We use all fields with the attribute name
let request = new XMLHttpRequest(); // Create a new XMLHttpRequest-object.
request.open('POST', "php/send.php"); // We configure it: POST-request for URL php/send.php
//#1grn --- Filtering characters such as: &<>"'
['name', 'socialname', 'numberfo', 'email', 'text'].forEach(name => {
let input = document.querySelector(`[name='${name}']`);
input.value = escape(input.value);
console.log("Event check №1.");
});
//#1grn --- Check ("real" event or generated by code)
let sendBttn = document.querySelector("#send-btn-form");
sendBttn.addEventListener('click', e => { // We accept the event object into our callback-function, call it "e".
if (e.isTrusted) { // CHECKING, if a e.isTrusted === true - then this is not a machine click.
request.send(formData); // We send HTTP request to the server and get a response.
console.log("Event check №2.");
} else {
console.log('blocked!');
}
});
// This code will work after we receive the server response
request.onload = function() {
if (request.status != 200) { // analyze HTTP-response status, if the status is not 200, then an error has occurred
} else { // if everything went smoothly, clear the form and display the result
formName.reset(formData); // Clearing the form
let on = document.querySelector(".message-good");
on.classList.add('ms-on');
}
};
};
If ".button-f" and "#send-btn-form" are the same button, you are adding an event listener every time you click the button. In that case, you are not executing the code inside that listener, it will be executed the next time you click it. So you could replace this
let sendBttn = document.querySelector("#send-btn-form");
sendBttn.addEventListener('click', e => {
if (e.isTrusted) {
request.send(formData);
} else {
console.log('blocked!');
}
});
with just this
if (e.isTrusted) {
request.send(formData);
} else {
console.log('blocked!');
}
I have an ajax request executing through the XMLHttpRequest() object
My AJAX method is called in this format:
var xmlhttp = new XMLHttpRequest();
$(document).ready(function () { LoadData(); });
function LoadData()
{
var parameters = "DisplayData=true";
var url = "default.aspx";
Send(url, parameters, "DisplayData");
CheckForAbort();
}
function Send(url, parameters, QueryType)
{
...
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-lencoded");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange = function (){...}
}
There is also a timer on the page which refreshes the data by making a new request through the Send(...) method in intervals of 15 seconds. Every .3 seconds and it calls an Elipsis() method that displays and "blinks" the "loading message" (if appropriate to be displayed) and checks for the abort.
var Color = "red";
function Elipsis() {
if (ResponseMessage != "")
{
if (Color == "darkred") { Color = 'red'; } else { Color = 'darkred'; }
$("#StatusResponse").css("display", "block");
$("#StatusResponse").css("color", Color);
CheckForAbort();
}
}
function CheckForAbort()
{
console.log("MenuActivted: " + MenuActivted);
if (MenuActivted)
{
xmlhttp.abort();
ResponseMessage = "Aborting Request";
MenuActivted = false;
}
}
But when the user clicks the menu bar which is an anchor tag with the HREF set to another page. The browser doesn't respond until the ajax request has completed it's fetch.
The HTML HREF is called the following way on an ASPX page:
<%#Eval("Text")%>
the Ajax Abort sets the flag that is checked in the CheckForAbort() method:
var MenuActivted = false;
function AbortAjax()
{
MenuActivted = true;
return false;
}
I am running IE 11 on Win 7. I have called an abort() method in another section of the code. which executes the xmlhttp.abort(). The response status and ready state respond (console output below) but the page still waits to respond to the HREF
Console output:
HTML1300: Navigation occurred.
File: ChangePassword.aspx
MenuActivted: true
ReadyState: 4
Status: 0
Does anyone have a solution to this problem?
[Updated **********]
I thought I had the solution but I didn't.
I commented out the set header but although it allowed my HREF to execute it was because the xhr was throwing an error and the fetch was terminating.
xmlhttp.open("POST", url, true);
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
Please read the entire post before responding.
I want to make browser extension for Firefox that detect the ajax code of of website that load the hidden page and redirect to new page ,like if user visit index.php where ajax load the two pages one is hiddenpage.php and redirect to new.php . Is there any other solution to detect this ajax at client side.
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("myDiv").innerHTML="";
}
}
xmlhttp.open("GET","hidden.php",true);
xmlhttp.send();
}
HTML
click here
document.addEventListener('DOMContentLoaded', function() {
getCurrentTabUrl(function(url) {
fetchData(url);
});
});
function fetchData(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
var data = xhr.responseText;
var index = data.indexOf('XMLHttpRequest');
if(index != -1){
document.getElementById("status").innerHTML = "The page contains AJAX requests";
}else{
document.getElementById("status").innerHTML = "Page doesn't contains AJAX";
}
//document.getElementById("status").innerHTML = data;
}
}
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
//xhr.setRequestHeader("Access-Control-Request-Method", "POST");
xhr.send();
}
function getCurrentTabUrl(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
var url = tab.url;
console.assert(typeof url == 'string', 'tab.url should be a string');
callback(url);
});
}
just go through this code you will get the better help
You can modify XMLHttpRequest's prototype in an userscript.
/* Save the old method somewhere, it may be useful if you want to allow some AJAX */
XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send;
/* Override the previous method to define yours */
XMLHttpRequest.prototype.send = function () {
/* Do stuff here */
alert(1);
/* Use this line if you want to continue the AJAX request */
XMLHttpRequest.prototype._send.apply(this, arguments);
}
I'm new to web-development. Created a signup page making some asynchronous calls to php. Ran debugging found the control skips the onreadystatechange function completely. Please help...
var ajax = ajaxObj("POST", "signup.php"); //defines the ajax object, definition is below
ajax.onreadystatechange = function () { //doesn't run after this line
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box
at <u>"+e+"</u> in a moment to complete the sign up process.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g); //control reaches here directly
}
}// control exits here
The ajax object is created externally here..
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is because it's an event callback function and it will be called when server responds to your ajax request. If you're using firefox press F12, switch to network tab and check html and xhr to see it's status.
Because it is asynchronous so the function won't be called as you step through the code in a linear fashion.
It gets called by native code when the ready state changes.
Stick a breakpoint inside the function if you want to debug it.
i have a trouble with my project.
In my site i have a page html with a single button and at onclick() eventa js function call intro.js, trough a XmlHttpRequestObject have to do many calls at many php function, in detail:
in js i call scan() function
function scan() {
if (xmlHttp)
{
// try to connect to the server
try
{
// initiate reading the async.txt file from the server
xmlHttp.open("GET", "php/intro.php?P1=http://"+oStxt.value, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
// change cursor to "busy" hourglass icon
document.body.style.cursor = "wait";
}
// display the error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
And in handleRequestStatuschange i have:
function handleRequestStateChange()
{
// obtain a reference to the <div> element on the page
// display the status of the request
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
// read response only if HTTP status is "OK"
if (xmlHttp.status == 200)
{
try
{
// read the message from the server
response = xmlHttp.responseText;
// display the message
document.body.appendChild(oRtag);
oPch = document.getElementById("divRtag");
oOch = document.createTextNode(response);
oPch.appendChild(oOch);
}
catch(e)
{
// display error message
alert("Error reading the response: " + e.toString());
}
}
else
{
// display status message
alert("There was a problem retrieving the data:\n" +
xmlHttp.statusText);
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
It works for just one php call, but i need to call different php page in scan function after intro.php (scan2.php, scan3.php, ecc ecc) and with json_decode write single data of the array that return in div tags on my html page.
Which is the best way to call different php pages and manage the results with a single js function in ajax?
Thanks in advance
Alessandro
Not sure how you built your php-functions. Cant you create a function, that calls other functions (scans)?
function doScan(){
$data = array();
//like this, or with a loop
$data['scan1'] = scan1();
....
$data['scanN'] = scanN();
echo json_encode($data);
}
Really, the simplest method that comes to mind is just to parameterise this function. This is as simple as
function doScan(url) { // Code here }
Then simply make the exact same ajax request with the url variable.
xmlHttp.open("GET", "php/" + url + "?P1=http://"+oStxt.value, true);
Next, simply call the doScan function with various parameters.
doScan("index.php");
doScan("otherPage.php");
doScan("somethingElse.php");
This will make ajax requests on the PHP file that you specify.