I use heroku CORS anywhere proxy to solve CORS Access-Control-Allow-Origin in my form.
Now, my form showing message not send every time i tried to send a message. How can i solve this issue?
My form: Demo
Scripts:
const blogId="xxxxxxxxxxxxx";
var contactForm = document.querySelectorAll(".contact-form-blogger");
function an(req) {
try {
return JSON.parse(req)
} catch (req) {
return false
}
}
for (i = 0; i < contactForm.length; i++) {
var a = contactForm[i];
a.addEventListener("submit", function (submitUrl) {
submitUrl.preventDefault();
var form = submitUrl.target;
var req = new FormData(form),
cH = "blogID=" + typeof blogId !== "undefined" ? blogId : "";
req.forEach(function (cL, cK) {
cH += "&" + encodeURIComponent(cK) + "=" + encodeURIComponent(cL)
});
submitUrl = "https://cors-anywhere.herokuapp.com/https://www.blogger.com/contact-form.do";
req = new XMLHttpRequest;
req.open("post", submitUrl, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(cH);
req.onreadystatechange = function () {
var cK;
if (this.readyState === 4) {
if (this.status === 200) {
if (this.response != "") {
cK = an(this.responseText.trim());
if (cK.details.emailSentStatus == "true") {
form.reset();
var formSend = form.querySelector(".send-success");
if (formSend) {
formSend.style.display = "block";
}
} else {
var notSend = form.querySelector(".send-error");
if (notSend) {
notSend.style.display = "block";
}
}
}
}
}
}
})
}
You're using the demo server as your proxy, which is rate-limited and not open. See this announcement for details. You need to deploy it yourself and change the URL prefix to point to your version. The documentation, such as it is, can be found at the bottom of the README. Advanced options are here. You're also posting to Blogger, which doesn't accept a POST at that path (returns a 405, method not allowed).
Related
here is my code that call a function to redirect the page using browser.webRequest.onBeforeRequest
browser.webRequest.onBeforeRequest.addListener(
redirect,
{
urls: ["<all_urls>"],
types: ["main_frame"],
},
["blocking"]
);
and redirect function:
function redirect(requestDetails){
let redirection_url = "https://google.com/";
let type = requestDetails.type;
let url = requestDetails.url;
var checkurl = ""
var final_url = '';
if(url.includes("http://")){
checkurl = url.split('http://')[1]
final_url = 'https://'+checkurl;
}else if(url.includes("https://")){
final_url = url;
}else{
final_url = 'https://'+url;
}
var xhttp = new XMLHttpRequest();
xhttp.open("GET", final_url, true);
xhttp.send();
return xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
return {
cancel:true,
};
}else if(this.status == 0 && this.readyState == 4){
return {
redirectUrl: redirection_url,
};
}
};
}
I am returning redirectUrl or cancel on the basis of the url is working on https or not. If there is no https on the website then I want to redirect to google.com, the response is fine and code is fine but there is some delay in response so the listener is not redirecting after getting a response.
the listener is in blocking state but still not working, i found this answer on
stackoverflow
and i am return the readystatechange but still it is not working, really appreciate your help. thanks
The answer was simple that we have to return a promise so we have a blocking behaviour untill we get a value from promise.
function redirect(requestDetails){
return new Promise((resolve, reject) => {
let redirection_url = "https://google.com/";
let type = requestDetails.type;
let url = requestDetails.url;
var checkurl = ""
var final_url = '';
if(url.includes("http://")){
checkurl = url.split('http://')[1]
final_url = 'https://'+checkurl;
}else if(url.includes("https://")){
final_url = url;
}else{
final_url = 'https://'+url;
}
var xhttp = new XMLHttpRequest();
xhttp.open("GET", final_url, true);
xhttp.send();
var abc = setInterval(() => {
console.log(xhttp, xhttp.status)
if(xhttp.readyState == 4){
if (xhttp.status == 200) {
reject({ cancel: true });
} else if(xhttp.status == 0 && xhttp.readyState == 4) {
resolve({
redirectUrl: redirection_url,
});
}
clearInterval(abc)
}
}, 1000);
});
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to return a value from an onreadystatechange AJAX call... I found this page : stackoverflow link. I though I had it working but realised that it made no difference to add or remove the fn function. The following code works :
username_is_available();
function username_is_available() {
var username = document.getElementById('username').value;
get_data('username', username, function(returned_value) {
if (returned_value == 'true') {
document.getElementById('username_err').innerHTML = 'Taken';
} else {
document.getElementById('username_err').innerHTML = 'Available';
};
});
}
function get_data(data_type, data, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "availability.php?" + data_type + "=" + data, true);
xmlhttp.send();
}
It all works fine but that's not my goal, I would like a function username_is_available() that returns true if the username is indeed available.
Instead, here I an action happens (innerHTML is changed). And if I try and do a return in the anonymous function I get the same result as if I had returned it from directly inside the onreadystatechange : var unasigned
Unfortunately, since the process to determine if a username is taken is asynchronous, there is no way to simply return a value of true or false from the function call. What you can do is set up something similar to what you have now (callbacks) using language features specifically designed for this exact purpose.
A Promise is one of these features.
Usage would look something roughly like this:
function username_is_available(username) {
return new Promise(resolve => {
get_data("username", username, resolve);
});
}
function get_data(data_type, data, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText == "true");
}
};
xmlhttp.open("GET", "availability.php?" + data_type + "=" + data, true);
xmlhttp.send();
}
// Usage:
username_is_available("Ivan").then(available => {
let text = available ? "Available" : "Taken";
document.getElementById("username_err").innerHTML = text;
});
This relies on availablity.php returning true and false as text, which is converted to a Boolean before resolve is called.
In the future, when ES7+ async and await directives are available, using the promise will be as simple as this (note the await keyword):
let available = await username_is_available("Ivan");
let text = available ? "Available" : "Taken";
document.getElementById("username_err").innerHTML = text;
Edit: If you can't use ES6 or promises, it's back to good ol' callbacks!
function username_is_available(username, callback) {
get_data("username", username, callback);
}
function get_data(data_type, data, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText == "true");
}
};
xmlhttp.open("GET", "availability.php?" + data_type + "=" + data, true);
xmlhttp.send();
}
// Usage:
username_is_available("Ivan", function(available) {
var text = available ? "Available" : "Taken";
document.getElementById("username_err").innerHTML = text;
});
I've been playing around with observers as an alternative to promises. I set up a an example in plnkr to show how it can work. I think in your case it would look like this:
function Producer() {
this.listeners = [];
}
Producer.prototype.add = function(listener) {
this.listeners.push(listener);
};
Producer.prototype.remove = function(listener) {
var index = this.listeners.indexOf(listener);
this.listeners.splice(index, 1);
};
Producer.prototype.notify = function(message) {
this.listeners.forEach(function(listener) {
listener.update(message);
});
};
var notifier = new Producer;
function get_data(data_type, data) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
notifier.notify(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "availability.php?" + data_type + "=" + data, true);
xmlhttp.send();
}
var username_is_available = {
update: function(returned_value) {
var username = document.getElementById('username').value;
if (returned_value == 'true') {
document.getElementById('username_err').innerHTML = 'Taken';
} else {
document.getElementById('username_err').innerHTML = 'Available';
};
}
}
notifier.add(username_is_available);
get_data("username", username);
Note the Producer code is reusable, you would make a new instance for other ajax/observable requests.
I've read a lot of how to try and make two xmlhttprequest in parallel, but it looks like something doesn't quite work.
I have 1 php file. which includes 2 .js files.
The first runs xmlhttprequest every 3 seconds.
I want the second to run on demand, but whenever i trigger it, it returns with status 4 but the responseText is always empty. (the PHP file prints with no question, i even tried to put on the PHP file just window.open('1') to see that the file is called and its not).
Here is the first JS :
var req1 = createXMLHttpRequest2();
var user_redirected = false;
function createXMLHttpRequest2() {
var ua2;
if(window.XMLHttpRequest) {
try {
ua2 = new XMLHttpRequest();
} catch(e) {
ua2 = false;
}
} else if(window.ActiveXObject) {
try {
ua2 = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua2 = false;
}
}
return ua2;
}
function set_user_redirected_false() {
user_redirected = false;
}
function get_user_redirected() {
return user_redirected;
}
function handleResponse(username, game_id, isInvitation) {
if(req1.readyState == 4 && req1.status==200) {
var response = req1.responseText;
if (response == "true") {
// Ask to set the game_accepted var to 1 (user is redirected and not leaving)
user_redirected = true;
if (isInvitation == "true") {
window.location.href = "game.php?game_id="+game_id+"&position=2";
} else {
window.location.href = "game.php?game_id="+game_id+"&position=1";
}
}
else {
setTimeout(function(){sendRequest();}, 3000);
}
}
}
function sendRequest() {
user_redirected = false;
var username = "";
var game_id = -1;
var isInvitation = "false";
username = document.getElementById("username").value;
game_id = document.getElementById("game_id").value;
isInvitation = document.getElementById("invitation").value;
if (isInvitation == "true") {
req1.open('GET', 'check_for_inviter.php?username='+username+'&game_id='+game_id ,true);
} else {
req1.open('GET', 'check_for_opponent.php?username='+username+'&game_id='+game_id,true);
}
req1.onreadystatechange = function(){handleResponse(username, game_id, isInvitation);};
req1.send(null);
}
This is the second JS file :
function createXMLHttpRequest() {
var ua;
if(window.XMLHttpRequest) {
try {
ua = new XMLHttpRequest();
} catch(e) {
ua = false;
}
} else if(window.ActiveXObject) {
try {
ua = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua = false;
}
}
return ua;
}
function delete_waiting_games(username) {
var req2 = createXMLHttpRequest();
req2.open('GET', 'delete_waiting_games_for_username.php');
req2.onreadystatechange = function(){
window.open(req2.readyState+'&'+req2.responseText);
};
req2.send(null);
}
As you can see i open a new window to see the response and the ready state (just for testing) and i always get status 4 and empty responseText.
Thanks.
Use setTimeout to separate the calls, and with to encapsulate the XMLHTTPRequest:
function xhr()
{
with(new XMLHttpRequest)
{
open("GET",{},true);
setRequestHeader("Foo", "Bar");
send("");
onreadystatechange = handler;
}
}
function handler(event)
{
!!event.target && !!event.target.readyState && event.target.readyState === 4 && ( console.log(event) );
}
setTimeout(xhr, 500);
setTimeout(xhr, 1000);
What I'm trying to do is limit the options of one select box based on what the user chooses in a prior select box. It works perfectly in Chrome and Firefox, but in IE 10 the only thing that shows up is the text "Not Found". I'm not sure, but my guess is that something is going wrong in request.status. What it is, however, I have no idea.
function prepForms() {
for (var i = 0; i<document.forms.length; i++) {
var thisform = document.forms[i];
var departCity = document.getElementById("departcity");
departCity.onchange = function() {
var new_content = document.getElementById("ajaxArrive");
if (submitFormWithAjax(thisform, new_content)) return false;
return true;
}
}
}
function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {}
return false;
}
return new XMLHttpRequest();
}
function submitFormWithAjax(whichform, thetarget) {
var request = getHTTPObject();
if (!request) {return false;}
var dataParts = [];
var element;
for (var i = 0; i<whichform.elements.length; i++) {
element = whichform.elements[i];
dataParts[i] = element.name + "=" + encodeURIComponent(element.value);
}
var data = dataParts.join("&");
request.open("POST", "flightlocationfilter.asp#ajaxArrive", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var matches = request.responseText.match(/<div id="ajaxArrive">([\s\S]+)<\/div>/);
if (matches.length > 0) {
thetarget.innerHTML = matches[1];
} else {
thetarget.innerHTML = "<p>--Error--</p>";
}
} else {
thetarget.innerHTML = "<p>" + request.statusText + "</p>";
}
}
};
request.send(data);
return true;
};
Edit: After walking through with the IE Developer Tools, it looks like the request.readyState is not moving beyond 1 to 4.
I am executing a function where first I am making cursor to wait state(hourglass) and then I am sending a synchrounous AJAX request .After getting the response I am making cursor to default state.
The Actual Code is this..
// tests the smtp settings
function TestSettings()
{
var buttonparams= new Object();
buttonparams.IsCommandButton = true;
buttonparams.ButtonId = "testsettings";
buttonparams.ButtonText = "Sending Test Mail...";
buttonparams.ButtonOrigText = "Test Settings";
if(buttonparams.IsCommandButton == true)
HandleButtonStatus(true, buttonparams);
var request = function()
{
var ret = SendForm(buttonparams);
alert(ret);
}
window.setTimeout(request, 0);
}
function SendForm(pButtonParams)
{
var http;
var formdata;
http = yXMLHttpRequest();
http.open("POST", "./", false);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.setRequestHeader("Req-Type", "ajax");
formdata = xEncodePair("_object", "PrefMgr")+ "&";
formdata += xEncodePair("_action", "SmtpTest")+ "&";
formdata += GetEncodedFormData();
http.send(formdata);
if(http.status == 200)
{
if(pButtonParams.IsCommandButton == true)
HandleButtonStatus(false, pButtonParams);
return (http.responseText);
}
else
{
return ("Error " + http.status + ": " + http.statusText);
}
}
function HandleButtonStatus(pIsButtonStatusChange, pButtonParams)
{
var button = yById(pButtonParams.ButtonId);
if(pIsButtonStatusChange)
{
document.body.style.cursor = "wait";
button.value = pButtonParams.ButtonText;
button.disabled = true;
}
else
{
document.body.style.cursor = "default";
button.disabled = false;
button.value = pButtonParams.ButtonOrigText;
}
}
Try to assign:
var st = document.body.style;
and then refer to st in both functions. This could be a scope issue in AJAX callback function.
EDIT: Use callback function to restore cursor shape. Don't forget to do the same in case AJAX call fails.