How to add variable to FormData in jquery? - javascript

Actually i am using following script to post my form
var formData = new FormData($("form#driver_information")[0]);
$.ajax({
type: "POST",
url: "/",
data: formData,
success: function(data) {
$("#page_message_box").html(data);
},
cache: false,
contentType: false,
processData: false
});
I need to pass some more variables along with form data
eg:
var formData = new FormData($("form#driver_information")[0]);
$.ajax({
type: "POST",
url: "/",
data: formData + "&con=delete",
success: function(data) {
$("#page_message_box").html(data);
},
cache: false,
contentType: false,
processData: false
});
But it's not working.( data: formData + "&con=delete", ). Please help to solve this problem.

Try this:
formData.append('con', 'delete');
before the $.ajax call.
Then within that call you just need:
data: formData,

You can append data to FormData like this:
formData.append('con', 'delete');

Related

Ajax not passing correct data to $_POST on responding php page

I've got an ajax function:
$('#addSiteButton').on('click',function() {
let addSiteOption = $('#enterNewWebsiteLink').val();
const form = new FormData();
form.append('addSiteOption', addSiteOption);
$.ajax({
url: "includes/submit_site.php",
data: { 'data': form },
method: "POST",
contentType: false,
processData: false,
enctype: false,
cache: false,
datatype: "text",
success: function (response, data) {
}
});
My PHP file looks just like this:
if (isset($_POST['data'])) {
$websitelink = $_POST['addSiteOption'];
}
my HTML looks like this:
<input type="url" form="addsite" class="enterNewWebsiteLink"
id="enterNewWebsiteLink"
name="enterwebsitelink"
placeholder="Enter A New Website">
The error that I am getting is: Warning: Undefined array key "data"
I've tried outputting the variable addSiteOption and it outputs the URL correctly.
The frustrating thing, I've been checking/copying this against a previous project I did that I got it working in, and I can't make any difference between them now.
I get a 200 response from the server for the page.
You can't serialize FormData, and processData: false tells jQuery not to try to serialize the data: option.
You should just pass the FormData as the data: option. Then the keys of the FormData will become the $_POST keys.
JS:
$('#addSiteButton').on('click',function() {
let addSiteOption = $('#enterNewWebsiteLink').val();
const form = new FormData();
form.append('addSiteOption', addSiteOption);
$.ajax({
url: "includes/submit_site.php",
data: form,
method: "POST",
contentType: false,
processData: false,
enctype: false,
cache: false,
dataType: "text",
success: function (response, data) {
}
});
PHP:
if (isset($_POST['addSiteOption'])) {
$websitelink = $_POST['addSiteOption'];
}
You also had a typo: datatype: should be dataType:

contentType: false and processData: false make POST empty in PHP

I am trying to upload a file to my server using AJAX. The AJAX call works fine and my PHP returns correctly but when I add contentType: false and processData: false it no longer does.
var formData = new FormData();
formData.append('image', input.files[0]);
$.ajax({
url: "php/API.php",
data: {action: "changeProfilePicture", profilePicture: formData},
type: "POST",
contentType: false, // if i remove this
processData: false, // and this, and my form data in `data:` then POST is not empty
success: function(resp) {
console.log(resp)
}
});
// inside of php/API.php
<?php
// post is empty
print_r($_POST);
if(isset($_POST) && !empty($_POST)) {
...
}
?>
When sending multipart/formdata with jQuery.ajax, the request data should be an instance of FormData. e.g.
var formData = new FormData();
formData.append('image', input.files[0]);
formData.append('action', 'changeProfilePicture');
$.ajax({
url: "php/API.php",
data: formData,
type: "POST",
contentType: false,
processData: false,
...

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

Send image with ajax , using jquery validator on submitHandler

I trying to send two images with ajax (inside submitHandler) after using jquery validator plugin and i don't know hoy i cant take and send this image by ajax.
My code here:
var submitHandler = function(form) {
var formData = form[0];
var formData = new FormData(formData);
$.ajax({
url: 'function/savePreInscripcion.php',
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
alert(data);
}
});
};
but this dont work..
this display this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
var formData = new FormData(formData);
so.. what's worng here?
Thnx for the help!,
I resolve this..
Just change a little party on my code..
var submitHandler = function(form) {
$.ajax({
url: 'function/savePreInscripcion.php',
type: 'POST',
data: new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
alert(data);
}
});
};
Just I change the call to the form and put this directly on the data whit the next code: "data: new FormData(form)" and it work fine! =)

Ajax - onload attribute

How is possible to bring data from server onload data from server?
I have something like this, and it's not working:
JS:
function getItems(){
var formData = new FormData();
formData.append("ask", "MainView");
$.ajax({
type: "POST",
url: "getItems.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(result){
var result=trim(result);
$("#PageWrap").html(result);
}
});
}
function getItemsOnLoad(){
var formData = new FormData();
formData.append("ask", "OnLoad");
$.ajax({
type: "POST",
url: "getItemsOnload.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(result){
var result=trim(result);
$("#onloadInfoID").html(result);
}
});
}
PHP getItems.php:
echo <table onload="getItemsOnLoad()"><tr>some info</tr></table>;
If you're using jQuery, why you can't make it in ready?
$(document).ready(function() {
getItemsOnLoad();
});
function getItems(){
var formData = new FormData();
formData.append("menuItem", menuItem);
formData.append("ask", "MainView");
$.ajax({
type: "POST",
url: "getItems.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(result){
var result=trim(result);
$("#PageWrap").html(result);
}
}).done(function() {
formData.append("ask", "OnLoad");
$.ajax({
type: "POST",
url: "getItemsOnload.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(result){
var result=trim(result);
$("#onloadInfoID").html(result);
}
})
});
}
That was it, .done(). Change only js file.
try this on <body> tag
<body onload="getItemsOnLoad()">

Categories