Combining 2 Javascript/Jquery scripts - javascript

Im having a issue, I need to combine 2 scripts together. One of which is a validation and the other is variables/ajax script. I tried but i cannot get it to work. I put it within the script under the area that checks if it has the needfilled element attached however it submits without executing the ajax call.
Script 1:
$(document).ready(function(){
$("#loading").hide();
// Place ID's of all required fields here.
required = ["parentFirstName", "parentLastName", "parentEmailOne", "parentZip"];
// If using an ID other than #email or #error then replace it here
email = $("#parentEmailOne");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Script 2:
// Form Varables
var parentFirstNameVal = $("#parentFirstName").val();
var parentLastNameVal = $("#parentLastName").val();
var emailaddressVal = $("#parentEmailOne").val();
var parentPhoneVal = $("#parentPhone").val();
var parentAddressVal = $("#parentAddress").val();
var parentAddressContVal = $("#parentAddressCont").val();
var parentCityVal = $("#parentCity").val();
var parentStateVal = $("#parentState").val();
var parentZipVal = $("#parentZip").val();
var parentListenVal = $("#parentListen").val();
var codeVal = $("#code").val();
var getUpdateVal = $("#getUpdate").val();
input.removeClass("needsfilled");
$("#message-space").html('<br /><br /><span class="greenText">Connected to Facebook.</span><br />');
$("#loading").show();
var counter = 0,
divs = $('#div1, #div2, #div3, #div4');
function showDiv () {
divs.hide()
.filter(function (index) { return index == counter % 3; })
.show('fast');
counter++;
};
showDiv();
setInterval(function () {
showDiv();
}, 10 * 600);
alert(parentFirstNameVal);
$.ajax({
type: "POST",
url: "includes/programs/updateEmailsTwo.php",
data: "parentFirstName="+parentFirstNameVal+"&parentLastName="+parentLastNameVal+"&UserEmail="+emailaddressVal+"&parentPhone="+parentPhoneVal+"&parentAddress="+parentAddressVal+"&parentAddressCont="+parentAddressContVal+"&parentCity="+parentCityVal+"&parentState="+parentStateVal+"&parentZip="+parentZipVal+"&parentListen="+parentListenVal+"&code="+codeVal+"&getUpdate="+getUpdateVal+"&ref=<?php echo $_SESSION["refid"]; ?>",
success: function(data){
$("#message-space").html('<br /><br /><span class="greenText">Complete</span><br />');
divs.hide()
}
});

In addition to the suggestions that #JeffWilbert gave, I am going to follow it up with some more suggestions to make your code a bit more cleaner and efficient.
First, just like you did in script 1, where you have an array of field names, you can do the same for script 2. Below is an example of what you can do make your code a bit more readable.
var fields = ['parentFirstName', 'parentLastName', 'parentEmailOne', 'parentPhone'];
var fieldsValue = [], dataString;
for(i = 0; i < fields.length; i++){
fieldsValue.push(fields[i] + "Val=" + $('#' + fields[i]).val());
}
dataString = fieldsValue.join("&");
Second, If Script 2 is not dependent on any variable declared from Script 1, I would convert Script 2 into its own function and call it from Script 1. I think adding all that code inside the else like Jeff suggested is not best.
function Script2(){
//Script 2 Code
}
$("#theform").submit(function(){
//Call Script 2
});
And Third, If you are going to submit the form via AJAX and not through its default method, I would recommend using .preventDefault and then handle the flow of the submission inside the event handler function.
$("#theform").submit(function(e){
e.preventDefault();
//rest of your code here.
});

The code in script 2 needs to go inside script 1 where I marked below with a comment; if your code in script 2 is submitting the form via ajax call then you don't need to return true if no errors are found, by doing so your telling the form to submit normally.
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
// SCRIPT 2 CODE HERE BEFORE THE RETURN
// If the ajax call in script 2 is submitting your form via ajax then change
// the line below to return false so your form doesn't submit
return true;
}

Related

Is there a way to stop Form from executing action and wait for ajax to complete executing?

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

Javascript function "does not exist". Bad syntax but can't see it

The javascript is supposed to handle form submission. However, even if called with
script src="js/registerform.js"> Uncaught ReferenceError: sendreg is not defined .
The function is called onclick. Can be reproduced on www.r4ge.ro while trying to register as well as live edited. Tried jshint.com but no clue.
I will edit with any snips required.
function sendreg() {
var nameie = $("#fname").val();
var passwordie = $("#fpass").val();
var emailie = $("#fmail").val();
if (nameie == '' || passwordie == '' || emailie == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/register.php", {
numeleluii: nameie,
pass: passwordie,
mail: emailie
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
setTimeout(fillhome, 1000);
});
}
}
function sendpass() {
var oldpassw = $("#oldpass").val();
var newpassw = $("#newpass").val();
if (oldpassw == '' || newpassw == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
xoldpass: oldpassw,
xnewpass: newpassw
}, function(data2) {
alert(data2);
$('#passform')[0].reset(); // To reset form fields
});
}
}
function sendmail()
{
var curpass = $("#curpass").val();
var newmail = $("#newmail").val();
if (curpass == '' || newmail == '')
{
alert("Please fill all the forms before submitting!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
curpass: curpass,
newmail: newmail
}, function(data3) {
alert(data3);
$('#mailform')[0].reset(); // To reset form fields
});
}
}
I'm guessing here but... I imagine you are doing something like
...<button onclick="sendreg">...
And you have your <script> in the bottom on the code. Just put them on top or use $("#mybtn").click(sendreg)
Try using $("#mybtn").click(sendreg) instead of inline onclick.
The script wasn't called in the html. sorry for wasting time. A simple
<script src="js/registerform.js"></script> Fixed it.
There is no syntax error there, and I don't see any such error when trying the page.
The error that you get is that you can't make a cross domain call. Do the request to the same domain:
$.post("http://www.r4ge.ro/php/register.php", {
or:
$.post("/php/register.php", {

How to retrieve input value before submit

I have to retrieve three input values before submitting so I can use ajax to fill in the form depending on the information inside these boxes.
I first check that the three boxes have text using this script:
<script>
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
var direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
});
});
</script>
What I need is that when these three fields have a value to retrieve that value so I can pass it through a URL in PHP before submitting (ajax maybe?)
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
$value would be the variable (direccion) which is in the script.
If you need more information please let me know.
You need to set the variable as global to access it outside.due to declaring it in change, the scope of variable remains within change function only. so declare the variable outside change event.like this:
<script>
jQuery(document).ready(function () {
var flag = false;
var direccion="";//declare variable
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');//define variable on every on change
}
});
});
</script>
On your form you can add an onsubmit attribute which will define an action to take when the form is submitted.
eg :
<form method='GET' action='' onsubmit='doAjax();return false;'>
<input type='text' id='inp_name' value='hello'/>
</form>
<script>
function doAjax(){
alert("this form won't be posted!");
return false;
}
</script>
you need to make a ajax call to the url which is constructed
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
var direccio="";
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
$.ajax({
url: "target.php",
data:{'value':direccion},
success: function(response) {
//process the data received from server script
});
});
});
PHP CODE(target.php):
$value=$_POST['value'];
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
//further processing of data at server end and finally echo the data to client
You need to do it with your last desired input tag. Suppose you want data up to the 3rd input tag then you need to Call your custom function in the 3rd input tag with onkeyup="myFunction()"
In myFunction() you can check if the fields are populated or not and can also do the ajax to transfer the data to server

How to rewrite and submit form at same time

There is a form that i want to submit and url rewrite at the same time. I can change url by adding onsubmit="rewrite_form(event);" option in form :
function rewrite_form(e) {
var form = document.forms[0]; // .getElementById("form1");
window.location = '/search/' + form.f.value + '_' + form.t.value + '.htm/' + form.amt_from.value;
if (e && e.preventDefault) { e.preventDefault(); }
return false;
}
Url changes but other values of form not posted to url generated page.
Just change the form's action property instead.
function rewrite_form(e) {
var form = documen.forms[0];
form.action = 'newurl';
//rest of code, make sure not to call e.preventDefault(); or return false
//because the form will not get submitted
}
i got the solution:
function rewrite_form() {
//Create custom link here
----------------------------
----------------------------------
//create form submit action
var url = '/search/' +'your custom link';
document.getElementById('FormId').action = url;
document.FormId.submit();
}

$("#submit").click not working :/

I've tried everything I can think of to get this "send" button to work, but I'm not very good at javascript :(
http://www.kimscakes.biz/contactme.php
Prehaps someone here can tell me where i'm going wrong?
Many thanks
Gem
You are binding the submit before the element exists, move the code after the form or put it inside $(document).ready:
jQuery(document).ready(function () {
jQuery("#submit").click(function () {
console.log("button clicked");
// declare these vars
var name = jQuery("#name");
var email = jQuery("#email");
var message = jQuery("#message");
var human = jQuery("#human");
var success = jQuery("#success");
var error = jQuery("#error");
// reset these vars
success.html("");
error.html("");
// ajax call to script.php
jQuery.getJSON("mailer.php", {
name: name.val(),
email: email.val(),
message: message.val(),
human: human.val()
}, function (html) {
// if html from script.php == 1, happy days
if (html == '1') {
jQuery("#contact").hide()
success.html("Thank You, your message has been sent.")
error.show()
}
else {
error.html(html)
}
});
});
});

Categories

Resources