generic ajax form submission - javascript

ajax/javascript problem:
I have an app which consist of multiple forms. What i want to achieve is to make a generic js function to submit forms to their respective controllers by getting form id.. I m successfully getting form ids in form_id variable but m unable to use them. I tried replacing $('patient_form') with form _id and got following error: TypeError: form_id.on is not a function
Here is the following code for better understanding of the problem:
$(function () {
var form = document.getElementsByTagName("form");
var form_id = "'#" + form[0].id + "'";
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
});

The way you have it form_id is a string.
Try:
var form_id = $("#" + form[0].id);

$.ajax is a jquery function. If you want to use jquery (which in this case I think you should), then do it as follows:
$('form').on('submit', function () {
$(this).preventDefaults();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});

In addition to the other answers, you want to keep your form ID dynamic, right, so you can insert whatever values you want?
$(function () {
var form = document.getElementsByTagName("form");
// note you have to convert to jQuery object
var form_id = $("#" + form[i].id); // i, so you can put in the id for any form
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $(this).serialize(), // again, keep generic so this applies to any form
success: function (result) {
alert(result);
}
});
});
});

You should set the event listener to the element, not the string of the id of the element. Also I presume you have jQuery because you are using $. Set an id on the form in the HTML. Then:
$(function () {
var form = $('#theFormId');
form.submit(function(event) {
$.post('Controllers/c_insertPatient.php', form.serialize(), function() {
alert('success');
});
event.preventDefault();
});
});

Related

AJAX Submitting Single Forms on Page

I have 2 forms on the same page and want them to submit independently of each other using AJAX. The code I currently have is:
<script type="text/javascript">
$("#form_tab").on("submit", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
success: function(data){
$('#ResponseDiv').html(data);
}
});
});
</script>
When I put both form id's to form_tab they both submit when the other is. How Can I make they both submit interdependently with the same code? Thanks!
ID's must be unique or else you will have problems with JavaScript. You can use
$('form').on('submit', function() {
var formID = $(this).id; // get this form's id
Then you can use the ID, if you need to, to handle processing for each form.

How to pass multiple parameter from view to controller without ajax request

I want to pass multiple parameters from view to controller using jquery without an ajax call and I don't want to use ajax, Because that return is in jquery but I want to return view.
<script>
$(document).ready(function () {
$(".addCF").click(function () {
var Resource = $("#ResourceId option:selected").text();
alert(Resource);
var Description = $("#ResourceDescription ").val();
alert(Description);
var Count = $("#ResourceCount option:selected").text();
alert(Count);
var Cost = $("#ResourceCostId option:selected").text();
alert(Cost);
var Duration = $("#ResourceDuration option:selected").text();
alert(Duration);
$.ajax({
url: '#Url.Action("ResourceList", "Home")',
data: { Resource: Resource, Description: Description, Count: Count, Cost: Cost, Duration: Duration },
datetype: 'json',
contenttype: "application/json",
type: "GET",
success: function (data) {
location.reload();
}
});
});
});
</script>
Any suggestion please?
You will need a form to submit. Then use .submit() https://api.jquery.com/submit/ If you are using razor your can create a from like this.
#Html.BeginForm("YourAction", "YourController", FormMethod.Post)
Then have your controller return a view.

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.

JQuery recognize string as function dynamically callback

I have a simple jquery function that I am trying to get ajax to run dynamically. The function works fine when called as such
function widget1() {
console.log("test");
}
$(function () {
$('#thisbutton').bind('click', function() {
var htmlString = $("#uid").html();
$.ajax({
type: "GET",
url: "/getappobj",
data: {id:htmlString},
success: function(data) {
widget1();
}
});
});});
but if I try to get the function called dynamically I get an error that the string is not a function
$(function () {
$('#thisbutton').bind('click', function() {
var htmlString = $("#uid").html();
$.ajax({
type: "GET",
url: "/getappobj",
data: {id:htmlString},
success: function(data) {
var findit = data[0].widget;//returns "widget1"
findit();
}
});
});});
I have tried this every way that I can think of. Using jquery-1.9.1.min.js.
If widget1 is global, you can call window[findit]() to get the function from the window object by name.
You are trying to call a string as a function which of course won't work. You need to use the string to look-up the function to execute.

pass data to lable in same page using jquery

i have this working code with this code i can pass data to div within same page
but insted of passing data to div i want to pass this to label or textbox so that i can post it to the server. i am new in ajax,jquery . please suggest me best answer
<script type="text/javascript">
//send clicker data to div
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(){
//alert(data);
$('.responseDiv').text(data);
}
});
});
});
</script>
<script type="text/javascript">
i think i need to change this line only
$('.responseDiv').text(data);
but dont know how to do that. didnt find any solution on net also
take any name like propertyId
Let's say the text field has id="propertyID"
Use the val() method to assign this new value to your text field.
$('#proertyID').val(data);
Like:
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(){
//alert(data);
// $('.responseDiv').text(data);
$('#proertyID').val(data);
}
});
});
});
In the below line change selector .responseDiv with id/name or class of input/label $('.responseDiv').val(data);
<script type="text/javascript"> //send clicker data to div
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(data2){
//alert(data);
$('.responseDiv').text(data2);
}
});
});
});
success return in data2 and use this..

Categories

Resources