I have this problem that i cant seem to solve, for sure is a noob thing but here it goes, i'm trying to past values and upload file using the same form, but the file is not passing to the php function.
my html with ajax:
<form name="create_batch" method="post" role="form">
<input type="hidden" name="token" value="<?= \Middlewares\Csrf::get() ?>" required="required" />
<input type="hidden" name="request_type" value="create" />
<input type="hidden" name="project_id" value="<?= $data->project->project_id ?>" />
<input type="hidden" name="type" value="batch" />
<div class="notification-container"></div>
<div class="form-group">
<label><i class="fa fa-fw fa-signature fa-sm mr-1"></i> <?= $this->language->create_link_modal->input->location_url ?></label>
<input type="text" class="form-control" name="location_url" required="required" placeholder="<?= $this->language->create_link_modal->input->location_url_placeholder ?>" />
</div>
<div class="form-group">
<input type="file" name="file">
</div>
<div class="form-group">
<label><i class="fa fa-fw fa-link"></i> <?= $this->language->create_link_modal->input->url ?>
</label>
<input type="text" class="form-control" name="url" placeholder="<?= $this->language->create_link_modal->input->url_placeholder ?>" />
</div>
<div class="text-center mt-4">
<button type="submit" name="submit" class="btn btn-primary"><?= $this->language->create_link_modal->input->submit ?></button>
</div>
</form>
<script>
$('form[name="create_batch"]').on('submit', event => {
$.ajax({
type: 'POST',
url: 'link-ajax',
data: $(event.currentTarget).serialize(),
success: (data) => {
if(data.status == 'error') {
let notification_container = $(event.currentTarget).find('.notification-container');
notification_container.html('');
display_notifications(data.message, 'error', notification_container);
}
else if(data.status == 'success') {
/* Fade out refresh */
fade_out_redirect({ url: data.details.url, full: true });
}
},
dataType: 'json'
});
event.preventDefault();
})
</script>
this will post the data to the php file and the respective funtion, but only the fields are passing through. The file, that is a csv, is not passing. for sure i have something wrong on my ajax script that is only allow to pass the values of the form via post but not the file.
my php is something like this:
<?php
if(!empty($_FILES)){
$fh = fopen($_FILES['file']['tmp_name'], 'r+');
$i=0;
$lines = array();
while( ($row = fgetcsv($fh, 8192)) !== FALSE ) {
$lines[] = $row;
$location_url = $lines[$i][0];
$url = $lines[$i][1];
$umt_source = $lines[$i][2];
$utm_medium = $lines[$i][3];
$utm_campaign = $lines[$i][4];
$utm_term = $lines[$i][5];
$utm_content = $lines[$i][6];
$i=$i+1;
}
fclose($fh);
}
$_POST['project_id'] = (int) $_POST['project_id'];
$_POST['location_url'] = trim(Database::clean_string($_POST['location_url']));
$_POST['url'] = !empty($_POST['url']) ? get_slug(Database::clean_string($_POST['url'])) : false;
...........
Any help? Many thanks.
In order to send multipart form data, you need to create and send a form data object.
see example below -
var formdata = new FormData($('#formId')[0]);
$.ajax({
url: URL,
type: 'POST',
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function (response) {
$('#responseMsg').html(response.msg);
}
});
On server end you can get your data by $_POST and files by $_FILES
the solution.
$("form#create_batch").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'link-ajax',
type: 'POST',
data: formData,
dataType: 'json',
success: (data) => {
if(data.status == 'error') {
let notification_container = $(event.currentTarget).find('.notification-container');
notification_container.html('');
display_notifications(data.message, 'error', notification_container);
}
else if(data.status == 'success') {
/* Fade out refresh */
fade_out_redirect({ url: data.details.url, full: true });
}
},
cache: false,
contentType: false,
processData: false
});
});
Related
I've built a simple form that posts data using jQuery AJAX to a PHP endpoint.
Everything works fine and the data is all being posted correctly.
The problem I am having is once the file is added to the input and submitted, the page refreshes. It doesn't refresh if I don't add the file, and doesn't refresh if I take the file input out altogether. Only when the file is successfully moved.
I need the page not to refresh, hence the use of AJAX in the first place.
Form:
<form id="form-send">
<div class="c-form-group grid-2">
<label for="first_name">First Name</label>
<input class="c-form-control" type="text" id="first_name" name="first_name" placeholder="Joe" value="Joe">
</div>
<div class="c-form-group grid-2">
<label for="file">Add File</label>
<input class="c-form-control c-form-control--file" type="file" id="file" name="file">
</div>
<div class="c-btn-group">
<button id="send" class="c-btn c-btn--primary" type="submit">Submit</button>
</div>
</form>
Ajax:
$("#form-send").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '/send-form.php',
cache: false,
processData: false,
contentType: false,
data: new FormData(this),
success: function(data) {
console.log(data);
},
error: function(response) {
console.log('An error ocurred.');
},
});
})
Endpoint:
<?php
$uploadDir = 'uploads/';
// If post
if (isset($_POST)) {
// Request Values
$firstname = $_REQUEST['firstname'];
$file = $_REQUEST['file'];
// Upload to folder
if(!empty($_FILES["file"]["name"])){
// File path config
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
echo "Success: File uploaded.";
} else {
echo "Error: Something went wrong.";
}
} else{
echo "Error: File is not the correct format.";
}
}
}
?>
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("#form-send").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '/send-form.php',
cache: false,
processData: false,
contentType: false,
data: new FormData(this),
success: function(data) {
console.log(data);
},
error: function(response) {
console.log('An error ocurred.');
},
});
});
You can remove the form tag that is responsible for refreshing the page. Else, you can change button to
<button id="send" class="c-btn c-btn--primary" type="button">Submit</button>
This is how I am able to achieve in one of my projects.Hope it helps
AJAX CALL:
var form_data = new FormData();
form_data.append('title',title);
form_data.append('body',body);
form_data.append('link',link);
$.ajax
({
url: 'blog_insert.php',
dataType: 'text',
cache : false,
contentType : false,
processData : false,
data: form_data,
type: 'post',
success: function(php_script_response)
{
$("#success-message").css('display','active').fadeIn();
var title = $('#title').val(' ');
var body = $('.nicEdit-main').html('');
//$('#sortpicture').prop(' ')[0];
var link = $('#link').val('');
}
});
HTML
Blog posted successfully
<div class="form-group">
<label for="exampleFormControlInput1">Blog Title</label>
<input type="text" class="form-control" required="" name="title" id="title" placeholder="Enter your blog title">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Write your blog body here</label>
<textarea class="form-control" name="body" id="body" ></textarea>
</div>
<div id="dropzoneFrom" class="dropzone">
<div class="dz-default dz-message">Test Upload</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Reference Link</label>
<input type="text" class="form-control" id="link" name="link" placeholder="Post a reference link">
</div>
<button type="submit" id="submit-all" class="btn btn-primary" name="submit" >Post</button>
I want to send data on the controller into JSON format. but getting into a string. so can I do this?
I used header that is being passed on ajax call but it not converting Form filed into JSON format .
due to string format Laravel not able to process this response.
My Browser Response.
HTML Code
<form id="NoeticeBoardGetAllFrm" name="NoeticeBoardGetAllFrm" role="form" method="post" >
<div class="row">
<div class="col-sm-6">
<label> URL </label>
<input type="text" name="NoeticeBoardGetAllUrl" id="NoeticeBoardGetAllUrl"
class="form-control" placeholder="URL"
value="https://XXXXXXXXXXXX/get-all-notice-board-information"/>
</div>
<div class="col-sm-4">
<label> Session Code </label>
<input type="text" name="scode" id="scode" class="form-control"
value="cFZnMVJUY0JNUUJsTXZBeVZhZmRHZz09"
maxlength="50" minlength="32" placeholder="Session Code"/>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">
<input type="submit" name="NoeticeBoardGetAllBtn" id="NoeticeBoardGetAllBtn"
class="btn btn-danger " value="Get Result" />
</div>
<div class="col-sm-3"> <i class="fa fa-reddit-square"></i>
<span class="inLine">Result :</span>
<div id="NoeticeBoardGetAllResult" class="inLine result_box">---</div>
</div>
</div>
</form>
My Javascript Code
$("#NoeticeBoardGetAllFrm").submit(function(e) {
e.preventDefault();
console.log( new FormData(this));
$.ajax({
url: $("#NoeticeBoardGetAllUrl").val(),
type: 'POST',
headers: {'Accept': 'application/json','Content-Type': 'application/json',
'DBAuth': $("#DBAuth").val(),'Authorization': $("#Authorization").val(),},
dataType: 'json',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
if (data.error == 0) {
$("#NoeticeBoardGetAllResult").html("Record fetched successfully!");
$("#NoeticeBoardGetAllResult").addClass("alert alert-success");
} else {
$("#NoeticeBoardGetAllResult").html(data.errmsg);
$("#NoeticeBoardGetAllResult").addClass("alert alert-warning");
}
}, statusCode: {
500: function (data) {
$("#NoeticeBoardGetAllResult").html("Something went wrong!");
$("#NoeticeBoardGetAllResult").addClass("alert alert-danger");
},
401: function (data) {
$("#NoeticeBoardGetAllResult").html("Login Failed");
$("#NoeticeBoardGetAllResult").addClass("alert alert-danger");
}
}
});
setTimeout(function(){ resetResult(); }, 3000);
});
You can use serialize method to send Data as Json
$('#NoeticeBoardGetAllFrm').serialize()
You should use this in place of
data: new FormData(this),
instead of data: new FormData(this);
use following
data: $(this).serializeArray();
It gets your form data and serialize into array that is ready of convert into JSON.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
i am creating the simple crud system using php ajax.in the crud system i add the image also.but when i fill the data and browse image and click add button record is not added in to the database.what i tried so far i attached below.no error shown on the console.i think might be the problem with jquery
send the form values and images data: {form_data: form_data,data: data},
Form Design
<form role="form" id="frmcompany" class="card" enctype="multipart/form-data">
<div align="left">
<h3>Company</h3>
</div>
<div align="left">
<label class="form-label">Company name</label>
<input type="text" class="form-control" placeholder="Patient No" id="cno" name="cno" size="30px" required>
</div>
<div align="left">
<label class="form-label">Country</label>
<input type="text" class="form-control" placeholder="Patient Name" id="coutry" name="coutry" size="30px" required>
</div>
<div align="left">
<label class="form-label">Currency</label>
<input type="text" class="form-control" placeholder="Phone" id="currency" name="currency" size="30px" required>
</div>
<div align="left">
<label class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Address" id="address" name="address" size="30px" required>
</div>
<div align="left">
<div class="fileuploader fileuploader-theme-default">
<input type="hidden" name="fileuploader-list-files_" value="[]">
<input type="file" id="file" name="file" >
<div class="fileuploader-items">
<ul class="fileuploader-items-list"></ul>
</div>
</div>
</div>
</br>
<div align="right">
<button type="button" id="save" class="btn btn-info" onclick="addPatient()">Add</button>
<button type="button" id="clear" class="btn btn-warning" onclick="reset()">Reset</button>
</div>
</form>
jquery
function addPatient()
{
var upload_date = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', upload_date);
if($("#frmcompany").valid())
{
var url = '';
var data = '';
var method = '';
if(isNew == true)
{
url = 'php/add_patient.php';
data = $('#frmcompany').serialize() ;
method = 'POST';
}
$.ajax({
type : method,
url : url,
dataType : 'JSON',
cache: false,
contentType: false,
processData: false,
// data: data,
data: {form_data: form_data,data: data},
success:function(data)
{
if (isNew == true) {
alert("Company Addedd");
}
}
});
}
}
$('#file').fileuploader
({
limit: 1,
});
<div align="right">
<button type="button" id="save" class="btn btn-info" onclick="addPatient()">Add</button>
<button type="button" id="clear" class="btn btn-warning" onclick="reset()">Reset</button>
</div>
</form>
php code
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error)
{
die("connection failed" . $conn->connect_error);
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (0 < $_FILES['file']['error'])
{
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else
{
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
$stmt = $conn->prepare("insert into company(companyname,coutry,currency,address,image) VALUES (?,?,?,?,?)");
$stmt->bind_param("ssss",$companyname,$coutry,$currency,$address,$image);
$companyname = $_POST['cno'];
$coutry = $_POST['coutry'];
$currency = $_POST['currency'];
$address = $_POST['address'];
$image = $_FILES['file']['name'];
if($stmt->execute())
{
echo 1;
}
else
{
echo 0;
}
$stmt->close();
}
?>
You can't send a FormData object inside another object. All the POST parameters have to be in form_data.
function addPatient() {
if ($("#frmcompany").valid()) {
var url = '';
var data = '';
var method = '';
var form_data = new FormData(document.getElementById("frmcompany"));
var upload_date = $('#file').prop('files')[0];
form_data.append('file', upload_date);
if (isNew == true) {
url = 'php/add_patient.php';
data = $('#frmcompany').serialize();
method = 'POST';
}
$.ajax({
type: method,
url: url,
dataType: 'JSON',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
if (isNew == true) {
alert("Company Addedd");
}
}
});
}
}
function addPatient()
{
var upload_date = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', upload_date);
$.ajax({
url: 'php/add_patient.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
I have an user information form in my Laravel site and trying to upload image using Ajax.
Blade
<form id="edit_form" enctype="multipart/form-data">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
<div class="form-group">
<label>Image</label>
<input id="edit_form_image" type="file" class="form-control" name="user_image">
</div><!-- end form-group -->
<div class="form-group">
<label>Name</label>
<input id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
</div><!-- end form-group -->
<button type="button" id="edit_form_submit" class="btn btn-orange">Save Changes</button>
Ajax
$('#edit_form_submit').click(function(event) {
var fd = new FormData();
var edit_form_image = $('#edit_form_image')[0].files;
var edit_form_name = $('#edit_form_name').val();
var token = $('input[name=_token]').val();
fd.append( 'image', edit_form_image );
fd.append( 'name', edit_form_name );
fd.append( '_token', token );
$.ajax({
url:"{{ url('/profile-update') }}",
data: fd,
async:false,
type: 'POST',
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
But in my controller I can't get the image file.
controller
if (request()->hasFile('image'))
{
return "file present";
}
else{
return "file not present";
}
Though I upload an image controller always response that `file no present'.
Where is the error? Anybody Help please ?
why dont you name your input tags as you need to send in post method in :
<input name="image" id="edit_form_image" type="file" class="form-control">
<input name="name" id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
And,
$("#edit_form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url:"{{ url('/profile-update') }}",
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
This might works.
I am trying to upload a file with ajax and php without page refresh and for submit.
my code is able to run and alert the valid message if I just do the preg_match, but when I add the rest of the validation which need to use the $_FILES[$filrec]["tmp_name"], it won't alert me the valid message.
What is wrong here? isn't it possible to upload the file without submitting the form with the following method?
There are bunch of different suggestions and examples with more complicated javascript or jquery methods, but I am trying to simply the ajax and leave the rest for PHP. is that possible with my bellow ajax function ?
Javascript :
var fileselected = $("#browse").val().replace(/C:\\fakepath\\/i, '');
setTimeout(function() {
$.ajax({
type: 'POST',
url: "ajax/extval.php",
data: {fileprs: fileselected},
dataType: 'json',
cache: false,
success: function(resuval) {
// file validation result
if (resuval === "valid"){
alert ("valid")
PHP :
<form id="upload" method="post" class="<?php echo $orvalue."<separator>".$user_id ?>" action="" enctype="multipart/form-data">
<div id="formcontent">
<label class="required" for="unitprice" title="Unit price"><input type="text" id="unitprice" name="unitprice" />Unit price</label>
<label class="required" for="qty" title="How many pcs"><input type="text" id="qty" name="qty" />Quanity</label>
<label class="required" for="express" title="Express within China"><input type="text" id="express" name="express" />Express</label>
<label class="required" for="linkURL" title="Insert a full URL http:\\"><input type="text" id="linkURL" name="linkURL" />Link</label>
<label for="yourdesc" title="Describe your need clearly"><textarea id="yourdesc" name="yourdesc"></textarea>Description<li><font size="-2">You can type 400 letters only, you typed :</li><li id="lettercounter"></li>letters</font></label>
<label for="formsubmit" class="nocontent"><input type="button" id="submitButton" href="#" class="progress-button" value="Add to order" /><strong>Note:</strong> Items marked <img src="../../images/required.jpg" alt="Required marker" width="20" height="20" /> are required fields</label>
</div>
</form>
PHP :
$filrec =mysql_real_escape_string($_POST['fileprs']);
if(preg_match("/\.(gif|png|jpg|JPG|jpeg|bmp|BMP)$/", $filrec))
{
$fileType = exif_imagetype($_FILES[$filrec]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
$allin = "valid";
echo json_encode($allin);
}
Appreciated
You can use the following PHP code to get the file received from Ajax:
$data = split(",",file_get_contents('php://input'));
$img_data = base64_decode($data[1]);
file_put_contents( 'uploads/' . $_SERVER['HTTP_X_FILENAME'],
$img_data );
You can use Following Ajax POST Request this will help you
<script>
$(document.body).on('click','.postDefects',function(){
var form_data = new FormData();
var defect = $(this).closest('tr').find( "input[name='defect_id']" ).val();
var txt_defect=$("#text_defect").val();
var upload_defect = document.getElementById("upload_defect").files[0];
form_data.append("upload_defect",upload_defect);
form_data.append("defect_id",defect_id);
form_data.append("txt_defect",txt_defect);
console.log(form_data);
$.ajax({
url:"postsample_defects.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading..</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
});
});
</script>