Ajax formdata submission using click - javascript

I have this form that allows user to write an article also upload an image.
i use the ajax script below
$(document).ready(function() {
$("#publishArticle").on('submit', function() {
event.preventDefault();
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "send.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Published") {
$("#publishArticle")[0].reset();
}
}
});
});
});
It works well. then i decided to have another button that drafts an article...
am trying to use an onclick event to differenciate between them. but it's not going through...
//Publish
$(document).ready(function() {
$("#publish").click(function(){
event.preventDefault();
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "send.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Published") {
$("#publishArticle")[0].reset();
}
}
});
});
});
//Drafts
$(document).ready(function() {
$("#draft").click(function(){
event.preventDefault();
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "draft.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Drafted") {
$("#publishArticle")[0].reset();
}
}
});
});
});
Please help me out...
Thanks in advance

You can attach a custom click handler to all buttons, and that way you can check which button is clicked before submitting the form:
Javascript:
$("#my-form button").click(function(event){
alert($(this).attr("value"));
event.preventDefault()// cancel form submission
if($(this).attr("value")=="button-publish"){
//do button 1 thing
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "send.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Published") {
$("#publishArticle")[0].reset();
}
}
});
}
if($(this).attr("value")=="button-draft"){
//do button 2 thing
var form = $(this);
var formData = new FormData($(this)[0]);
$.ajax({
url : "draft.php",
type : "POST",
cache: false,
contentType : false,
processData: false,
data: formData,
success:function(response){
$("#result").fadeIn();
$("#result").html("");
$("#result").html(response);
$("#result").fadeOut(4000);
if (response == "Article Drafted") {
$("#publishArticle")[0].reset();
}
}
});
}
$("#my-form").submit(); // If you want to submit the form
});

Related

How to JQuery Select an html item which is not "loaded" yet?

I have an Ajax call, that in the Success function, load a PartialView(html), in a container.
And I need to do "something" with a hiddenField value that it is in the loaded PartialView.
Trying $("#IdOfHiddenTextField").val() or a class selector and Jquery do not select the Html element.
How can I achieve that?
Actual code:
$.ajax({
url: '/apps/server',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (response) {
if (response.ok == "ok") {
esValido = true;
$("#divContenedorPaso2").html(response.vistaRazor);
if (response.modificoEmail) {
$("#popup-mensaje").html("Modification successfull");
$('#myModalAdvertencia').modal('show');
}
} else {
$("#divContenedorPaso2").html(response);
}
}
});
I need to do:
$.ajax({
url: '/apps/server',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (response) {
$("#divContenedorPaso2").html(response);
var submitSuccesfull = $("#IdOfHiddenTextField").val();
// this hidden element is inside de PartialView "response"
if (submitSuccesfull ) {
esValido = true;
$("#popup-mensaje").html("Modification successfull");
$('#myModalAdvertencia').modal('show');
} else {
esValido = true;
}
}
});
I don't know your code but i think you need something like this :
$.ajax({
url: "partialView.html",
success: function(response) {
var result = $(response).find("#IdOfHiddenTextField").val();
}
});

How to upload file in laravel with formData in jquery ajax

I am using laravel 5.4 and jquery Ajax to upload file and some form data.
I am using below code
function submitDocument(){
var formData = new FormData(); // Currently empty
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "documents",
method: "post",
data:{_token,formData},
}).done(function(data) {
});
return false;// Not to submit page
}
And I am getting error
Uncaught TypeError: Illegal invocation
How can I fix this ? Thanks in advance for your time.
I am able to get value in formData by using
console.log(formData.get('title'));
console.log(formData.get('doc'));
Try adding processData: false, contentType: false in your code
Replace your script with this:
function submitDocument(){
var formData = new FormData(); // Currently empty
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "documents",
method: "post",
data:{_token,formData},
cache : false,
processData: false,
contentType: false
}).done(function(data) {
});
return false;// Not to submit page
}
By default, data passed in to the data option as an object will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
<script>
$(document).ready(function() {
var url = "{{ url('/admin/file') }}";
var options = {
type: 'post',
url: url,
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
dataType: 'doc',
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert('Ok');
},
error: function (data) {
alert('Error');
}
};
$('#save').on('click', function() {
$("#form").ajaxSubmit(options);
return false;
});
});
</script>
Try this way
$(document).ready(function (){
$("#form").on('submit',(function(e){
e.preventDefault();
var formdata = new FormData(this);
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "/site/url",
type: "POST",
data:{token:_token,formData},
contentType: false,
cache: false,
processData:false,
success: function(data){
},
});
}));});

sending values file and text inputs together with ajax to php

I have a form and it has text inputs and file input for upload an image. I tried to send values to my php page but i couldnt do it. Here is my ajax codes.
function sendval() {
var form = $('#user_update_form')[0];
var form_data = new FormData();
$.ajax({
type: 'POST',
url: 'user_update.php',
processData: false,
data: form_data,
success: function(msg) {
$('#updtalert').html(msg);
}
});
}
You should add from ajax inside this code
function sendval(){
var form = $('#user_update_form')[0];
var form_data = new FormData(this);
$.ajax({
type:'POST',
url:'user_update.php',
processData: false,
cache:false,
contentType: false,
data:form_data,
success: function (msg) {
$('#updtalert').html(msg);
}
});
}
Try below code :
function sendval(){
var form = $('#user_update_form')[0];
var form_data = new FormData(form);
$.ajax({
type:'POST',
url:'user_update.php',
processData: false,
contentType: false,
data:form_data,
success: function (msg) {
$('#updtalert').html(msg);
}
});
}

Jquery ajax upload not showing values for the big images?

I have a page where i have send form data using jquery ajax upload and in php file i am posting these values in database but it is not showing any values for big image in php files when i try to print . Please check with the my screen shot. upload image size 2mb
var formData = new FormData($('form')[0]);
formData.append('licens_certificate', licens_certificate);
$.ajax({
url: "<?php echo site_url(); ?>pro/submit_business",
type: "POST",
data:formData,
async: false,
processData : false,
contentType : false,
// fileElementId :'licens_certificate',
dataType: "json",
// contentType: 'multipart/form-data',
success: function(result){
alert()
}
});
Please check data properly append with formdata.
var formData = new FormData($('form')[0]);
formData.append('licens_certificate', licens_certificate);
$.ajax({
url: "pro/submit_business",
type: "POST",
data:formData,
async: false,
processData : false,
contentType : false,
// fileElementId :'licens_certificate',
dataType: "json",
// contentType: 'multipart/form-data',
success: function(result){
alert(result)
}
});
Edit: Here's how you convert your form to JSON:
var serializeJSON = function(formData) {
var jsonData = {};
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
return jsonData;
}
var formData = $("#myform").serializeArray();
var json = serializeJSON(formData);
// Add your licens_certificate data
json['licens_certificate' = 'licens_certificate';
$.ajax({
url: "<?php echo site_url(); ?>pro/submit_business",
type: "POST",
data: json,
async: false,
processData : false,
contentType : false,
dataType: "json",
success: function(result){
alert()
},
error: function(err) {
console.log(err);
}
});
Original
Have you tried to serialize your form?
var formData = $('form').serializeArray();
formData.push({licens_certificate:, 'licens_certificate'});
$.ajax({
url: "<?php echo site_url(); ?>pro/submit_business",
type: "POST",
data: formData,
async: false,
processData : false,
contentType : false,
dataType: "json",
success: function(result){
alert()
},
error: function(err) {
console.log(err);
}
});
Also, make sure you are serializing the right form, especialy if you have several in your page.
You could also simply use the $.post function
var url = "<?php echo site_url(); ?>pro/submit_business";
$.post(url, dataForm).succes(function(data) { alert(); });

Post files with AJAX + jQuery with input element ID

I am trying to POST form data with AJAX + jQuery using the code below
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
data.append("file_"+i, file_data[i]);
}
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input) {
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
Here submit1 is a button on form form_id
This code is working fine, however the below line
data.append("file_"+i, file_data[i]);
as you can see posts the file with id of file_0, file_1 and so on. How can I get this to be the actual id of the input element rather than being a generic file_0, file_1 etc ?
Thanks for reading this
If you are using jQuery then why not something like this
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
Entire Code :-
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>

Categories