Second AJAX function fails when other AJAX function has already been executed - javascript

I have a file that shows a bunch of orders, each of which has a button with an ajax function that sends an email. Aside from that, every 30 seconds another ajax function runs and searches for new orders and loads them on top. When I first load the page, the send mail function works just fine. But once the function that searches for new orders has been executed for the first time, when I click the button that fires the mail ajax function, it doesn't send it and reloads the page
I have checked for repeated variable and function names that might conflict but there's none. The functions work just fine on their own, only when the order-searching one has been executed the other one starts to fail
this is the simplified html code for each form (there are many orders on the page with different ids)
<form role="form" id="contactForm4081">
<div class="form-group fg4081">
<label for="message" class="h4 ">Tiempo de entrega</label>
<!-- <textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea> -->
<input type="hidden" value="Santiago" name="name4081" id="name4081" />
<input type="hidden" value="contacto#nodorojo.com" name="email4081" id="email4081" />
<select name="message4081" id="message4081" required>
<option value="15">15 min</option>
<option value="30">30 min</option>
<option value="45">45 min</option>
<option value="60">60 min</option>
</select>
<button type="submit" id="form-submit" class="btn btn-default btn-md pull-right ">Enviar mail</button>
</div>
<div id="msgSubmit4081" class="h4 text-center hidden">Tiempo de entrega enviado.</div>
</form>
this is the mail function
$("#contactForm4081").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm4081();
});
function submitForm4081(){
// Initiate Variables With Form Content
var name4081 = $("#name4081").val();
var email4081 = $("#email4081").val();
var message4081 = $("#message4081").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name4081 + "&email=" + email4081 + "&message=" + message4081,
success : function(text){
if (text == "success"){
formSuccess4081();
}
}
});
}
function formSuccess4081(){
$( "#msgSubmit4081" ).removeClass( "hidden" );
$( ".fg4081" ).addClass( "hidden" );
}
and this is the function that looks for new orders
var ultimoid = 4081;
var xultimoid = "";
function nuevospedidos() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "cosito3.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#contenidogral');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval( nuevospedidos, 30000);

Instead of -
$("#contactForm4081").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm4081();
});
Try with this -
$(document).on("submit","#contactForm4081",function(event){
event.preventDefault();
submitForm4081();
});

Related

checking object for blank values and show errors

I am trying to figure out how I can check if any values in the object are blank, and then show the corresponding error.
The form inputs look like this:
<form role="form" action="home.php" class="addLaneForm" id="addLaneForm" name="addLaneForm">
<label for="addlanepartnercode">Partner Code</label><span id="addlanepartnercodeError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnercode" placeholder="Enter Partner Code" />
<label for="addlanepartnername">Partner Name</label><span id="addlanepartnernameError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnername" placeholder="Enter Partner Name" />
<label for="addlaneipicy">IPI/CY</label><span id="addlaneipicyError" class="text-danger laneError" style="display:none;"> * </span>
<select class="form-control validation" id="addlaneipicy">
<option></option>
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
// few more inputs and selects
<button type="button" class="btn btn-default btn-flat addLaneSubmit" id="addLaneSubmit" name="addLaneSubmit">Add</button>
</form>
Here is the onClick event:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let ipiCy = $('#addlaneipicy').val();
let addlane = new ProcessLane();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
ipiCy: ipiCy
}
// how I typically would check the values below:
if(addlanecriteria.partnerCode == ""){
$('#addlanepartnercodeError').show();
return false;
}
if(addlanecriteria.partnerName == ""){
$('#addlanepartnernameError').show();
return false;
}
else{
addlane.addLaneProcessing(addlanecriteria);
}
});
The way I typically check the values is redundant and time consuming.
I did add a class to the inputs called 'laneError'. I was trying to use that to display the errors by calling a function, as follows:
function showAllErrors(){
if($(".addLaneForm .validation") == ""){
$('.laneError').show();
}
}
For one, I wasn't sure where I could put the function call.
But when I was able to call the function, I can only get the first error to show, which is "addlanepartnercodeError".
There has to be a simpler way to check the values in the object.
You can just have a reusable function like below:
showErrorMsg(elemId) {
if($.trim($('#' + elemid).val()) === '') {
$('#' + elemId + 'Error').show()
return true;
}
return false;
}
So your code would just be:-
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let Error = false,
addlane = new ProcessLane();
$('form')
.find("input[id^='add']")
.each((i , e){
if(!Error) {
Error = showErrorMsg($(e).attr('id'))
}
})
if(!Error) {
// Your form has no errors , do your thing here
addlane.addLaneProcessing(addlanecriteria);
}
});

Keep getting null on create user

Hello guys i have this php jquery ajax create user form that passes the create details to the php script but i keep getting null on the post variables anyhelp would be appreciated! code below
Html:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*" id="createUserPass">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" id="createUserPass">
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control"><option value="yes">Ja tak!</option><option value="nej" selected="">Nej tak</option></select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
jquery:
$(document).ready(function(){
$("#submitCreateUser").click(function(){
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#createUserPassC").val();
var newsletter = $("#newsletter").val();
$.ajax({
type: "POST",
url: "createuserajax.php",
data: "username="+username+"&email="+email+"&pass="+pass+"&cPass="+cPass,
success: function(html){
if(html=='true')
{
alert(username);
}
else
{
}
},
}
);
});
});
PHP:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
var_dump($username);
$securePassword = md5(($password));
$sqlInsertUser = "INSERT INTO users (username,email,password) VALUES ('$username','$email','$securePassword')";
$result = mysqli_query($con,$sqlInsertUser);
As adeneo says, your html form is likely being submitted the standard way before the ajax call is made because you haven't prevent the default behaviour. try the below instead:
Alternatively, you could remove <input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!"> and give the id="submitCreateUser" to some other element like a custom button or link. When you click and input tag with the type submit it will submit the accompanying form the normal way by default. This happens before the click handler hears the click so the form is submitted before your code call the ajax. Use a different element for the click and this wont happen
And don't forget for this to work at all, your php file must echo something which will be returned in your html variable, without that html will never be true and nothing will ever happen.
Part of your problem is that your input elements, specifically the ones for the password and password checks both have two separate id tags the first is duplicated and the second is a different id altogether. Also in your jquery, when you try to get the id check value you use another, different, id.
Here is a test page that address all of these issues and works as expected:
http://dodsoftware.com/sotests/createuserajax.html
The test php code:
<?php
if( isset($_POST) )
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
echo 'username --'.$username.', email --'.$email.', password --'.$password;
}
?>
The html code:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" >
<!-- these lines had duplicated id tags-->
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control">
<option value="yes">Ja tak!</option>
<option value="nej" selected="">Nej tak</option>
</select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
The jQuery code:
<script>
$(document).ready(function() {
$("#submitCreateUser").click(function( event ) { // add event var here
event.preventDefault(); // add this line to stop the form from submitting the normal way before the ajax call
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#confirmUserPass").val(); // you were using "#createUserPassC" here in error
var newsletter = $("#newsletter").val();
var datastring = "username=" + username + "&email=" + email + "&pass=" + pass + "&cPass=" + cPass +"&newsletter=" + newsletter;
$.ajax({
type: "POST",
url: "createuserajax.php",
data: datastring,
success: function(html) {
if (html) { // changed this line from "if (html == 'true')" just for testing
alert(html); // changed this line from "alert(username);" just for testing
} else {
alert('something went wrong!');
}
},
});
});
});
</script>

Form Validation in a pop up window

Hi I am displaying a pp up window based on the value stored in a localStorage.In the pop up window there is a form containing email and password.The user has to enter his email and password.Now what I need is that, the email entered by user has to be sent to a url and the url returns a status(either 1 or 0).If the url returns 1 then the user can just continue with the log in process.Otherwise an error message should be shown.The url is in the format http://www.calpinemate.com/employees/attendanceStatus/email/3".Here in the place of email highlighten should come the email entered by user in the form.In this way I have to pass the email.In this way I am doing form validation.But I don't know how to do.
Here is my userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" />
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
This is the form in the pop up window
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
login();
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
function login(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
localStorage.username=userStr;
localStorage.password=pwd;
}
else{ alert('error');}
}
}
});
var url = urlPrefix + encodeURIComponent(userStr) + urlSuffix;
req.open("GET", url);
req.send(null);
}
});
This is my javascript.When the user presses the log in button,whatever the user enters in the email textbox gets stored in localStorage.username.Now what I need is that I have to check whether such an email id exists by passing the email to the above specified url.And if it exists only it should be stored in localStorage.username.Please anyone help me. I have tried using the above code.But noting happens.Please help me
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
It is a contact form. You can change it to validation.
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.

Sending parameters with ajax not working

I'm trying to send some variables using ajax to a php page and then displaying them in a div but it isn't working.
Html code :
<div id="center">
<form>
<input type="text" id="toSearch" class="inputText" title="Search for ...">
<select name="thelist1" id="ecoElem" class="comboBox">
<option>-- Ecosystem Element --</option>
</select>
<select name="thelist2" id="ecoActor" class="comboBox">
<option>-- Ecosystem Actor --</option>
</select>
<input type="button" value="Search" id="searchButton" onclick="loadData();">
</form>
</div>
<div id="resBox">
</div>
The loadData function :
function loadData(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
searchT = document.getElementById('toSearch').value;
ecoElem = document.getElementById('ecoElem').value;
ecoActor = document.getElementById('ecoActor').value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('resBox').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","databaseRead.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("text=" + searchT + "&elem=" + ecoElem + "&actor=" + ecoActor);}
and finally the php page :
<?php
$searchT = $_POST['text'];
$ecoElem = $_POST['elem'];
$ecoActor = $_POST['actor'];
echo $searchT;
?>
That's it , I've been working on this for a few hours but still can't figure it out.
Try changing the button so that the onclick return false (in case that is submitting the form)...
<input type="button" value="Search" id="searchButton" onclick="loadData();return false;">
Also, you might want to URL encode the values from the textbox, otherwise somebody entering a = or a & will mess it all up...
xmlhttp.send("text=" + encodeURIComponent(searchT) + "&elem=" + + encodeURIComponent(ecoElem) + "&actor=" + + encodeURIComponent(ecoActor));}
You could also use JQuery.
function loadData(){
var searchT = $('#toSearch').val();
var toSearch = $('#ecoActor ').val();
var ecoActor = $('#ecoActor').val();
$.post("databaseRead.php"),{ text:searchT, elem:toSearch, actor:ecoActor },
function(data){
$('#resBox').html(data);
});
}

jquery post undefined in firebug

On 2 of my elements in a form, I am receiving 'undefined' in firebug. I have tried to trace the error, but keep hitting a brick wall, hence the post. One of the areas with the error is in the divId block and the other is the #company in the form. I would be grateful if someone could check my code and point out my error. Thanks
// Function to add box
function addbox() {
$("#boxform").dialog({
autoOpen: false,
resizable: true,
modal: true,
title: 'Submit a box intake request',
width: 470,
beforeclose: function (event, ui) {
$("#addbox").html("");
$("#divId").html("");
}
});
$('#boxsubmit').click(function () {
var company = $('.company').val();
var box = $('.box').val();
var service = $('#service').val();
var authorised = $('.authorised').val();
var address = $('.address').val();
var data = 'company=' + company + '&box=' + box + '&authorised=' + authorised + '&service=' + service + '&address=' + address;
$.ajax({
type: "POST",
url: "boxesadd.php",
data: data,
success: function (data) {
$("#boxform").get(0).reset();
$('#addbox').html(data);
//$("#form").dialog('close');
$("#flex1").flexReload();
}
});
return false;
});
$("#boxform").dialog('open');
}
html
<script language="javascript" type="text/javascript">
$(function() {
$("#company").live('change', function() { if ($(this).val()!="")
$.get("../../getOptions.php?customer=" + $(this).val(), function(data) {
$("#divId").html(data); }); });
});
</script
<form id="boxform" method="post" class="webform" name="boxform" />
<label for="company">Select a Company:</label>
<select name="company" id="company" />
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
<!--- displays the address from the change function -->
<div id="divId"></div>
Try changing
<form id="boxform" method="post" class="webform" name="boxform" />
to
<form id="boxform" method="post" class="webform" name="boxform">
and
<select name="company" id="company" />
to
<select name="company" id="company">
and
var company = $('.company').val();
to
var company = $('#company').val();
<select name="company" id="company" /> should be <select name="company" id="company">
Then form tag is also not closed correctly.
In your #boxsubmit click handler, you use dot instead of hash for #company.
Change
var company = $('.company').val();
to
var company = $('#company').val();
and remove the self close / on non-empty elements.

Categories

Resources