jQuery AJAX passing more than one variable to data - javascript

below you can see the html code, javascript/jquery and PHP. I'm trying to send a request using AJAX PHP, to send multiple variable to PHP, one of them is FormData and the other is some text or values from inputs etc.
Here's html code:
<div>
<p>Name:</p>
<input id="newP_name"></input>
<p>Product Image</p>
<input type="file" id="img"></input>
<p>Description:</p>
<textarea id="newP_desc"></textarea>
<button name="submitProductBtn" id="submitProductBtn">Submit</button>
Here's my javascript:
$("#submitProductBtn").click(function(){
var file_data = $('#img').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'imgParser.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data, name: "John",
type: 'POST',
success: function (response) {
alert(response);
},
error: function (response) {
alert("ERROR OCCURED");
}
});
});
As you can see I'm trying to pass to 'data:' the FormData (image) and a second variable name.
Here's PHP code:
<?php
if(isset($_FILES["file"]["name"])){
if($_FILES["file"]["error"] == 0){
move_uploaded_file($_FILES["file"]["tmp_name"], "images/".$_FILES["file"]["name"]);
echo $_POST["name"];
}else{
echo $_POST["name"];
}
}
?>
I would expect it to print "John", but the alert is blank, image showing ->
Any help appreciated,
thanks in advance.
EDIT:
Changed slightly the jQuery code, still outputs empty, but when I had code commented out in PHP (below closing tag), it printed it.
here's my new jquery code:
$("#submitProductBtn").click(function(){
var file_data = $('#img').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', "John");
$.ajax({
url: 'imgParser.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function (response) {
alert(response);
},
error: function (response) {
alert("ERROR OCCURED");
}
});
});

You append all data fields to the form data object just like you did with the file
form_data.append('file', file_data);
form_data.append('name', 'John');

I'm not sure what is form_data maybe you can try this,
form_data.append('file', file_data);
form_data.append('name', 'john');
and simply pass form_data in data property
$.ajax({
...
...
data: form_data

Related

Uploading Image Using JSON is not Working

Can anyone help my code structure? What's wrong with it?
HTML
<form method="post">
<div class="col-md-4">
<div class="field name-box">
<input class="btn" name="image_file" id="image_file" type="file" style="font-size:15px;width:100%;margin-bottom:2px;" required=""/>
</div>
</div>
</form>
JS
var form_data = new FormData();
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(ts){
}
});
AJAX_CONTROLLER
public function add_product_image(){
if(is_array($_FILES)){
if(is_uploaded_file($_FILES['image_file']['tmp_name'])){
$sourcePath = $_FILES['image_file']['tmp_name'];
$targetPath = "product_images/"."sample_img_name".".png";
if(move_uploaded_file($sourcePath,$targetPath)){
// echo '<script>alert("Successfully Save")</script>';
}
}
}
}
But I've been wondering why I will get a success response on my ajax form? even my upload_file doesn't work properly. Can anyone help me?
you need to append data with form_data in your js file and send response
formData.append('image_file', $('#image_file')[0].files[0];);
var form_data = new FormData();
formData.append('image_file', $('#image_file')[0].files[0]);
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(){
}
});
pass form Element to FormData
let form = document.getElementById("yourFormId");
var form_data = new FormData(form);

sending uploaded file and other data , both using one ajax call

I am trying to send the uploaded file and the input text data (there are 5 text fields) without using form action. Is this the correct way to do it, this code works fine if I send only form_data or the values in {} but not both together. This is my code:
actionval = document.getElementById('action').value;
titleval = document.getElementById('title').value;
stageval = document.getElementById('stage').value;
substageval = document.getElementById('substage').value;
agentval = document.getElementById('agent').value;
var file_data = $('#uploadFileTrans').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "tabs/get_old_contents.php",
data: {form_data, insert1:actionval, insert2:titleval, insert3:stageval, insert4:substageval, insert5:agentval},
type: 'post',
complete: function(response){
alert('Details added successfully!');
$('#restrans').html(response.responseText);
// console.log('hey', response.responseText);
// editor.setValue(response.responseText);
}
});
and php is this :
$action = (isset($_POST['insert1'])?$_POST['insert1']:"");
$title = (isset($_POST['insert2'])?$_POST['insert2']:"");
$stage = (isset($_POST['insert3'])?$_POST['insert3']:"");
$substage = (isset($_POST['insert4'])?$_POST['insert4']:"");
$agent = (isset($_POST['insert5'])?$_POST['insert5']:"");
$date = date("Y/m/d");
and this is to upload , it works fine if I have only form_data in data field of ajax
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
You can't put a FormData inside an object being sent with AJAX. You need to add the other parameters to the FormData object, and use that as the data by itself.
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('insert1', actionval);
form_data.append('insert2', titleval);
form_data.append('insert3', stageval);
form_data.append('insert4', substageval);
form_data.append('insert5', agentval);
$.ajax({
url: "tabs/get_old_contents.php",
data: form_data,
processData: false,
type: 'post',
complete: function(response) {
alert('Details added successfully!');
$('#restrans').html(response.responseText);
// console.log('hey', response.responseText);
// editor.setValue(response.responseText);
}
});
You have to add all your data to the FormData object and pass that as the data parameter. Also, set processData to false and contentType to false.
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('insert1', actionval);
form_data.append('insert2', titleval);
form_data.append('insert3', stageval);
form_data.append('insert4', substageval);
form_data.append('insert5', agentval);
$.ajax({
url: "tabs/get_old_contents.php",
data: form_data,
type: 'post',
processData: false,
contentType: false,
complete: function(response){
alert('Details added successfully!');
$('#restrans').html(response.responseText);
// console.log('hey', response.responseText);
// editor.setValue(response.responseText);
}
});

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

How to add ajax parameters?

Faced with such a problem that you can't add parameters to ajax request, because there is a "Form Data" and it does not work to add more options. When you add in the parameter 'data' another variable, the error occurs. How to do that would be to post a file and parameters in one request?
Forgive the mistake, error or no, the php file simply does not output anything, rather empty values
//Here the file is sent without problems, but the parameters no more don't accept php file, nothing displays in the result
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: fd,
type: "POST",
processData: false,
contentType: false,
success: function(data) {
$(".news .containers").append(data);
}
});
//When this code runs the PHP file won't take anything, although I was expecting the output variables and the file. Using var_dump, $_POST and $_FILES displays array(0){}
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: {fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
type: "POST",
processData: false,
contentType: false,
success: function(data){
$(".news .containers").append(data);
}
});
//Similarly, nothing appears in the php file
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: {fd:fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
type: "POST",
processData: false,
contentType: false,
success: function(data){
$(".news .containers").append(data);
}
});
Just like you have appended the file, you can append more data into it like:
fd.append('file', input[0].files[0]);
fd.append('var1', val1);
fd.append('var2', val2);

Clear formData after $.ajax submit

var fd = new FormData();
fd.append( 'file', input.files[0] );
fd.name = 'something';
fd.etc = 'something more';
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
I put above code within a submit event, I found in my backend I received duplicated formData's data. Because after submit I did not want to hard refresh the page for good UX. How to clear the formData after ajax's success?

Categories