Save 2 Forms At the Same Time MVC 3 - javascript

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

Related

Submitting multiple html forms

I want to submit html forms present in an array. But the problem is only last form is actually posted to server. All other forms do not reach server. Any hint what I am doing wrong here?
if (numberOfRows > 0) {
for (var i = 0; i < numberOfRows; i++)
{
alert('submitting form ' + i);
submittedForms[i].submit();
}
}
}
Submitting a form with .submit() is similar to a user clicking a submit button which will result in a new page being loaded. So calling .submit() on multiple forms in the same page would equal a user clicking multiple submit buttons, what is the browser supposed to be doing then? I'm not sure if the specification documents a certain behavior, but I don't see how this could be handled generally. If all you want is that the form data reaches the server, use AJAX. For example like this when using jQuery: jQuery AJAX submit form
Thanks to #pschichtel.
I ended up using ajax to post multiple forms at once. Below is my final code:
var numberOfRows = submittedForms.length;
if (numberOfRows > 0) {
for (var i = 0; i < numberOfRows; i++) {
var formData = new FormData(submittedForms[i]); // yourForm: form selector
postFormAjax(formData);
}
deleteForms();
}
function postFormAjax(formData)
{
$.ajax({
type: "POST",
url: "https:url/servlet/servlet.WebToCase?encoding=UTF-8", // where you wanna post
data: formData,
processData: false,
contentType: false,
error: function (jqXHR, textStatus, errorMessage) {
alert(errorMessage); // Optional
},
success: function (data) {
alert(data)
}
});
}
Try this:
$('#form1').submit();
$('#form2').submit();

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

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

javascript or ajax to update database with asp.net mvc?

I have a function here from a change event on a dropdownlist. When the selection gets changed I want to update a row in my database. Should I use javascript or ajax. I don't want the page to be refreshed. I think it should be ajax, but not sure? If ajax, can anyone point me to a tutorial/video/etc?
Here is where I want to update my db row.
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function(event) {
// call db and update row
}, false);
Looks like you using asp.net mvc.
You can write your ajax calls with pure javascript Ajax docs or the easiest way, using JQuery.
You need to add one action on your controller to receive the ajax data, and then insert/update your db.
See this, this and this.
Most common scenario would be making an ajax call using HTTP POST/PUT to a controller method, which would then handle the data and update the database directly or pass through to your service/data layer code.
Probably the easiest way to make the call would be using the jQuery.ajax method. Documentation can be found here: http://api.jquery.com/jquery.ajax/
You can try something like this
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var name = $('#TextBox1').val();
var email = $('#TextBox2').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home/UpdateDB', //if it is plain asp.net then UpdateDB is declared as WebMethod
async: false,
data: "{'name':'" + name + "','email':'" + email + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#TextBox1').val('');
$('#TextBox2').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
fg
iuou
uouienter link description here
uiouidfgsdfgddfgdfgdfgdgdgd##
Heading
##*
uio
uiopomkl
hjlkdsg
dsf
dfgdg
Blockquote

simple form validation with jquery serialize() function

$(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

Categories

Resources