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;
});
Related
I am adding some data to data attr with jquery when click button
$(document).on('click','.musicButton',function(){
var genre = $('.musicPlay').last().data('genre');
var musicBox = $($('#musicBoxTemplate').html());
$(musicBox).appendTo('.allMusics');
$('.getData').last().data('music',genre);
}
Then I need when that data
$(document).on('click','.musicPlay',function(){
var data = $(this).data('genre');
var music = $('.getData[data-music=' + data + ']');
if( music.find(':first-child').attr('tagName').toLowerCase() == 'em'{
//Do some stuff
}
}
that alert me undefined. why it don't see that data when I need?
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
When a form is submitted, I want to asynchronously invoke an email-sending script order.php with some $_GET parameters.
The jQuery $.get() function doesn't execute and there are no errors displayed in console.
HTML markup:
<form name="submit" id="orderconfirm" action="somefile.php">
<input type="hidden" name="orderkey" id="orderkey" value="somekey"/>
<input type="text" name="email" id="orderemail"/>
<input type="submit" value="submit"/>
</form>
jQuery script:
$(document).ready(function() {
$('#orderconfirm').submit(function() {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
It's really strange because a similar script (also $.get() with a simple URL) works just fine. I'm also sure that the order.php script works fine and the path is correct. The problem is that somehow $.get(url) is not executed and no request is sent.
The submit handler works fine too - for example an alert worked.
Any ideas?
Prevent default browser action by using preventDefault()
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
Documentation
Also you can use return false; to restrict the form submission
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
return false;
});
});
To submit the form after $.get try this,
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url,function(){$('#orderconfirm').submit()});
});
});
Documentation
Because you don't prevent default browser behavior. Add event.preventDefault method:
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
try this
$('#orderconfirm').submit(function(e) {
e.preventDefault();
})
and use valid $.get
$.get( "order.php", {'key':key,'mail': email});
$(document).ready(function() {
$('#orderconfirm').submit(function(e) {
e.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
the problem happens with the default behavour from browser on form submission. you need to prevent the default from being executed.
optionally you can even change the type of button from 'submit' and try.
Use return false or e.preventDefault() like,
$('#orderconfirm').submit(function(e) {
e.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
You have two ways to fix this.
1.Use e.preventDefault(); to prevent browser's default behavior from submitting the form.
$('#orderconfirm').submit(function(e) { // 'e' here is new
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
e.preventDefault(); // and this line is new
});
2. Or just change the submit type to button.
<input type="button" value="submit"/>
By the way, you can get values as parameters instead of string. jQuery.get()
$('#orderconfirm').submit(function(e) {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var page = 'order.php';
$.get(page, {mail: email, key: key}); // this line
e.preventDefault();
});
Try this
$.get( "order.php", { key: key , mail: email } );
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();
}
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;
}