post multipart/form-data with ajax - php

I want to post my form by ajax, the form contains some text fields and one file field, I used bootstrapValidator to validate the form, here is my code:
ajax:
$('#profile').bootstrapValidator({
// some validations here
}).on('success.form.bv', function(e) {
e.preventDefault();
var $form = $(e.target), // The form instance
bv = $form.data('bootstrapValidator'); // BootstrapValidator instance
var formData = new FormData($form);
$.post('index.php', formData, function(response) {
...
but the post request didn't sent, so where is the error in my code?

Related

Getting $_POST not working after Ajax successful submit in same page

I create a Form after user click on a div, and I submit on same page using Ajax without reloading page.
I see that the form is submitted successfully with data when I check the network tab in dev tools but when I print $_POST or check if isset($_POST["data"]), I get $_POST is empty and the if condition is false, is there any way to get the data in PHP ($_POST) without refreshing the page.
I get no errors in console or php
When using:
form.submit();
The form is submitted and I get $_POST but the page reload, this is why I need to use Ajax
My code on Js page :
function post(path, parameters) {
var form = $('<form id="form"></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", JSON.stringify(value));
form.append(field);
form.append(data);
});
$(document.body).append(form);
$.ajax({
type: "POST",
url: path,
data: $("#form").serialize(),
success: function(data) {
$('.before').hide();
$('.next').show();
}
});
return false;
}
$('.card-container').on('click',function(e){
e.preventDefault();
var page = window.location.href;
var object = {
'array': [
['string1', 'string2'],
['string3', 'string4']
]
};
post(page, object);
});
My code on PHP page :
var_dump($_POST);
if (isset($_POST['array'])) {
$array = json_decode($_POST['array'], true);
print_r("ok");
}
The full code is too long to include it here.

Getting data from HTML input fields to AJAX and declaring to data method

Good day! Me and my colleagues studying AJAX almost two weeks and we had difficulties in getting the data from input fields from HTML and transferring it to AJAX.
<script>
$(document).ready(function () {
$("#addmarble").on('submit',(function(e) {
e.preventDefault();
//var image = document.getElementById("#Marble_Img").files[0];
/*var image = $("#Marble_Img").val();
var desc = $("#Marble_Desc").val();
var size = $("#Marble_Size").val();
var thickness = $("#Marble_Thickness").val();
var supplier = $("#Marble_Supplier").val();
var quantity = $("#Marble_Quantity").val();
var submit = $("#Marble_Submit").val(); */
var image = $("MarbleImg").val();
var desc = $("MarbleDesc").val();
var size = $("MarbleSize").val();
var thickness = $("MarbleThickness").val();
var supplier = $("MarbleSupplier").val();
var quantity = $("MarbleQty").val();
var submit = $("submit").val();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{
image: image,
desc: desc,
size: size,
thickness: thickness,
supplier: supplier,
quantity: quantity,
submit: submit
},// Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert("noice");
console.log(data);
}
})
}));
});
</script>
It prompts that we get the data from the input fields but the data returns undefined.
How to fix them? Thanks!

How to pass form data along with image through jquery? [duplicate]

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.

What does the php insert code look like when dealing with ajax and serialized data?

UPDATE II
$("#form").submit(function(event){
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, {
id: $('#id').val(),
name: $('#name').val(),
wname: $('#wname').val(),
xcor: $('#xcor').val(),
ycor: $('#ycor').val(),
xwid: $('#xwid').val(),
yhei: $('#yhei').val(),
photo: $('#photo').val(),
targeturl: $('#targeturl').val()
});
posting.done(function( data ){
alert('success');
});
});
UPDATE
This does not work... the alert('nice'); is not triggered
$("#form").submit(function(e){
var postData = $(this).seralizeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type : "POST",
data : postData
});
e.preventDefault();
e.unbind();
});
$("#form").submit();
alert('nice');
My goal is to send data with a form through ajax and the page does not refresh.
I am not using a button, the submit is triggered by a javascript function which triggers the ajax
The serialized data I had follows the format of
name=name$email=email etc...
I don't know what to do with this string
This is what I have on the sending page
var frm = $('#form');
var formData = $('#form').serialize();
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
data: formData,
url: frm.attr('action'),
success: function (data) {
alert('successful update');
}
});
ev.preventDefault();
});
Does the serialized data get appended to a URL? I mean I realize upon submission the current page does not go anywhere so how would that work as far as the action page "seeing the url and pulling it" so to speak...
My action page is the cliche design of a form being submitted by a button on the same page mostly it is a declaration of the variables and then an insert line
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['name'];
$email= $_POST['email'];
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$stmt = mysqli_prepare($link, "INSERT INTO table VALUES(?,?)");
$stmt->bind_param('ss',$name,$email);
$stmt->execute();
I apologize if this is clearly wrong, I haven't used serialized form data submission before
Assuming your form method frm.attr('method') is POST, the serialized data does not get put in the URL but instead in the HTTP request body.
http://en.wikipedia.org/wiki/HTTP_message_body
If the form method is GET then the data would be appended to the end of the URL like so:
http://yoursite.com/yourrequestpage?name=yourname&email=youremail
If you are using the GET method then on the PHP side, you would have to use $_GET['email'] instead of $_POST['email'].
I also see that var formData = $('#form').serialize(); is out of the form submission function body. This should be put in the body so that it is initialized when the form is submitted (when you have filled out the form), not when the page is loaded (when you haven't yet interacted with the form).

php form not submitting using ajax jquery

.on('success.form.bv', function(e) {
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
If i comment this code, then form submits.PLease tell me the error.This is the form

Categories