Windows Location don't redirect after XMLHttpRequest - javascript

I have these code with a XMLHttpRequest:
function Registrarse()
{
conexionRegistrarse = new XMLHttpRequest();
conexionRegistrarse.onreadystatechange = procesarRegistro;
conexionRegistrarse.open('GET', 'index.php?registrarse=&username='+username+'&mail='+mail+'&pw='+contraseña+'&pwr='+repetircontraseña, true);
conexionRegistrarse.send();
}
function procesarRegistro()
{
var detalles = document.getElementById("labelUsername");
if(conexionRegistrarse.readyState == 4)
{
if((conexionRegistrarse.responseText).indexOf("cuenta") == -1)
{
window.location = "http://localhost/index.php?creada";
}
else
{
detalles.innerHTML = conexionRegistrarse.responseText;
}
}
else
{
detalles.innerHTML = "Cargando...";
}
}
The problem is that when a succesfull register happen (these occurs when the responseText of the xmlhttprequest don't have the string "cuenta"), don't redirect me to: "index.php?creada". I try with assign() and neither work.

I tested.
It works very well.
code As:
var oAjax = new XMLHttpRequest();
oAjax.open('GET', 'a', true);
oAjax.send();
oAjax.onload = function() {
if (oAjax.status == 200) {
window.location = 'http://baidu.com';
}
};
as well, check your error message!

Related

XMLHttpRequest don't include GET request

I'm trying to retrieve JSON data using XMLHttpRequest but it seems like it won't include any of my field data.
var fields = ["ID", "item_id", "item_tag", "item_name", "item_default_price", "item_quantity", "item_comment"];
function loadTable(json_items) {
alert(json_items);
}
var frm = document.querySelector("form.inventory-search-form");
frm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE && this.status == 200){
try {
loadTable(JSON.parse(this.responseText));
} catch(err) {
}
}
};
request.open('GET', '/api/inventory/list', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // Tells server that this call is made for ajax purposes.
// Most libraries like jQuery/Prototype/Dojo do this
var data = new FormData(frm);
for (i=0; i<fields.length; i++) {
data.append(fields[i], frm.querySelector("[name='" + fields[i] + "']").value);
}
request.send(data);
}
frm.onsubmit(document.createEvent("Event"));
What did I do wrong?
I have checked the FormData and it contained the fields, but it didn't make the required GET request such as /api/inventory/list?ID=2 instead it only issued /api/inventory/list.
Thanks!

Javascript check if an html file exists [duplicate]

This question already has answers here:
using javascript to detect whether the url exists before display in iframe
(8 answers)
Closed 5 years ago.
How can I check if there is an .html file in a folder exists? I'm trying to not get the error "It may have been moved or deleted." and instead display notFound.html
<body>
<header>
<form autocomplete="off">
<input id="3Digits" type="number" min="100" placeholder="3-Digit Code">
<span style="display:inline-block; width: 15px;"></span>
Go
<hr>
</form>
</header>
<div id="frameDiv">
<iframe id="srcCC"></iframe>
</div>
<script>
var newLink
function check() {
newLink = document.getElementById("3Digits").value + ".html";
if(newLink == ".html") {
alert("You forgot to put the 3-Digit Code");
}
else {
LinkCheck(newLink);
}
}
function LinkCheck(url) {
if(HTML EXISTS) {
document.getElementById("frameSRC").src = newLink;
}
else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
</script>
</body>
The function LinkCheck is what I'm asking for, all the files are going to be in the same directory.
This is a small school project, so any help would be appreciated!
You can use XMLHttpRequest to check if the file exists
function LinkCheck(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Replace your function with this:
function LinkCheck(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.getElementById("frameSRC").src = newLink;
} else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
};
xhr.send(null);
}
Option 2: use jQuery ajax
function LinkCheck(url) {
$.ajax({
url: url,
success: function(data) {
document.getElementById("frameSRC").src = newLink;
},
error: function(data) {
document.getElementById("frameSRC").src = "notFound.html";
},
})
}
Try replacing your function LinkCheck with this:
function LinkCheck(url) {
const http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) { // if (HTML EXISTS)
document.getElementById("frameSRC").src = newLink;
} else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
http.open('get', url, true);
http.send();
}
If that says some deprecation issue try the new javascript native fetch API:
function LinkCheck(url) {
fetch(url).then(function(response) {
if (response.status === 200) {
document.getElementById("frameSRC").src = newLink;
} else {
// this else isn't needed but you can put it here or in the catch block
document.getElementById("frameSRC").src = "notFound.html";
}
})
.catch(function (err) {
throw err;
});
}

validate multiple ajax call complete successfully in javascript

In my application i'am making two ajax call for getting some data from database based on another variable value.
code part:
var xmlHttp;
var redirect;
function populate_site(obj, passedselect) {
xmlHttp = GetXmlHttpObject();
var site_type;
if (obj.value) {
site_type = obj.value
}else {
site_type = document.app.site_type.value;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Get_Site_List";
url=url+"&site_type=" + site_type;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged() {
if (xmlHttp.readyState == 4){
document.getElementById('site_id').innerHTML = xmlHttp.responseText;
}
}
function Populate_Process_List(obj, process_id_param) {
var action_id;
if (obj.value) {
action_id = obj.value
}else {
action_id = document.app.action_id.value;
}
xmlHttp = GetXmlHttpObject();
if (obj.value == '') {
document.getElementById('process_id').innerHTML = ' ';
return false;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Fetch_User_Process_List";
url=url+"&action_id=" + action_id;
url=url+"&process_id=" + process_id_param;
url=url+"&gp_flag=" + 'YES';
xmlHttp.onreadystatechange= Process_Data_StateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function Process_Data_StateChanged() {
if(xmlHttp.responseText != 'NA') {
if (xmlHttp.readyState == 4){
document.getElementById('process_id').innerHTML = xmlHttp.responseText;
}
}
}
function GetXmlHttpObject(){
var xmlHttp1=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp1=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp1=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp1;
}
And validating site_id and process_id variable using JavaScript.
Problem facing is whenever user press the submit button before ajax call loading is not completed (since me passing async parameter of the open() method has as true). Even while validating the site_id and process_id variable using JavaScript is not getting captured.
Validation code:
var siteaddindex = document.app.site_id[document.app.site_id.selectedIndex].value;
if(siteaddindex == "null"){
alert("Please select site location.");
document.app.site_id.focus();
return false;
}
var process_id = document.app.process_id.value;
if (process_id == '') {
alert("Please select process");
return false;
}
Please let me know how to perform validation of above fields, since those fields are mandatory.

Display server message after form submission without JQuery

I have a form that is supposed to display a feedback message from the server once it is submitted in <div id="resposta"></div>
I can't use JQuery on my page because it is also using Mootools and it's really a mess to avoid the conflicts with those two (I tried all sorts of things I don't to bother you with). Therefore, I must use pure JavaScript here.
Once the form is submitted (after validation) it calls the function getResposta below:
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
};
function getResposta(){
var resposta = document.getElementById("resposta");
var request = getXmlHttp();
request.open("POST", "thanks.php", true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState != 4) return;
if (request.status == 200) {
resposta.innerHTML = '<p>' + request.responseText + '</p>';
} else {
alert("Erro: "+request.statusText);
}
};
}
}
thanks.php:
<?php
echo "thank you";
?>
It seems that thanks.php isn't being called, although the form is correctly filled in and sent to the server.
I've tried typing in the absolute path to the file but it didn't work. So, what is wrong with this code?
Thanks for any help!

Timeout method after hitting the url

We have the following method to invoke the URL using ajax.
Currently after hitting the url we are using the response.
So we want to put a timeout for reposne.So when we invoke the url if the response didn't came after 2sec then call one more method and if resp comes within two seconds call other mehtod.
We have tried using the timeout,but unable to made it working with the code.
function ajaxCall(url1) {
var ajaxresp = null;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url1, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
ajaxresp = xmlhttp.responseText;
//function call
getAdResponse(ajaxresp);
}
}
}
}
Please advice me how to proceed.
Try smth like this
xmlhttp.open("GET",url1,true);
xmlhttp.onreadystatechange= function (){
if (xmlhttp.readyState==4){
if (xmlhttp.status == 200){
ajaxresp = xmlhttp.responseText;
}
}
xmlhttp.send();
setTimeout(function() {
if(ajaxresp) {
dosmth(ajaxresp);
} else {
dosmthelse();
}
}, 2000);

Categories

Resources