simple form validation with jquery serialize() function - javascript

$(document).ready(function(){
$('#send').click(function() {
var names = $('#appontment_form').serialize();
//this is how my names variable look like
//doctor=Dr.Fathmath+Shahuda&date=2013-02-27&time=1900+-+1700&phone=
var doc = $(names).filter('doctor');
if(doc !='')
{
$.ajax({
type: "post",
url: "../../includes/jqueryRequireFiles/appointmentSave.php",
data:names,
success: function(data)
{
$('#confir').text('Your Appointment Received..');
}
});
return false;
}
});
});
I have a appontment form. when i click send link it will grab all the values in the textboxs and put it in the names variable through serialize() function. i want to filter the names variable and find out if any of the field is left not filled.. if only if then i will make the ajax part.. but its not working...any help

When you use $.serialize() the variable content looks like ?key=value1&key=value2. If you want to validate the form, just do it without serialize like
var found_errors = false;
if($('#formfield1').val().trim() == "") {
//Handle errors if field is empty
found_errors = true;
}
And if no errors are found, serialize the form and send it.

Consider using jQuery validation plugin.
http://docs.jquery.com/Plugins/Validation

Related

How to detect that my select form have been change by ajax success

I have two form input ( text and select form ).
The select form change by ajax success when user search the employee data.
Now, i want the other jquery function that can automatically detect when the select form have been change by ajax success and retrieve the new value of select form to use by other function to make new data in my input text.
my Search Employee Function
function search_personal_result(formObj, urlres, responseDIV, disable_data, modal_class,result_data)
{
disable_data=disable_data||false;
modal_class=modal_class||false;
result_data=result_data||false;
var loading = '<p>Loading ...</p>';
$.ajax({
url: site_url+'/'+urlres,
beforeSend: function(){
$(responseDIV).html(loading);
},
data: $(formObj).serialize(),
type: "post",
dataType: "html",
success: function(response){
//proceed data result here
if(result_data==false){
var obj = jQuery.parseJSON(response);
$.each(obj, function (index, value) {
if(result_data==false){
for(var j in value){
//My SELECT Form Changed here
$('#VCIDSBU').val('MY NEW VALUE');
}
}
});
}
},
error: function(){
alert("Terjadi kesalahan!");
},
});
}
If the user search the employee data using search_personal_result, my select form have been successfully changes.
Now that i need is, how to make the other jQuery function that can detect that my SELECT Form have been changed by search_personal_result
I have try using
$(function () {
$('#form_create_sp').on('change','SELECT#my_select_id',function(){
alert('it changes');
});
})
It can only detect when the user manually change the select form. but not working when the select form changed by search_personal_result
Thanks for all expert here
You could always do some sort of console.log("Success"); Function based on if it sent or not.

Post to PHP backend from javascript code

I have tried other answers but none have worked. The javascript code is supposed to submit a list of product id's to a php page. When products are selected, the submit button triggers the submit function.
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
console.log(ids);
//send the ids to api
bundle = [];
$('.bundle-list').empty();
$('.total').html('No item in bundle');
$('.submit').addClass('hide');
}
I have tried inserting this line in the function
document.getElementByID("test").value = bundle;
and a hidden tag within the form but can't get the var to submit to PHP
<input type="hidden" id="test" name="test" visibility="hidden"></input>
Where should the position of the hidden element be relative to the JS code? and any other methods of retrieving the ID's?
Either by $.post or $.get variable you can send data to PHP file, but i think you want to save pids in hidden field, but you are not update its value on submit. like
$('#test').html('YOUR DATA')
Try this..
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
$.ajax({
url: 'YOUR_URL HERE',
type: 'POST',
data: { qry: ids },
success: function(data) {
///WHEN SUCCESS
}
},
error: function(e) {
}
});
}

Submit form data as JSON

I have to recreate a form that was originally created using Jotform - it is here. I am struggling in one area. It is a pretty simple form, the only caveat being the ability to duplicate a form field form multiple entries. That part can be seen here. When the form is duplicated, I need to submit the form data as a JSON array. In the fiddle, I didn't put the regular form fields, here is how they and the cloned field need to submit the data.
q2_fullName[first]:test
q2_fullName[last]:test
q1_currentCommission1:[{"Instruments":"a","Commissions":"1","Margins":"a"},{"Instruments":"b","Commissions":"2","Margins":"b"},{"Instruments":"c","Commissions":"3","Margins":"c"}]
normally in my $.ajax handler, I just serialize the data, but that doesn't work in creating the json array for the cloned fields. Normally like so:
submitHandler: function(form) {
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url: form.action,
data: dataString,
dataType: "json",
beforeSend: function(data){
//before send
},
success: function(data){
//success function
}
});
return false;
},
I need to somehow serialize the non cloned fields (I think) and create a json array out of the cloned values and assign them a key name
You can build the post data and the json string like this :
var data = {
// get/set the firstname etc
"q2_fullName":{
"first":"", // get firstname ie $("#first_2").val(),
"last":""
},
"q1_currentCommission1" :""
},
commisions = [];
$('.InsContain').each(function() {
var $inputs = $(this).find('input');
commisions.push({
"Instruments" : $inputs.eq(0).val(),
"Commissions" : $inputs.eq(1).val(),
"Margins" : $inputs.eq(2).val()
});
});
data.q1_currentCommission1 = JSON.stringify(commisions);
Posted data :
q2_fullName[first]:aaa
q2_fullName[last]:123
q1_currentCommission1:[{"Instruments":"1","Commissions":"1","Margins":"1"}]
Update fiddle here

Save 2 Forms At the Same Time MVC 3

Im planning to save 2 forms but the 1st form is where i get the Foreign key for the Second form
This is my Attempt to save this Using Javascript
$("#btnSave").click(function (e) {
e.preventDefault();
$('#workForm').submit();
$('#conttForm').submit();
});
But it errors on Contact Form Submit because the ID of Worker Form is still null while saving the contact form that is its Foreign Key
i also Tried this method
$("#btnSave").click(function (e) {
e.preventDefault();
if (Id != 0) {
$('#workForm').submit();
$('#contForm').submit();
} else {
$('#workForm').submit(); }
});
But it only go at Else because the ID is 0
I hope someone can help me here
Thanks :D
jQuery's submit function actually causes the browser to send a request, i.e. you're submitting the form. To accomplish this you'll need to uses ajax. Something like this should do the trick:
$.ajax({
method: 'POST',
url: $('#workForm').attr('action'),
data: $('#workForm').serialize(),
success: function(data) {
//grab whatever id you need here
var id_thing = $(data).find('#id_here').val();
//do something with id
$('#conttForm input[name="your-hidden-id-field"]').val(id_thing);
$('#conttForm').submit();
}
})

ajax field insert without loading second page bug

So I went through this tutorial http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/ and instead of using php I created my own classic asp page, but one thing is bugging me when trying to put spaces in the input boxes they do not show up for example if I put bill gates in the name field it shows up as billgates
any ideas
$(".btn22").bind("click", function() {
var name = $("input#yourname").val();
if (name === "") {
$("input#yourname").focus();
return false;
}
var email = $("input#youremail").val();
if (email === "") {
$("input#youremail").focus();
return false;
}
var message5 = $("#limitedtextarea").text();
if (message5 === "") {
$("#limitedtextarea").focus();
return false;
}
var sku5 = $("#sku5").val();
var dataString = 'yourname='+ name + '&youremail=' + email + '&message=' + message5 + '&sku5=' + sku5;
$.ajax({
type: "POST",
url: "actions/newreview.asp",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<br><br><p class='big red'>Thanks for the review.</p>")
.hide()
.fadeIn(1500, function() {
$('#message');
});
}
});
return false;
});
});
'asp looks like this
name = request.form("yourname")
email = request.form("youremail")
sku = request.form("sku5")
comment = request.form("message")
then inserts names into a database, but it has already gotten rid of the spaces before this point
You'll have to post your markup here for us to tell what's going on for sure, but have you set the input type to type='text'?
looks like you are doing your own encoding of the form data. Not sure if that's the problem but it could be. jQuery includes a utility that does this for you.
dataString = $("#JqAjaxForm").serialize();
reference: http://api.jquery.com/serialize/
Some other comments:
you may wish to produce a javascript object, rather than just use form encoding. In this case jQuery will serialize it into json, if you use dataType:json on the post() method.
use Javascript in your classic ASP page. It may make things a little simpler for you, to use the same language on client (browser) and server.
figured it out just added name = escape(name) add the %20 in and then take it out to add spaces in my asp code
thanks everyone

Categories

Resources