I'm creating a sign up page with inline validation, and having script for email availability in external file but pattern check inside the HTML using jquery but problem is css of elements doesn't change in email check script so i want to pass a variable value from external JavaScript to internal Jquery...
Help me out....
// JavaScript Document for live email availability check
function createXMLHttpRequest() {
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlhttp = false;
}
}
}
return xmlhttp;
};
function AjaxFunctionusername(signupemail){alert('call');
var mygetrequest = new createXMLHttpRequest();
mygetrequest.onreadystatechange = function() {
if (mygetrequest.readyState == 4 && mygetrequest.status == 200){
arrRecevied = mygetrequest.responseText;
alert(arrRecevied);
if (arrRecevied > 0) {
}
else {
}
}
}
pars = "";
pars = "signupemail=" + signupemail;
domainUrl = "ckh_client.php?" + pars;
alert(domainUrl);
mygetrequest.open("GET", domainUrl, true);
mygetrequest.send();
}
i want aarReceived variable's value to be passed in jQuery as shown below...
<script>
$(document).ready(function(){
//validation for invalid email ID
$("#signupemail").keyup(function(){
var msg = '';
var emmsg = '';
msg = document.getElementById('signupemail').value;
var emailReg = /^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
if (!emailReg.test(msg)) {
$(".validation-img-1").css("display", "block");
$(".validation-img-2").css("display", "none");
}
else if (emailReg.test(msg)) {
AjaxFunctionusername(msg);
}
});
//validation for invalid email ID ends here
});
</script>
Make the following changes-
function AjaxFunctionusername(signupemail){alert('call');
var arrRecevied=''; //Note the change. Do not create global vars.
var mygetrequest = new createXMLHttpRequest();
mygetrequest.onreadystatechange = function() {
if (mygetrequest.readyState == 4 && mygetrequest.status == 200){
arrRecevied = mygetrequest.responseText;
alert(arrRecevied);
if (arrRecevied > 0) {
}
else {
}
}
}
pars = "";
pars = "signupemail=" + signupemail;
domainUrl = "ckh_client.php?" + pars;
alert(domainUrl);
mygetrequest.open("GET", domainUrl, true);
mygetrequest.send();
return arrRecevied;
}
In your script,
if (!emailReg.test(msg)) {
$(".validation-img-1").css("display", "block");
$(".validation-img-2").css("display", "none");
}
else if (emailReg.test(msg)) {
var value= AjaxFunctionusername(msg);
//value is your arrRecevied
}
Related
I'm new to javascript and I'm trying to convert a functional jQuery script to pure Javascript. I tried but I failed. Overall I don't know how to "convert" '$.ajax...' in pure javascript language. Can somebody help me ?
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
var login = $('login').val();
var nom = $('nom').val();
if(login === '' || nom === '') {
alert('Fill the form correctly');
} else {
$.ajax({
url: $this.attr('action'), // call webservice
type: $this.attr('method'), // method="POST" in the form
data: $this.serialize(),
success: function(html) {
alert('User added : success'); /
window.location.href = "http://localhost:8080/games_v3/";
}
});
}
});
});
I tried this but I don't know if it is correct so far ...
var event = document.querySelector("#button").addEventListener("click", waitfunction());
function waitfunction(){
event.preventDefault();
form = document.getElementById(this);
var login = document.getElementById("login");
var nom = document.getElmentById("nom");
if(login === '' || nom === '') {
alert('Fill the form correctly');
} else {
[...]
}
}
Thank you for the help
New Edit :
I tried this with the following in my form:
<form onsubmit="return ready(fn);" [...]
And this brand new javascript:
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
function fn(){
var form = document.getElementById("form");
form.addEventListener('submit', fn2(e));
}
function fn2(e){
e.preventDefault();
var login = document.getElementById("login").value;
var nom = document.getElementById("nom").value;
if(login === '' || nom === '') {
alert('Les champs doivent êtres remplis');
} else {
var form = document.querySelector('form');
var data = new FormData(form);
var request = new XMLHttpRequest();
request.open('POST', './jeux/webservicesutilisateur/post', true);
request.setRequestHeader('Content-Type', 'application/x-www-form- urlencoded; charset=UTF-8');
request.send(data);
request.onload = function(html) {
if (request.status >= 200 && request.status < 400) {
alert('Utilisateur ajouté avec succès'); // J'affiche cette réponse
window.location.href = "http://localhost:8080/games_v3/";
var resp = request.responseText;
}
request.send();
}
}
}
But still no alert box appears, so the javascript code doesn't seems to be functional...
Hey the same problem was faced by me in one of my projects. Below code snippet helped to make ajax call in pure javascript. Hope this is what you were looking for.
/**
*
* #param url
* #param method
* #param data
* #param callback (Callback function to handle response state)
* #returns {boolean}
*/
function makeAjaxRequest(url, method, data, callback) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (!httpRequest) {
console.log('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = (function () {
return callback(httpRequest);
});
if (method && method.toUpperCase() == 'POST') {
httpRequest.open(method, url, true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
httpRequest.send(data);
} else {
httpRequest.open(method, url);
httpRequest.send();
}
}
** UPDATED CODE FOR FORM SUBMISSION **
function callbackHandler(httpRequest) {
// response has been received so handle it now
if (httpRequest.readyState === 4) {
//In case status is 200 is what you are looking for implementation
// of this will change accordingly
if (httpRequest.status >= 200 && httpRequest.status < 400) {
alert("Posted form successfully");
var resp = httpRequest.responseText;
console.log(httpRequest.responseText);
}
}
}
(function(){
document.addEventListener('DOMContentLoaded',function(){
var form = document.querySelector('form');
form.addEventListener('submit',function(e){
e.preventDefault();
var login = document.getElementById("login").value;
var nom = document.getElementById("nom").value;
if(login==='' || nom === '') {
alert('Les champs doivent êtres remplis');
} else {
var form = document.querySelector('form');
var data = new FormData(form);
var action = form.getAttribute("action");
var method = form.getAttribute("method");
makeAjaxRequest(action,method,data,handler);
}
});
});
})();
The script below should be sending an XMLHttpRequest, but is throwing the Uncaught TypeError: Cannot read property 'abort' of undefined in console when it's ran. This is for a homework assignment and I have triple checked to make sure this is the code that they are telling me to run... I cannot find any errors. But regardless, I just want this to work.
The most I can tell is that the variable 'httpRequest' is being registered as undefined... maybe it's in the function that get's assigned to it? I'm lost and don't know how to fix it.
// global variables
var selectedCity = "Tucson, AZ";
var httpRequest = false;
var weatherReport;
function getRequestObject() { // Possible function responsible for error?
try {
httpRequest = new XMLHttpRequest();
}
catch (requestError) {
document.querySelector("p.error").innerHTML = "Forecast not supported by your browser.";
document.querySelector("p.error").style.display = "block";
return false;
}
}
function getWeather(evt) {
var latitude;
var longitude;
if (evt.type !== "load") {
if (evt.target) {
selectedCity = evt.target.innerHTML;
} else if (evt.srcElement) {
selectedCity = evt.srcElement.innerHTML;
}
}
if (selectedCity === "Tucson, AZ") {
latitude = 37.7577;
longitude = -122.4376;
} else if (selectedCity === "Chicago, IL") {
latitude = 41.8337329;
longitude = -87.7321555;
} else if (selectedCity === "Montreal, QC") {
latitude = 45.5601062;
longitude = -73.7120832;
}
if (!httpRequest) {
httpRequest = getRequestObject();
}
httpRequest.abort(); // Where the error is thrown...
httpRequest.open("get","solar.php?" + "lat=" + latitude + "&lng=" + longitude, true);
httpRequest.send(null);
httpRequest.onreadystatechange = fillWeather;
}
function fillWeather() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
weatherReport = JSON.parse(httpRequest.responseText);
}
}
var locations = document.querySelectorAll("section ul li");
for (var i = 0; i < locations.length; i++) {
if (locations[i].addEventListener) {
locations[i].addEventListener("click", getWeather, false);
} else if (locations[i].attachEvent) {
locations[i].attachEvent("onclick", getWeather);
}
}
if (window.addEventListener) {
window.addEventListener("load", getWeather, false);
} else if (window.attachEvent) {
window.attachEvent("onload", getWeather);
}
You forgot to return httpRequest in getRequestObject(), so httpRequest = getRequestObject() sets it to undefined.
I am using JavaScript.
I amusing a setInterval timer method.
Inside that method I am changing the values of module variables.
The thing is in IE the changes to the variables are not 'saved'. But in Chrome they are.
What is the accepted practice to do what I need to do?
this is my code:
function start()
{
var myVar = setInterval(function () { GetTimings() }, 100);
}
var currentts1;
var currentts2;
var currentts3;
var currentts4;
var frameCounter;
function GetTimings() {
if (frameCounter < 1) {
frameCounter++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var nextts = xmlhttp.responseText;
var bits = nextts.split('|');
if (currentts1 != bits[0]) {
currentts1 = bits[0];
postMessage("0|" + bits[0]);
}
if (currentts2 != bits[1]) {
currentts2 = bits[1];
postMessage("1|" + bits[1]);
}
if (currentts3 != bits[2]) {
currentts3 = bits[2];
postMessage("2|" + bits[2]);
}
if (currentts4 != bits[3]) {
currentts4 = bits[3];
postMessage("3|" + bits[3]);
}
frameCounter--;
}
}
xmlhttp.send();
}
}
The variables:
currentts1
currentts2
currentts3
currentts4
frameCounter
values are not preserved...
Try this, but notice I changed the currentts* to an Array when you try to view them
function start() {
var myVar = setInterval(GetTimings, 100);
}
var currentts = [null, null, null, null];
var in_progress = 0; // clear name
function GetTimings() {
var xhr;
if (in_progress > 0) return; // die
++in_progress;
xhr = new XMLHttpRequest();
xhr.open('GET', urlTS);
function ready() {
var nextts = this.responseText,
bits = nextts.split('|'),
i;
for (i = 0; i < currentts.length; ++i)
if (currentts[i] !== bits[i])
currentts[i] = bits[i], postMessage(i + '|' + bits[i]);
--in_progress;
}
if ('onload' in xhr) // modern browser
xhr.addEventListener('load', ready);
else // ancient browser
xhr.onreadystatechange = function () {
if (this.readyState === 4 && xhr.status === 200)
ready.call(this);
};
// listen for error, too?
// begin request
xhr.send();
}
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.