upload image with reactjs and ajax - javascript

I'm trying to upload an image through a form to a url/api.
I call handleImgUpload() method on submitting the form.
The problem is that the request sent is empty.
I think that new FormData(this) does not work with react or something.
There's another function that sets the image path.
handleImgUpload(e){
e.preventDefault();
$.ajax({
url: "my url goes here", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // 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
console.log(new FormData(this));
}
});
}
here is the form:
<form id="uploadimage" onSubmit={this.handleImgUpload} action="" method="post" encType="multipart/form-data">
<Row id="image_preview" className="row">
<img id="previewing" src={this.state.imgPath}/>
</Row>
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="image" id="file" onChange={this.handleImgChange} required />
<Button type="submit" className="btn btn-primary" id="upload">Upload</Button>
</div>
</form>

this is going to be the React component, not the form, which can be found in event.target
handleImgUpload(e) {
e.preventDefault()
let formData = new FormData(e.target)
for (let [key, val] of d.entries()) {
console.log(key, val) <-- should log the correct form data
}
// ajax stuff
}

Related

Append File to Form before Submit HTML and PHP

I have an application that I am building. The app creates a json file, then a jar file is uploaded and the json file is inserted into the jar, and the new jar is returned.
I have created a basic HTML form and PHP file that currently works, but the user must select both the jar and the json file to upload. I need to modify this now so that the user chooses the zip file, but the form would select the JSON from the JS.
THE HTML:
<form id="jar-form">
<div class="mb-3">
<label for="test-jar-upload" class="form-label">Select Jar File Files:</label>
<input type="file" id="test-jar-upload" name="jar" accept=".jar" class="form-control">
</div>
<div class="mb-3">
<button type="button" class="btn btn-primary" ng-click="export.exTest()" name="upload_file">Submit</button>
</div>
THE JS:
$scope.export.exTest = function(){
console.log('New Manual Submit');
let formData = new FormData();
let tFile = new Blob([JSON.stringify($scope.export.file)], {type: 'application/json'});
formData.append('jar',document.getElementById('test-jar-upload').files[0]);
formData.append('desc',tFile);
$scope.newData = formData;
$.ajax({
url: './assets/api/test.php',
data: formData,
type: "POST",
contentType: false,
processData: false
})
}
The AJAX call was taken from another answer, but doesn't successfully open the test.php file. If I change the path, I do get a 404 error returned.

POST convert to GET when I want to fetch formData?

I want to send an image to server
my code works perfect in Chrome Version 77.0.3865.90
BUT
in Mozilla Firefox (version 69.0.1) POST method changes to GET with this error
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent.
Request URL: http://localhost:3000/...
Request method: GET
Status code: 200
<form class="form-horizontal" id="form" >
<div class="col">
<label for="images" class="control-label">image</label>
<input type="file" class="form-control" name="images" id="images" >
</div>
<div class="form-group row">
<div class="col">
<button type="submit" class="btn btn-danger">Send</button>
</div>
</div>
</form>
<script>
document.getElementById('form').addEventListener('submit' , async function(event) {
let images = document.querySelector('input[name="images"]');
let formData = new FormData();
formData.append('images' , images.files[0] );
try {
const response = await fetch('http://exampleurl.com/profile', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': "<%= req.csrfToken() %>",
},
body: formData,
credentials: 'same-origin'
});
} catch (error) {
console.error(error);
}
})
</script>
I can't use method ="POST" and enctype= "multipart/form-data" in the form because csrf tokens can't implement in forms with multipart/form-data enctype
I suspect your form might be submitting twice.
1) AJAX event handler
2) The submit button in the form actually posting the form through html
Try adding the event handler to the form itself, rather than the submit button.
There you can prevent the form from doing what it wants to do so only your AJAX request will go through.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event

i want to send file to api url and get the response without redirecting to it using ajax

the code below is form with action api link
and thats my ajax request
$('#form1').submit(function(e) {
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: formdata,
success: function(data) {
alert(data);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://www.example.com/uploader" id="myForm" method="post" name="myForm">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
when i send a file to that api it respond with data i want to get this data without redirecting to it this code in wordpress site
You need to add enctype in form tag and use preventDefault to prevent the refresh of page.
You need to serialize the data and send in data.
On the success area you need to deal with response.
HTML
<form action="http://www.example.com/uploader" id="form1" method="post" name="myForm" enctype="multipart/form-data">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
JS
$('#form1').submit(function(e){
e.preventDefault();
let data = $( this ).serialize()
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: data,
success: function(response){
// success action here
},
error: function(response) {
// error action here
}
});
});
You just need to add the following code to your function in your submit event.
e.preventDefault();
because, normally it would submit the form.

form data upload multiple files through ajax together with text fields

Good day all,
I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.
The following is the javascript code submitting the form data.
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
And, the following is the actual form:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?
Any help would be greatly appreciated.
Thanks!
Here is ajax, html and php global you can access. Let me know if it works for you.
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Updated HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
Now, in PHP, you should be able to access your files:
// i.e.
$_FILES['file-0']
Here's another way.
Assuming your HTML is like this:
<form id="theform">
<textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
<!-- note the use of [] and multiple -->
<input type="file" name="image[]" id="picture" multiple>
<input name="update" value="Send" type="submit" class="update" id="update">
</form>
You could simply do
$("#theform").submit(function(e){
// prevent the form from submitting
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
// pass the form in the FormData constructor to send all the data inside the form
data: new FormData(this),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Because we used [], you would be accessing the files as an array in the PHP.
<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>
More information:
FormData constructor
Multiple file input

Send form data with jquery ajax json

I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.

Categories

Resources