jquery change event to submit form using ajax - php

Here is my form
<form name="uploadImg" id="uploadImg" class="profile-image" enctype="multipart/form-data">
<input type="file" name="profile" id="updProfileImg">
</form>
Here is my jquery event
$("#updProfileImg:file").change(function() {
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
})
})
But the change event is not triggering form submit so I tried trigger('submit') but the page is refreshing instead of submitting in ajax.

You are binding the events incorrectly. As you currently have it, changing the field will trigger the binding of the submit. It need to be like this:
// bind the submit event
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
});
});
// bind the change event to trigger a submit
$("#updProfileImg:file").change(function() {
$("#uploadImg").submit();
});

A simple modification works
$("#updProfileImg:file").change(function() {
//$('#uploadImg').submit(function() {
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
//})
})

you should try this code:
$("#updProfileImg:file").on("change", function(){
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {},
success: function() {}
})
});
because i expect the ".change()" will be fired one time in the first change.

Related

ajax beforeSend not working when sending formData

I am having a div
that shows a loader image while sending ajax requests
I attached the div in the beforeSend attribute of ajax. The issue is if I send serialize() data then the beforeSend works but doesn't work when I send formData
Works
$.ajax({
url: 'centre-basic-process.php',
type: 'post',
data: $('#centreform').serialize(),
beforeSend: function() {
$('.displayLoader').show();
},
success: function(response) {
console.log(response);
$('#centreformupload').show();
$('#centreform').hide();
$('html, body').animate({
scrollTop: 0
}, 0);
}
});
Doesn't work
$.ajax({
url: 'centre-upload-process.php',
type: 'POST',
data: formData,
async: false,
beforeSend: function() {
$('.displayLoader').show();
},
success: function(response) {
alert("You have succesfully submitted the form. Please complete the payment method");
document.location.href = "dashboard.php";
},
cache: false,
contentType: false,
processData: false
});
I even tried ajaxStart() but facing same issue. Can anyone help me?

AJAX send data to PHP file

send $username php with data: new FormData(this), to add.php like data: new FormData(this),$username how can i do it with ajax code
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadFormuserimg").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "add.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#user_img_a").html(data);
},
error: function()
{ alert("error");
}
});
}));
});
</script>
var myData = new FormData(this);
myData.append('username','<?php echo $username; ?>');
and get on "add.php" like this
$username = $_POST['username'];
This worked on my side.
Based on comments to the question, specifically:
I just want to add some data
Are you just asking how to add more fields to the object that was created already in the data value? Something like this:
var myData = new FormData(this);
myData.append("anotherField", "anotherValue");
// etc.
Then just use that variable as your AJAX data:
$.ajax({
url: "add.php",
type: "POST",
data: myData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#user_img_a").html(data);
},
error: function()
{ alert("error");
}
});
You can store anything you like in a variable and use that variable at a later time. With a FormData object you would generally use .append() to add more key/value pairs to it.

jQuery ajax, send data

i'm having a problem sending the option selected with ajax.
Code:
$("#editarConta").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "includes/php/class_conta.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(resultado){
$("#accountEdit_result").html(resultado);
}
});
}));
Sending this data i can't see what option was selected. Is any way i can send this data, plus the selected option like:
data: { new FormData(this) , optionSelected: $( "#linguagem_favorita option:selected" ).val() },
My select HTML code:
<select name="linguagem_favorita" id="linguagem_favorita" class="form-control">
If i send with my code i get NULL when i var_dump the variable
var_dump($_POST["linguagem_favorita"]);
Append to the form data:
$("#editarConta").on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
formData.append("optionSelected", $("#linguagem_favorita option:selected" ).val() );
$.ajax({
url: "includes/php/class_conta.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(resultado){
$("#accountEdit_result").html(resultado);
}
});
}));

upload both form and file using ajax in jquery validation plugin in php

These is my form
<form action="<?php echo base_url();?> candidate/ajaxadd" name="candidate_form" method="post" id="candidate_form" enctype="multipart/form-data">
These is ajax function in jquery validation plugin
submitHandler: function(form) {
var formData = new FormData($(this)[0]);
$.ajax({
url: form.action,
type: form.method,
data: formData,
async: false,
complete: dispaly_candidate,
success: function(response) { alert(response);
if(response == "false"){
alert("Please enter all fields");
}
},
cache: false,
contentType: false,
processData: false
});
I don't understand question but:
submitHandler = function(form) {
var formURL = form.attr("action");
var formData = form[0];
var formData = new FormData(formData);
$.ajax({
url: formURL,
type: "POST",
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data) {
var response=$.trim(data);
alert(response);
if(response === "false"){
alert("Please enter all fields");
}
}
});
};
// use finction:
submitHandler($("#candidate_form"));
You need to ask the question in detail. And this function is a correction that (I guess) you're looking for.

Upload file via ajax jquery php api

I am having the code with the below format.
PHP file :
<form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data">
<input type="text" name="image_title" />
<input type="file" name="media" accept="image/*,video/*"/>
</form>
JQUERY file:
$('#form_createEvent').submit(function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
xhrFields: {
withCredentials: true
},
data: form.serialize()
}).done(function () {
showCurrentLocation();
alert('Event created successfully..');
location.reload();
}).fail(function () {
alert("fail!");
});
event.preventDefault();
});
The above Jquery code is submitting. Also While I am submitting the below format, It will redirect to the "http://clientwebapi.com/createEvent" and Event created successfully.
Form Submit and redirect to client page:
$('#form_createEvent').submit(function () {
var fd = new FormData();
fd.append('media', input.files[0]);
$.ajax({
url: form.attr("action"),
data: fd,
processData: false,
contentType: false,
type: form.attr("method"),
success: function (data) {
alert(data);
}
});
event.preventDefault();
});
Here How can I prevent while submit the form and create the event with the given image. Kindly help
You forgot to add event as argument to the submit function:
$('#form_createEvent').submit(function (event) {
I found the Answer for this. I made some mistake here. I resolved by using the below code..
$('#form_createEvent').submit(function() {
var form = new FormData($(this)[0]);
$.ajax({
url: 'http://clientwebapi.com/createEvent/',
type: 'POST',
xhrFields: {
withCredentials: true
},
async: false,
cache: false,
contentType: false,
processData: false,
data: form,
beforeSend: function () {
$("#output_process").html("Uploading, please wait....");
},
success: function () {
$("#output_process").html("Upload success.");
},
complete: function () {
$("#output_process").html("upload complete.");
},
error: function () {
//alert("ERROR in upload");
location.reload();
}
}).done(function() {
alert('Event created successfully..');
}).fail(function() {
alert("fail!");
});
event.preventDefault();
});
you can stop the form submission by return false;
$('#form_createEvent').submit(function () {
// some code
$.ajax({
// some code/objects
});
return false; // here, it will stop the form to be post to the url/action
});

Categories