Jquery ajax posting only some data at a time - javascript

I have always used query ajax request to something simple like preventdefault form submit and adding beforesend function or complete function after the form is submitted like this to my nodejs backend:
$.ajax({
type: "POST",
url: "/contact",
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
setTimeout(function(){
console.log('Here')
$(".loading_msg").fadeOut("slow");
$("#message").val("")
},3000)
}
});
Now, I have a sitution where I have to submit only part of the form input elements. There are also input elements inside the form which is dynamically generated.
Is there a way for me to send only input boxes with id's or classes that I want rather than the entire form?

If you want to send some particular data to your server, you can config the data by yourself like the following:
$.ajax({
type: "POST",
url: "/contact",
data: {
myKey1: $("#myKey1").val(),
myKey2: $("#myKey2").val()
},
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
setTimeout(function(){
console.log('Here')
$(".loading_msg").fadeOut("slow");
$("#message").val("")
},3000)
}
});

Related

how to send multiple value from client to server using ajax json

I'm trying to send multiple data from client to server using ajax json.
case First: when i send my form inputs data from client to server it was going well.
case second:now one modification done in my form and i am generating dynamic multiple rows with textboxes .and it's values should also pass using same ajax method but my try go in vain so any idea would be appreciated.
Refer below article for more coding part details about this question.
enter link description here
I am trying like this
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var fields = $("#WireDimTbl tbody").find(":input").serializeArray();
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
user.REVISION = $("#Revision").text();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: JSON.stringify({ user: user,fields:fields}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Data has been added successfully.");
window.location.reload();
},
error: function (response) { alert(response.responseText); }
});
return false;
});
At Sever side part what modification should be done.how would i define parameter object with same strucutre at server side and how would i store in db.

Bootstrap modal popup and fadeout after few seconds according to ajax success

I am trying to display a bootstrap modal with success of a ajax request. Its working for me. But my problem is when I try to hide it after few seconds as soon as it triggered.
This is how I tried it.
$.ajax({
type: "POST",
url: "includes/process.php",
data: $(".banner-form").serialize(), // serializes the form's elements.
success: function(data)
{
$("#myModal").fadeTo(2000, 500).slideUp(500, function(){
$("#myModal").modal('close');
});
}
});
But this is not working properly when I submitting the form first time. After that when I submitting the form this modal is not popup. Can anybody tell me what is the reason for this?
Thank you.
Here it is,
$.ajax({
url: 'link/',
dataType: 'json',
success: function (s) {
$('#MyModal').modal({
show: false
});
},
error: function (e) {
}
});
This should work
$.ajax({
url: "test.html",
context: document.body
// wait until ajax request is done
}).done(function() {
// close the modal
$('#myModal').modal('hide')
// try this if above does not work!
// $('#modal').modal('toggle');
});

Custom Ajax request with jQuery form validation

I want to validate a form with the jQuery form validation plugin but I was not able to send a custom Ajax request with the validation handler:
$('#headForm').validate(
{
//submitHandler: submit,
errorClass: "invalid",
rules: {
title: {maxlength: 50}
},
messages: {
title: {maxlength: 'Max 50 chars'}
}
});
My orginal submit handler looked like this:
$('#headForm').submit(function(event)
{
event.preventDefault();
$.ajax(
{
type: "PUT",
url: "/target",
data: $('#headForm').serialize(),
dataType: "json",
success: function()
{
alert("ok");
}
});
});
I tried to move it to a usual function and register it as a submitHandler in the validation block, but it didn't work.
function submit() { // impossible to pass the event!
$.ajax( ...
}
How can I combine jQuery validation with a custom Ajax request?
Possible form validation bug:
I've removed the validation code to see whether the submission works without it. And it did not unless I removed the link to jQuery form validation library! So it seems like validation is breaking jQuery core. Have I already said that I love dynamic typing ... ;-)
Did you define a parameter in the submit() function?
(I'm guessing that you didn't, and that could be why it didn't work)
I think you just need to specify the 'form' parameter, and then call serialize() on that parameter, as follows:
submitHandler: function(form) {
$.ajax({
type: "PUT",
url: "/target",
data: form.serialize(),
dataType: "json",
success: function()
{
alert('ok');
}
});
}
See the docs: http://docs.jquery.com/Plugins/Validation/validate#options

JQuery AJAX not sending file with form

I have the following AJAX function with JQuery:
var formData = $('#FonykerEditForm').serialize();
$.ajax ({
type: 'POST',
url: '<?php echo $html->url('/fonykers/edit',true); ?>',
data: formData,
dataType: 'json',
success: function(response) {
message.html(response.msg);
message.fadeIn();
if(!response.ok) {
message.removeClass('success');
message.addClass('error');
} else {
message.removeClass('error');
message.addClass('success');
username = $('#FonykerUsername').val();
email = $('#FonykerEmail').val();
}
$('#save-account-button').removeAttr('disabled');
$('.input-text').removeClass('ok');
$('.input-combo').removeClass('ok');
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
$('#save-account-button').removeAttr('disabled');
}
});
The problem I'm having is that a type file field in my form is not getting submitted along with the rest of the data of the form, how can I include the file in the data of the ajax request?
I tried this link and this works fine for me.
http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
Example:
$( '#my-form' ).submit( function( e ) {
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );
Like I said in the comment above, sending files via ajax is not straightforward. If you wish to try it anyway. The normal approach I've seen is to create a new iframe, add a file input field to it, select your file and submit it programmatically. This way, the iframe does the submission in the background.
Take a look at how this plugin does it:
https://github.com/valums/file-uploader/blob/master/client/fileuploader.js#L995
https://github.com/FineUploader/fine-uploader
Basically an AJAX will submit data in the form of key/value pairs.. Since files are binary data, you can't submit files using Ajax.. You'll need to submit the data using a standard form submit instead and on the server since accept a form/multipart

jquery submit form and then show results in an existing div

I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.
Here is what I have now:
<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" />
<div id=created></div>
What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.
I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).
This code should do it. You don't need the Form plugin for something as simple as this:
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
This works also for file upload
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
$('#created').html(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
You must use AJAX to post the form if you don't want the page to be refreshed.
$('#create').submit(function () {
$.post('create.php', $('#create').serialize(), function (data, textStatus) {
$('#created').append(data);
});
return false;
});

Categories

Resources