jquery submit form and then show results in an existing div - javascript

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

Related

AJAX call being canceled when submit button is used [duplicate]

I am trying to perform an ajax call inside a form (a Drupal node edit form) , but it seems when performing the call, it submits the form for some reason. Here is a sample code:
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: {"text": jQuery("#edit-body").html()
},
success: function(result){
console.log(result);
}
});
I can replicate this just by executing it in the console, but I attach this to a button click function inside the form. Any tips on preventing the form from submitting, on a POST ajax call?
Here is the full code as requested
jQuery("#edit-body").before('<div id="proofread_bot-button-holder"><button type="button" id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>');
jQuery("#proofread_bot-submit").click(function(event){
event.preventDefault();
jQuery("#proofread_bot-button-holder").append("<img id=\"proofread_bot_throbber\" src=\"sites/all/modules/proofread_bot/images/throbber.gif\" />");
jQuery.ajax({
type: "POST",
url: "proofread_bot/check",
dataType: "html",
data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
},
success: function(proofread_result){
jQuery("#proofread_bot-submit").after(proofread_result);
jQuery("#proofread_bot_throbber").remove();
}
});
});
You need to override form's onsubmit event to prevent submitting:
$("formSelector").bind('submit', function (e) {
var isValid = someYourFunctionToCheckIfFormIsValid();
if (isValid) {
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
e.preventDefault();
return false;
});
By calling
e.preventDefault();
return false;
You prevent synchronous postback from occurring.
UPDATE:
If you don't want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?
If you are using a input type="submit" button, then you need to do a return false; at the end of the function to prevent it from submitting.
Another solution is to e.preventDefault() on the button click
$(".button").click(function(e){
e.preventDefault();
return false;
});
you can change submit button type to just a button type and add "onclick" event to that button.
input type="button" value="savebutton" onclick="return doThisOnClick();"
function doThisOnClick(){
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
I think this is most straightforward.

Jquery ajax posting only some data at a time

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

Submit form having file using java script submit button

java-script :
i have a form that feed value to a controller via ajax call .
The form get serialized in ajax call and the controller return 'true' on success but the problem is that my form have a file and the file can't be serialized . I am working out how i can receive the file in my controller using this ajax call .
function save()
{
if(save_method == 'On_submitted')
{
url = "<?php echo site_url('MyController/insertForm')?>";
$.ajax({
url : url,
type: "POST",
data:$('#form_name').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_name').modal('hide');
alert('added successfully');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
}
When i omit the input file fields than its working fine , the main problem is to send the file to controller via java-script .
i have tries but i am don't know what is wrong and how can i do it .
you should not use dataType: "JSON" if you sending files.
you can form data for request using (filesForm = name of form):
var formData = new FormData(document.forms.filesForm);
then add other keys:
formData.append("key", keyValue);
and to send this data, add this options to ajax call:
contentType: false,
cache: false,
processData: false,
you need contentType = false (it will be multipart/form-data in fact) if you wish to upload files.
and final ajax call should be like this:
$.ajax({
url: url,
data: formData,
contentType: false,
cache: false,
processData: false,
type: 'POST',
success: function (result) {
$("#result").html(result)
},
error: function (result) {
$("#result").html(result)
}
});

Ajax call multiple time onclick event on bootstrap modal

By clicking a button Its loaded a bootstrap modal. On the modal there have a form and on click save button I am trying to submit form by ajax call. At first time the ajax call trigger one time, but 2nd time the ajax url trigger two times. I see on firebug console section the post url is called multiple times.
Here Is my jquery code.
$(".show-modal").click(function() {
$('.upload-modal').modal();
$(".save-logo").click(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
data : data,
contentType: false,
cache : false,
processData: false,
url : "../../io/upload/"
}).done(function(rawData) {
$('.modal-header .close').click();
})
});
})
The problem is that you have your .save-logo click handler inside the .show-modal click handler. So every time the modal is shown, you attach another click handler to the .save-logo element. The code below should fix that problem:
$(".show-modal").click(function () {
$('.upload-modal').modal();
});
$(".save-logo").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
data: data,
contentType: false,
cache: false,
processData: false,
url: "../../io/upload/"
}).done(function (rawData) {
$('.modal-header .close').click();
})
});
$(function(){
var editUserId;
$('#edit-user-modal').on('show.bs.modal', function(e) {
editUserId = $(e.relatedTarget).data('userid');
});
$("#edit-user-form").submit(function(event) {
event.preventDefault();
var form = $(this);
var route = "/edit-user/" + editUserId;
if(validateEditUserForm()){
$.ajax({
type: "POST",
url: route,
data: form.serialize(),
success: function(Response)
{
if(Response){
console.log(Response.status);
console.log(Response.message);
if(Response.status == 'success'){
$('#adduser-alert-box').hide();
$("#add-user-form")[0].reset();
$('#adduser-success-box').show();
$('#adduser-success-box').html(Response.message);
}
else{
console.log('User could not be added');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html(Response.message);
}
}
else{
console.log('No Response');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('No Response');
}
}
});
}
else{
console.log('Validation Error');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('Please Fill All the Fields Correctly');
}
});});
I faced the same issue and randomly i tried something .
so if you create a global variable to store the 'id' you pass from your button then store the id from the 'data' attribute of your button then it won't make multiple requests when clicked since you have declared the variable globally!
Hope it helps.

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

Categories

Resources