I wrote this program to help me send post request by javascript
only the elements with send class will be sent
I store all data in a variable, because this can be re-used in another ajax function.
and then use it to create form and send it out.
this can send any data in the page, not just form input element
but it cannot send file, because I don't know how to store file input element to variable, and then create input file element for that file.
Is it possible to make my program to handle file input?
function send(url)
{
var data=getData();
var form=document.createElement('form');
form.setAttribute('method', 'POST');
form.setAttribute('action', url);
for(x in data)
{
var hidden=document.createElement('input');
hidden.setAttribute('type', 'hidden');
hidden.setAttribute('name', x);
hidden.setAttribute('value', data[x]);
form.appendChild(hidden);
}
document.body.appendChild(form);
form.submit();
}
function getData()
{
var data={};
var sendNode = document.getElementsByClassName('send');
for(var x=0; x<sendNode.length; x++)
{
var node=sendNode[x];
if(node.nodeName=='INPUT')
{
var nodeType=node.type;
if(nodeType=='check')
{
if(data[node.getAttribute('name')])
{
data[node.getAttribute('name')].push(node.value);
}
else
{
var arr=[node.value];
data[node.getAttribute('name')] = arr;
}
}
else if(nodeType=='radio')
{
if(node.checked)
{
data[node.getAttribute('name')] = node.value;
}
}
else //text, password, email
{
data[node.getAttribute('name')] = node.value;
}
}
else if(node.nodeName=='SELECT' || node.nodeName=='TEXTAREA')
{
data[node.getAttribute('name')] = node.value;
}
else
{
data[node.getAttribute('data-name')] = node.innerHTML;
}
}
return data;
}
Related
I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});
Before customers can proceed to paypal, I have a quick check on the database to see if the items still available,. The problem im having is that while Ajax is executing. function check_availability continue executing and returns true to the Form onsubmit before the completion of Ajax. To fix that problem I kept calling the same function within. But I dont think that is the best possible option.
Here is the code:
<form onsubmit="return check_availability(0,0,1)" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="pp1">
function ajax_paypal(orders){
var htpr = new XMLHttpRequest();
var url = "Hi there";
var val = "orders="+orders;
htpr.open("POST", url, true);
htpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htpr.onreadystatechange = function(){
if(htpr.readyState == 4 && htpr.status == 200){
var sold_out_ids = htpr.responseText;
check_availability("continue", sold_out_ids, 0);
}
};
htpr.send(val);
}
function check_availability(str, sold_out_ids, n) {
if (str === "continue") {
if (sold_out_ids > 0) {
alert("One of your items has sold out! Sorry for any inconvenience");
location.reload();
return false;
} else {
return true;
}
}else if(n === 1){
var orders = [];
var x = document.cookie.split(';'); // your array of cookies
var i = 0;
x.forEach(item => {
//to make sure that item contains "order"
if (item.indexOf('order') > -1) {
var val = item.split("=");
orders[i] = val[1]+"o";
i++;
}
});
ajax_paypal(orders);
}
check_availability(0, 0, 0);//I keep calling this until Ajax is completed
}
You can use following code snippet to solve. This will be called on submit but before actual submit happen if you return true from here form will get submit to paypal. If you return false form won't get submit.
$('#pp1').submit(function() {
var submitOrNot=await callcheck_availability();
return true; // return false to cancel form submit
});
async function callcheck_availability(){
//your function goes here
}
for more on async await read this page on MDN
I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.
I'm having an issue where my call to $.ajax is completing successfully and returning content with a response of 200OK as reported by firebug, but the success,complete and error callbacks do not execute. This is only happening in firefox, in chrome it works fine (i am running firefox22).
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:data,success:check_salt});
var group = '';
function check_salt(d)
{
console.log(d);
The actual response for the request as reported by firebug is:
choose_login:{"admin":"Admin Zone"}
And response type:
Content-Type text/html
I have tried forcing settings like dataType and contentType in case jquery is assuming json or something and I have tried anonymous functions for the error, success and complete callbacks, but nothing works.
Am posting full function code, just in case its some kind of syntax error quirk:
function prep_login_form(elem,url,challenge)
{
function show_error(msg)
{
$(elem).find('.ecms-error-for-password .ecms-error-text').html(msg).closest('.ecms-error-container').removeClass('ecms-error-hidden');
}
function submit()
{
var data = {email:$(elem).find('input[name="email"]').val()};
data[csfr_token_name] = csfr_hash;
$.ajax({type:'POST',url:site_url+url+'/attempt_login',data:data,success:check_salt});
var group = '';
function check_salt(d)
{
console.log(d);
if (d=='no_email')
{
show_error('Invalid Email address');
}
else if (d=='account_disabled')
{
show_error('This account has been disabled, please contact your administrator');
}
else if (d.substr(0,12)=='choose_login')
{
var cl;
eval('cl = '+d.substr(13));
var cou = 0;
for (p in cl)
{
cou++;
}
if (cou==1)
{
group = p;
var mydata = $.extend(data,{group:p});
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:mydata,success:check_salt})
}
else
{
var str = '<div class="login-selection-popup"><p>We have detected that your email address is linked to more than one account.<br />Please select which zone you would like to login to.</p><ul class="choose-login-popup">';
for (p in cl)
{
str+='<li><a rel="'+p+'">'+cl[p]+'</a></li>';
}
str+='</ul></div>';
open_modal({heading:'Choose Account',content:str,buttons:function(close_modal)
{
$(this).find('.choose-login-popup').on('click','a',function()
{
group = $(this).attr('rel');
var mydata = $.extend(data,{group:$(this).attr('rel')});
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:mydata,success:check_salt})
close_modal();
});
}});
}
}
else
{
var salt = d;
var pw = $(elem).find('input[name="password"]').val();
data.password = hex_md5(challenge+hex_md5(salt+pw));
data.group = group;
$.ajax(site_url+url+'/attempt_login',{type:'POST',data:data,success:function(d)
{
if (d=='no_email')
{
show_error('Invalid username or password');//Invalid Email address
}
else if (d=='account_disabled')
{
show_error('This account has been disabled, please contact your administrator');
}
else if (d=='invalid_login')
{
show_error('Invalid username or password');//Email or Password did not match
}
else
{
window.location.href = d;
}
}});
}
}
}
$(elem).on('keyup','input',function(e)
{
if (e.keyCode=='13')
{
submit();
}
});
$(elem).find('.login-submit').on('click',function()
{
submit();
});
}
Sorry for all the trouble guys I recently had addware on my PC and battled to get rid of it. I think that it had damaged/hijacked my firefox. After re-installing firefox the problem has gone away, the callbacks now execute.
In this Code i try to get the value from text-field and dropdown listbox , I get values dynamically from user and send that value to webserices, In Given code get the value pass that values to webservice through javascript, but script didn't reponse to that code.. any one help me to fix this problem.
Here Code:
<body style=" "><script type="text/JavaScript" >
var xmlhttpuserid;
functionmyFunction() {
var checkid=new Array();
var userid = document.getElementById("userid").value;
for(var i=0;i<2;i++)
{
if(document.getElementById('domainid'+i).checked==true)
{
checkid[i]=document.getElementById('domainid'+i).value;
alert(checkid);
}
}
// var domainid = document.getElementById("").value;
//alert(userid);
var url= "../webservice/Passwordstation/ws_userauthpwdstation.jsp? userid="+userid+"&domain="+checkid;
alert(url);
xmlhttpduserid=GetXmlHttpObject();
if (xmlhttpduserid==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}
xmlhttpduserid.onreadystatechange=getuserid;
xmlhttpduserid.open("GET",url,true);
xmlhttpduserid.send(null);
}
function GetXmlHttpObject()
{
//alert("GetXmlHttpObject1");
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function getuserid()
{
if (xmlhttpduserid.readyState==4)
{
var text=xmlhttpduserid.responseText;
//alert(text);
text=text.replace(/^\s+|\s+$/g,"");
// alert("Text 2"+text);
if(text.match("SUCCESS"))
{
alert("Authenticate successfully");
window.location="accountmain.jsp";
}
else
{
alert("Please check your User id");
}
}
}
I hope this will help you .
You can get them in java script and pass them in the query as query parameter as already doing for user id .
// var domainid = document.getElementById("").value;
//alert(userid);
var textboxval = document.getElamentById("mytextbox").value;
var dropDown = document.getElementById("ddlViewBy");
var dropDownValue= dropDown.options[dropDown.selectedIndex].value;
var url= "../webservice/Passwordstation/ws_userauthpwdstation.jsp? userid="+userid+"&domain="+checkid&textboxvalue="+textboxval&selectedFromDropDown="+dropDownValue;