How to retrieve input value before submit - javascript

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

Related

ajax.post returns index html but not the html that I should get after a post

So I'm trying to build a JS script that allows me to automatically enroll in courses in uni once they're available, and what I've gotten so far is filling the boxes with course IDs and then clicking submit but then I realized using ajax to post would be a better way than simulating a click.
The problem is, the returned html after a post is just a normal html with no success msg on enrolling neither failure. Here is my code:
const courses = ['56895', '56712', '56812']
function findnewreg() {
var index = 0
courses.forEach(element => {
index++;
var ind = "crn_id" + index;
document.getElementById(ind).value = element
form = document.getElementById(ind).form
});
var regbtn = document.getElementsByName('REG_BTN')
regbtn.forEach(element =>{
if(element.value=='تنفيذ التغييرات'){
//element.click();//<form action="/PROD/xwckcoms.P_Regs" method="post" onSubmit="return checkSubmit()">
submitForm()
console.log("clicked")
document.addEventListener("DOMContentLoaded", function(event){
if (document.body.textContent.includes("لقد قمت بإجراء العديد من المحاولات لتسجيل هذا الفصل الدراسي، اتصل بمكتب التسجيل للحصول على مساعدة. ")) {
console.log('⛔️ error retrying...');
//history.back();
findnewreg()
}else{
console.log('✅ success');
}});
}
})
}
function submitForm(){
var form = form = document.getElementById("crn_id1").form
var href = '/PROD/xwckcoms.P_Regs'//form.getAttribute("action");
var formData = {};
jQuery(form)?.find("input[type=text]").each(function (index, node) {
console.log(index, node)
formData[node.name] = node.value;
});
// formData = jQuery(form).serialize() //also tried this, same result
jQuery.post(href, formData).done(function (data) {
prompt('DATA:' , data)
findnewreg();
});
}
findnewreg();

Return value from a function returns undefined

I have an html which has a form that a user could enter url if the value of the input text has www. in it i will create a variable and return it to the function then pass it to the ajax but it seems that when I check it(ajaxData var) in the console it says undefined.
<form action="" id="defaultForm">
<input type="text" id="url">
<button id="submit">Submit</button>
</form>
JS:
$(function () {
function myreturnValue() {
$('#defaultForm').submit(function () {
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match('www.')) {
console.log('it already consists of www');
var returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
return returnValue;
} else {
var returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
return returnValue;
}
}); //end submit
}
var ajaxData = myreturnValue();
console.log(typeof ajaxData);
var data = 'data:{' + ajaxData + '}';
});
then in the ajax I will pass the data variable. I hope my explanation is kinda clear.
Currently in your code, myreturnValue function only execute a code to register an event listener to your form, without return value (your return statement will only be triggered on submit event), so that's why it will return undefined at the first time.
Try this:
Put your url detect logic in myreturnValue function
Then put a code to prevent default submit event to be fired
Finally register a event listener for submit button.
And your original regex www. means match www with one other character, like wwww. and www0. will be valid. You may consider changing it to other regex like this one
$(function() {
function myreturnValue() {
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match(w)) {
console.log('it already consists of www');
var returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
return returnValue;
} else {
var returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
return returnValue;
}
}
$('#defaultForm').submit(function(e) {
e.preventDefault();
});
$('#submit').on('click', function() {
var data = 'data:{' + myreturnValue() + '}';
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="defaultForm">
<input type="text" id="url">
<button id="submit">Submit</button>
</form>
A few problems here.
Calling $('#defaultForm').submit(function () { binds a submit handler to the form. It does not submit the form nor execute the function. Please familiarize yourself with the documentation.
Your myreturnValue() doesn't return anything. You only have one top level line which is the above submit binding. Not only is it not executed, but return inside that function does not propagate up like you're expecting it to. Returning inside an event handler won't do anything in any context.
Don't declare vars inside if branches in general.
Here's a quick attempt to reorganize this code, but with this many problems the corrected code may depend on your specific needs.
(function () {
$('#defaultForm').submit(function (event) {
// prevent default form submit
event.preventDefault();
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
var value;
if (current.match('www.')) {
console.log('it already consists of www');
value = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
} else {
value = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
}
var data = 'data:{' + ajaxData + '}';
// Do whatever you want with data here
});
// If you want to now submit the form by hand...
$('#defaultForm').submit();
});
In your code, the myreturnValue() is only return the returnValue of the function in Submit. 'myreturnValue' function return anything because it doesn't any return value.
You executed unnecessary function to get the ajaxData.
To get the ajaxData, You only need to
$('#defaultForm').submit(function () {
contents
}
If fix the code simple...
$('#defaultForm').submit(function () {
var returnValue;
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match('www.')) {
console.log('it already consists of www');
returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
} else {
returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
}
console.log(typeof returnValue);
var data = 'data:{' + ajaxData + '}';
console.log('data : ', data)
});
Please, Note : http://codepen.io/onyoon7/pen/mRdJJV

Know which Form is submitted

I have eight Forms in a page (Form0, Form1, Form2 and so on). When a form is submitted, data is handed by JS and send to ReassignPreg.php, which search data in DB and send it back with json. Then the proper divs on the page are updated.
The code below is doing its job. But I have eigh copies of almost the same code, one for each Form (I only copy two of them for brevity). Newbie and amateur as I am, I wander which would be the way for synthesize this code (get Form name, and then pass that to only one function).
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox10").html(imagen)
$("#PregBox11").html(obj.Clase)
$("#PregBox12").html(obj.Dificultad)
$("#PregBox13").html(obj.Tipo)
});
return false;
});
});
</script>
A little more modularity helps a lot
$(document).ready(function () {
$("[id^=Form]").on('submit', function (e) {
e.preventDefault();
var _form = this.id.slice(-1); // 0, 1, etc
var cadena = $(this).serialize() + '&form=' + _form;
$.get('ReassignPreg.php?cadena=' + cadena, function (row) {
var image = $('<img />', {
src : "../ImageFolder/" + row.File + ".png",
width : 530
});
$("#PregBox"+_form+"0").html(image);
$("#PregBox"+_form+"1").html(row.Clase);
$("#PregBox"+_form+"2").html(row.Dificultad);
$("#PregBox"+_form+"3").html(row.Tipo);
}, 'json');
});
});
now you'll have a form key on the server containing the number of the form, for instance in PHP you'd get that with $_GET['form'] etc.
you could add an hidden field to each form with an ID/name and use that to identify the form submitting
You may need to assing classes to your PregBox elements and then target them accordingly to the form's ID.
$('form').submit(function(){ // listen to all form submissions.
var formID = $(this).prop('id'); // get the form ID here and do what you like with it.
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});

how to get data from javascript ajax from another page

I am using a script with jQuery:
$(document).ready(function () {
var button;
var line;
var inputs;
var params = {};
var updatefield;
$('button.update').click(function () {
button = $(this);
params['button'] = button.val();
line = button.closest('.line');
updatefield = line.find('td.resultFromGet');
inputs = line.find('input');
inputs.each(function (id, item) {
switch($(item).attr('type')){
case 'checkbox':{
params[$(item).attr('name')] = new Array($(item).is(':checked'));
break;
}
default:{
params[$(item).attr('name')] = new Array($(item).attr('value'));
break;
}
}
});
//alert(JSON.stringify(params, null, 4));
$.get( 'core/ajax/correct_exec.php', params )
.done(function (data){
if(data == '1'){
$(updatefield).html('UPDATE_RECORD_SUCCESS');
} else {
$(updatefield).html( data );
}
});
});
});
The page I am getting is doing echo '1'; from PHP in case of success.
I try to test this with data == 1 but it doesn't work even though it is a success. In fact, it sends me $(updatefield).html( data ); which is 1. So why can't it just print UPDATE_RECORD_SUCCESS?
The data response is coming with white space, if you use trim() function something like this, then if condition should be executed.
if(data.trim() == '1'){
$('#updatefield').html('UPDATE_RECORD_SUCCESS'); //this should be executed
} else {
$('#updatefield').html( data );
}
Here you can see the space with data in chrome debugger.

Combining 2 Javascript/Jquery scripts

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;
}

Categories

Resources