This question already has answers here:
Sending multipart/formdata with jQuery.ajax
(13 answers)
Closed 6 years ago.
I would like to pass form data via jquery to a php page. Now I am little confused with image passing through jquery and how it will reach php page.
My code:
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var guestbookSendMessage = { //Fetch form data
'name' : $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file' :$("#fileInput")[0].files[0];
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'php/process.php', //Your form processing file url
data : guestbookSendMessage, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
You may use File API or FormData to send image data to your server with ajax. What to choose is up to you to decide but since FormData is easier to implement I will answer your question using FormData here.
First of all you need to create FormData container and append your data to it. Just amend your code
var guestbookSendMessage = { //Fetch form data
'name': $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file': $("#fileInput")[0].files[0];
};
with this
var guestbookSendMessage = new FormData();
guestbookSendMessage.append('name', $('input[name=name]').val());
guestbookSendMessage.append('msg', $('textarea[name=msg]').val());
guestbookSendMessage.append('file', $("#fileInput")[0].files[0]);
Now instead of this parameter in your $.ajax
dataType: 'json'
Add these two
processData: false,
contentType: false
This will allow your data to be interpreted correctly.
Now in your php/process.php script you'll get 'name' and 'msg' in your $_POST superglobal array and 'file' in $_FILES.
var fdata = new FormData();
var myform = $('#prfform'); // specify the form element
var idata = myform.serializeArray();
var document = $('input[type="file"]')[0].files[0];
fdata.append('document[]', document);
$.each(idata,function(key,input){
fdata.append(input.name,input.value);
});
$.ajax({
url:"process.php",
type: "POST",
data: fdata,
processData: false,
contentType: false,
beforeSend: function() {
//something before send
},
success:function(data) {
//something after response
}
});
<form name="prfform" id="prfform" method="post" enctype="multipart/form-data">
<!-- elements -->
</form>
Please try this code.
"enctype" is important in the form.
In ajax script, give "processData: false" and "contentType: false"
This might solve your issue.
Related
I created a form. I added many validations as requirement like required all fields. Check duplicate fields. Now I want if form submitted successfully without error reset my form if it has any error like duplicate email then show error Duplicate data found and don't reset form. I completed my code but tucked in a place I m returning false then it's not showing an error which I mentioned din called PHP file. So, how can I do it without using JSON?
$("#create_stock_out").click(function(){
var form= new FormData();
var subject = $("#subject").val();
var slip_no = $("#slip_no").val();
var warehouse = $("#warehouse").val();
var vendor = $("#vendor").val();
var issued_by = $("#issued_by").val();
var received_by = $("#received_by").val();
var project = $("#project").val();
form.append('subject',subject);
form.append('slip_no',slip_no);
form.append('warehouse',warehouse);
form.append('vendor',vendor);
form.append('issued_by',issued_by);
form.append('received_by',received_by);
form.append('project', project);
form.append('method', "stock_out");
$.ajax({
url: 'Function/Function.php',
type: 'post',
data: form,
contentType: false,
cache: false,
processData:false,
success:function(data){
//alert(data);
$('#stock_out_result').html(""+data+"");
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000);
}
});
});
I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery
HTML:
<input type="text" name="description">
<input type="file" name="image" accept=".jpg">
How can I use $.ajax to upload the image and text value? I have no problem producing an object to submit text data, but have no idea where to start with the image.
I am using PHP server-side, so encoding the image in base64 or similar methods are perfectly acceptable.
it’s easiest to use the FormData() class:
So now you have a FormData object, ready to be sent along with the XMLHttpRequest. and append fields with FormData Object
<script type="text/javascript">
$(document).ready(function () {
var form = $('form'); //valid form selector
form.on('submit', function (c) {
c.preventDefault();
var data = new FormData();
$.each($(':input', form ), function(i, fileds){
data.append($(fileds).attr('name'), $(fileds).val());
});
$.each($('input[type=file]',form )[0].files, function (i, file) {
data.append(file.name, file);
});
$.ajax({
url: '/post_url_here',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (c) {
//code here if you want to show any success message
}
});
return false;
});
})
</script>
and forcing jQuery not to add a Content-Type header for you, otherwise, the upload file boundary string will be missing from it.
Use jQuery form js to upload images using ajax.
Check https://github.com/malsup/form/
var options = {
url : 'url',
success : function(responseText) { "event after success "}
};
$(" form id ").ajaxSubmit(options);
and get image in php file and upload images
So, I am doing a check when a user inputs an email to see if the email exists or not.
$('form.recover-form#check-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: {email: email},
success: function(response) {
if ( response == 'no' ) {
span.text('email does not exist');
} else if ( response == 'ok' ) {
form.submit();
}
}
});
});
The php code
if ( Input::isPost('email') ) {
$email = Input::post('email');
$check = $dbh->prepare(" SELECT * FROM users WHERE email = :email ");
$check->execute(array( 'email' => $email ));
echo ( $check->rowCount() == 1 ) ? 'ok' : 'no' ;
}
This way as soon as I submit the form it submits and the e.PreventDefault() inside the AJAX call is not working. If I put e.PreventDefault() before the AJAX call however, the form does not submit and the error appears if the email does not exists ( this is what I want to achieve ).
I can't understand where the problem is, hope you can help.
Thank you.
EIDT: This is the updated code
The problem is that you don't call preventDefault during the handling of the event. Instead, during the handling of the event, you start an ajax call (which is asynchronous), and then let the event continue. The ajax call completes later, which is too late to prevent the event's default — it's already happened.
Move the e.preventDefault() directly into the event handler, outside the ajax success handler.
$('.recover-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault(); // <=================== Here
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
// ============================ Not here, this would be too late
span.text('email does not exist');
}
}
});
});
In a comment, you've said:
Yes, it works for the validation, but I want to submit the form if ajax returns a positive response. I only do a check with AJAX, if it fails stop the submit, if it succeed continue the submit.
You can't hold up the original form submission waiting for the result of an asynchronous ajax call. What you do instead is cancel the original form submission, do the ajax, and then if the result is okay, re-submit the form using the submit method on the raw DOM form element. That method doesn't re-trigger submit event handlers.
Example: Live copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Delaying form submit during ajax</title>
</head>
<body>
<form action="http://www.google.com/search" method="GET">
<input type="text" name="q" value="kittens">
<input type="submit" value="Submit">
</form>
<script>
(function() {
$("form").submit(function(e) {
var rawFormElement = this; // Remember the DOM element for the form
// Stop form submission
display("Got form submit event, simulating ajax");
e.preventDefault();
// Simulate ajax check of data
setTimeout(function() {
// (This is the 'success' callback for the ajax)
display("Ajax call complete, pretending result is good and submitting");
// All okay, go ahead and submit the form
rawFormElement.submit(); // Doesn't trigger 'submit' handler
}, 1500);
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
</script>
</body>
</html>
You can't prevent the default action from a success handler of ajax request because of the asynchronous nature of it.
Instead by default prevent the form submission, then in the success handler if it is valid then call the submit again.
$('.recover-form').on('submit', function (e) {
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
//prevent the submit
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function (response) {
if (response == 0) {
span.text('email does not exist');
} else {
//submit if valie
form[0].submit()
}
}
});
});
First, you're options are incorrect. cache and async require boolean values, not strings.
async: false,
cache: false,
Secondly, instead of submitting the form after the ajax request you're instead triggering the event. Try this instead.
form.get(0).submit();
It returns the form node rather than a jquery object, allowing you to submit it directly rather than triggering an event (otherwise you would have an infinite loop.)
You don't really need async: false or cache: false in this case.
You need to do the following:
$('.recover-form').on('submit', function(e){
e.preventDefault();
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
span.text('email does not exist');
}
}
});
});
Notice how I've moved the e.preventDefault() to the beginning. This is because you were calling it when the ajax request responds which might happen 100s of milliseconds or even seconds after the form has been submitted
This happens because success function passed for jQuery.ajax() is executed assyncly, then it will be executed after event handler function is finish.
You should put the e.preventDefault() out of ajax function. and everything will work.
Better you can try something like this ,
<form name="myForm" onsubmit="return submitObj.validateAndSubmit();"> <!-- your form -->
<!-- your AJAX -->
var submitObj = {
validateAndSubmit : function()
{
var form = $('.recover-form'),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
return false;
}
else{
return true;
}
}
});
}
};
edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});