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);
}
});
});
})();
Related
I tried to create AJAX function but it shows noting in output
var ajaxObj = function(url, meth, data = "") {
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
this.responseAjax = this.responseText;
}
}
x.open(meth, url, true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.send(data);
}
function showHint(str) {
var xhttp = new ajaxObj("gethint.php?q=" + str, "GET");
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
document.getElementById("txtHint").innerHTML = xhttp.responseAjax;
}
<!DOCTYPE html>
<html>
<body>
<h3> Start typing a name in the input field below :</h3>
<form action="">
First Name : <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions:
<sapn id="txtHint"></sapn>
</p>
</body>
</html>
I tried to get suggested Names from gethint.php file when user starts typing into text box.
But it seems that responseAjax gets value after showHint() call please help me.
You need to handle the AJAX request asynchronously. In your showHint function when you call
document.getElementById("txtHint").innerHTML = xhttp.responseAjax;
the AJAX call has not yet returned, so the xhttp.responseAjax object is not yet defined. You need to wait to handle the response once it arrives. You can pass a callback function in to the ajaxObj definition, and the object will call that function when it gets its response.
var ajaxObj = function(url, meth, callback, data = "") {
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
// we're ready to handle the response data now
callback(x.responseText);
}
}
x.open(meth, url, true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.send(data);
}
// Callback function to be invoked when AJAX is complete
function fillTxtHint(responseHtml)
{
document.getElementById("txtHint").innerHTML = responseHtml;
}
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
}
// Pass in the callback function to be invoked when AJAX has returned
ajaxObj("gethint.php?q=" + str, "GET", fillTxtHint);
}
this inside onreadystatechange's handler is an instance of XMLHttpRequest so the line this.responseAjax = this.responseText is adding a field to the XMLHttpRequest object and setting its value to another field in the same object. This is completely redundant. In showHint, xhttp is an instance of ajaxObj and there is no responseAjax field ever defined for this object. You can directly set innerHTML of the element that shows suggestion inside the handler of onreadystatechange like the following:
function getSuggestions (meth, data) {
meth = meth.toUpperCase();
var params = "q=" + data;
var url = (meth == "GET") ? "gethint.php?" + params : "gethint.php";
var elem = document.getElementById("txtHint");
if (data.length == 0) {
elem.innerHTML = "";
return;
}
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
elem.innerHTML = this.responseText;
}
}
x.open(meth, url, true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (meth == "GET") {
x.send();
} else {
x.send(params);
}
}
and showHint becomes:
function showHint(str) {
getSuggestions ("GET", str);
}
here is my ajaxHandler i want to convert this to native javascript i.e
using XMLHttpRequest but i am unable to understand how to convert.`
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
Paper.giffyLoading.style.display = 'block';
if (!attributes.nopopup) {
if (attributes.loadmsg) {
Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
attributes.loadmsg = null;
}
}
$.ajax(attributes);
}
}
i have try to convert the above code like this
XMLRequestDefaultHandler = function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'index.php/request', true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {
} else {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
}
};
xmlHttp.send(null);
}
I extracted ajax function of Jquery, to work without jquery.
And replace $.ajax(attributes); to ajax(attributes);
JQuery's ajax function, without JQuery :
function ajax(option) { // $.ajax(...) without jquery.
if (typeof(option.url) == "undefined") {
try {
option.url = location.href;
} catch(e) {
var ajaxLocation;
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
option.url = ajaxLocation.href;
}
}
if (typeof(option.type) == "undefined") {
option.type = "GET";
}
if (typeof(option.data) == "undefined") {
option.data = null;
} else {
var data = "";
for (var x in option.data) {
if (data != "") {
data += "&";
}
data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
};
option.data = data;
}
if (typeof(option.statusCode) == "undefined") { // 4
option.statusCode = {};
}
if (typeof(option.beforeSend) == "undefined") { // 1
option.beforeSend = function () {};
}
if (typeof(option.success) == "undefined") { // 4 et sans erreur
option.success = function () {};
}
if (typeof(option.error) == "undefined") { // 4 et avec erreur
option.error = function () {};
}
if (typeof(option.complete) == "undefined") { // 4
option.complete = function () {};
}
typeof(option.statusCode["404"]);
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
else { xhr = new XMLHttpRequest(); }
} else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }
xhr.onreadystatechange = function() {
if (xhr.readyState == 1) {
option.beforeSend();
}
if (xhr.readyState == 4) {
option.complete(xhr, xhr.status);
if (xhr.status == 200 || xhr.status == 0) {
option.success(xhr.responseText);
} else {
option.error(xhr.status);
if (typeof(option.statusCode[xhr.status]) != "undefined") {
option.statusCode[xhr.status]();
}
}
}
};
if (option.type == "POST") {
xhr.open(option.type, option.url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(option.data);
} else {
xhr.open(option.type, option.url+option.data, true);
xhr.send(null);
}
}
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
}
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 did find some javascript/activex code in a project, called when leaving a page (window.onbeforeunload):
My project is reachable at the address
www.someaddress.itdoesntexists/MyProjectName/page.jsp
When the logout function is called, the action in the page logout.jsp is correctly performed but at the end of the process the user is redirected to
www.someaddress.itdoesntexists
instead of
ww.someaddress.itdoesntexists/MyProjectName/
The code:
<script type="text/javascript">
var loggedout = false;
bVer = parseInt(navigator.appVersion);
bName = navigator.appName;
browserIE = bName == "Microsoft Internet Explorer";
browserNS = bName == "Netscape";
function sendHttpRequestSubmit (http_request, parameters) {
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function httpRequest(url, mime, callback, async, parameters) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) http_request.overrideMimeType(mime);
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Unable to create a XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
if (callback != null) callback(http_request);
} else alert('There is a problem with the request "' + url + '"');
}
}
async = async == null ? true : async;
http_request.open('POST', url, async);
if (parameters != null) sendHttpRequestSubmit(http_request, parameters);
else http_request.send(null);
if (browserNS && !async) {//
if (callback != null) callback(http_request);
}
}
function logout () {
var sg;
if (!loggedout)
httpRequest ("logout.jsp?js=1", "text/javascript", function (http_request) {
sg = eval(http_request.responseText);
}, false);
loggedout = true;
return sg;
}
window.onbeforeunload = logout;
Can someone explain to me where to tell the script that it doesn't have to go to the root path?
The script doesn't directly declare the redirect - it simply handles a response from an AJAX call to logout.jsp?js=1 by evaluating it as a function - I would guess that you'll need to modify that response text (so outside of the script you've posted) to get it to redirect to the location you want.