File submit failing with jQuery's Form Data() and Ajax - javascript

I have created a form to upload two files - questionpaper and the key. But the Ajax request is not working in an intended manner. I have been trying and trying but unable to figure out the bug. Please help.
Here is my form.
<form name="facform" id="facform" data-abide="ajax" enctype="multipart/form-data">
<fieldset>
<legend> All fields are required </legend>
<div class="row">
<div class="large-3 medium-3 columns">
<label> <b> Upload Question Paper </b> </label>
<input type="file" id="qfile" name="qfile" tabindex="7" required>
</div>
<div class="large-3 medium-3 columns end">
<label><b> Upload Key </b></label>
<input type="file" id="kfile" name="kfile" tabindex="8" required>
</div>
</div>
</fieldset>
<div class="row">
<div class="large-6 medium-6 columns">
<label><img id="loadingimg" src="http://dev.cloudcell.co.uk/bin/loading.gif"/></label>
<input id="form-submit" type="submit" class="button tiny" value="Submit" />
</div>
</div>
</form>
Here goes the javascript part.
<script>
//-----------------------//
$('#facform').on('valid.fndtn.abide', function() {
var fileInput = document.getElementById('facform');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('qfile', file);
formData.append('kfile', file);
var form_url = 'getfiles.php';
$("#form-submit").hide();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: 'POST',
data: formdata,
processData: false,
cache: false,
success: function(returnhtml){
$("#loadingimg").hide();
$("#facform").hide();
$("#smsg").html(returnhtml);
$("#facform")[0].reset();
}
//-----------------------//
});
});
</script>

to upload files using Ajax or jQuery , you need to use hidden iframe
this is full example for ajaxfileupload.js class allow you to use upload form .
or you could create simple function to submit your form into hidden iframe then get the iframe body html or text using jQuery as response .
<html>
<head>
<link href="http://www.phpletter.com/css/general.css" rel="stylesheet" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://www.phpletter.com/contents/ajaxfileupload/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{
$.ajaxFileUpload
(
{
//YOUR URL TO RECEIVE THE FILE
url: 'http://localhost/testing/postfile.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(data.error);
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<form name="form" action="" method="POST" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" class="tableForm">
<thead>
<tr>
<th>Ajax File Upload</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input"></td>
</tr>
<tr>
<td>Please select a file and click Upload button</td>
</tr>
</tbody>
<tfoot>
<tr>
<td><button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button></td>
</tr>
</tfoot>
</table>
</form>
</body>
</html>

Related

How to call api path in thymeleaf to reload table data in javascript function

I need click the submit button to reload table data,
But in javascript function , I don't known how to call the url pass parameters in thymeleaf.
I call this web page is below:
.....[menu partial code]....
<a class="dropdown-item" th:href="#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}">user list</a>
.....
the query and content Page:
<form >
<div class="col-sm-3 my-1">
<label class="sr-only" for="inlineFormInputName">Name</label> <input
type="text" class="form-control" id="inlineFormInputName"
placeholder="user name">
</div>
<div class="col-auto my-1">
<button type="submit" class="btn btn-primary query-submit"
id="querySubmit">Submit</button>
</div>
</div>
</form>
.....
<div class="row mt-5" th:fragment="table_content">
<div class="col">
...
<table class="table table-responsive table-hover">
<tbody>
<tr th:each="users,iter : ${response.content}">
<th scope="row" th:text="${iter.index+1}"></th>
<td class="text-info text-center"
th:text="${users.name}"></td>
</tr>
</tbody>
</table>
</div>
</div>
.....
I don't know the syntax in thymeleaf , if I need pass the params and call api in the js function. If the url will write #{/registeredUserList(type=0,userId=id0001,page=0,size=10)} like menu path, how can I write the syntax in the js function at url.
thank you~
$(function() {
$('#querySubmit').click(querySubmitClickAction);
querySubmit.addEventListener('click', querySubmitClickAction);
function querySubmitClickAction(e) {
$.ajax({
url: url, // here , I don't know syntax, I can't use [#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}] the path in here . how can I write the syntax.
type: 'POST',
success: function (data) {
$(".table_content").html(data);
}
})
}
});
</script>
Use th:inline="javascript" and the /*[[#{/url/}]]*/ syntax:
<script th:inline="javascript">
$(function() {
$('#querySubmit').click(querySubmitClickAction);
querySubmit.addEventListener('click', querySubmitClickAction);
function querySubmitClickAction(e) {
$.ajax({
url: /*[[#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}]]*/ 'dummy',
type: 'POST',
success: function (data) {
$(".table_content").html(data);
}
})
}
});
</script>

Controller method is not detecting any parameter

I'am trying to send an id in my url but my controller doesn't get that value
$("#ChangeSlideForm").on("submit", function(){
$.ajax({
type: "POST",
url: base_url + "Visualiser/ChangeSlide/21",
success: function (response) {
alert(response);
// $("#deleteConfirm").modal('hide');
// jQuery(function RefreshPageAdd($){
// $('#deleteConfirm').on('hidden.bs.modal', function (e) {
// location.reload();
// });
// });
}
});
});
My View
<div id="bodyChange" class="modal-body">
<form id = "ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<label class="btnSlide btn btn-outline-success">
Zip <input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success">
Csv <input class="file" name ="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</form>
My controller header :
public function ChangeSlide($id){
print_r($id);
}
When I a put the id in the url directly then the parameter is accessible otherwise when I pass with ajax, It doesn't detect the parameter.
Try this:-
The HTML
<form id="ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide/21" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="bodyChange" class="modal-body">
<label class="btnSlide btn btn-outline-success"> Zip
<input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success"> Csv
<input class="file" name="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</div>
</form>
The Script:
<script type="text/javascript">
$(document).ready(function(){
$("#ChangeSlideForm").on("submit", function(e){
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serializeArray(),
success : function(data)
{
console.log(data)
},
error: function (xhr)
{
console.log(xhr)
}
});
});
})
</script>
Try this
public function ChangeSlide(){
print_r($this->uri->segment(3));
}
You missing parameter data in $.ajax(). So your ajax didn't send any data to your controller
When you pass value with ajax then controller method get that value as $this->input->post('id'); not as parameter.
So you have to add following to method
public function ChangeSlide($id = "")
{
}

Can't upload multiple files using ajax and php

I'm trying to upload multiple files using jquery and PHP.
But my form data is not being submitted as required to the PHP page.
Please, can someone help me out writing the correct way of uploading files?
Below is my code:
index.php:
<form id="step17Form" action="" name="step17Form" method="post" enctype="multipart/form-data">
<div style="text-align :left; margin-left:15px"> <label><big>
(<span style="color: red; font-family: Comic Sans MS;"><small style="font-weight: bold;">Note: Max File Size - 75KB</small></span>)</big></label>
<br><br>
<table style="text-align: centre; width: 800px; margin-left:15px" border="0" id="upload" cellpadding="6" cellspacing="6">
<tbody>
<tr>
<td><br><label for="stuphoto"><span style="font-family: Comic Sans MS;">1. Student Photo</label></span>
</td>
<td><br><input id="file-upload" name="stuphoto" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
</tr>
<tr>
<td><br><label for="stuadhar"><span style="font-family: Comic Sans MS;">2. Aadhar Card</label></span>
</td>
<td><br><input name="stuadhar" accept=".jpg,.pdf" class="custom-file-upload" type="file" style="display: inline;"></td>
</tr>
</tbody>
</table>
</div>
<br>
<input type="hidden" name="reason" value="step17" />
<button type="submit" id="upload_save" class="btn btn-success"> Save And Next >></button>
</form>
JS:
$('#upload_save').click(function(){
event.preventDefault();
$.ajax({
url: 'controller.php',
type: 'post',
dataType: 'json',
data: new FormData($(this).parents('form')),
processData: false,
contentType: false,
success: function(suc){
alert(suc['msg']);
},
error: function(error){
alert(error);
}
});
});
controller.php:
$reason = $_POST['reason'];
var_dump($_FILES);
if ($reason === "step17" ) {
var_dump($_FILES);
$status=array();
$uploaded_file=array();
$document_type=array("Photo","Aadhar");
$i=0;
$j=0;
foreach($_FILES as $key=>$file)
{
$status= uploadImage($key, $file_size=5000000, "../..".FILE_PATH_LOC );
if($status['error']!==200 && $status['status']===false )
{
echo json_encode(array('status'=>'false','msg'=>"Error ".$file['name']." ".$status['msg']));
break;
}
}
}
Output of var_dump($_FILES):
array(0){
}
The issue I'm facing here is that the data I post is not being recognized in controller.php and control doesn't reach inside the if condition.
You need to make stuphoto as an array. Sor please try to change this line
<td><br><input id="file-upload" name="stuphoto" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
To
<td><br><input id="file-upload" name="stuphoto[]" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
and
foreach($_FILES as $key=>$file)
to
foreach($_FILES['stuphoto']['name'] as $key=>$file)
Your problem is that you are passing a jQuery object as the parameter to the FormData constructor when it takes an html form
$('#upload_save').click(function(event){
event.preventDefault();
$.ajax({
url: 'controller.php',
type: 'post',
dataType: 'json',
data: new FormData(this.form), // pass the form itself to the constructor
processData: false,
contentType: false,
success: function(suc){
alert(suc['msg']);
},
error: function(error){
alert(error);
}
});
});

Unable to Post Data in my JSON File

Unable to Perform Post method on my JSON File
My JSON File is
[{
"name": "Help",
"description": "Deletion not allowed for products!?",
"price": 100000.0 }]
<html>
<head>
<title>Product Management</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/default.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"</script>
<script src="js/bootstrap.min.js"></script>
Function for Getting the Values
<script>
$(document).ready(function() {
$(window).load(function() {
$.ajax({
type: 'GET',
url: 'test.json',
dataType: 'json',
success: function(data) {
$.each(data, function(index, element) {
$("#abc").append($('<li>', {
text: element.name
}))
});
}
});
});
});
</script>
Function for Posting the Values in the JSON file
<script>
function sumbitForm(){
var x=document.getElementById("#name");
var y=document.getElementById("#description");
var z=document.getElementById("#price");
var Product={"name":x, "description":y, "price":z };
$.ajax({
url: "test.json",
type: "POST",
contentType: "application/json",
data: JSON.stringify(Product)
});
}
</script>
</head>
<body>
<div>
<ol id="abc">
</ol>
</div>
<div class="container">
Input Form for posting the Data
<form name="PForm" action="" method="POST">
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control" id="name" placeholder="Product Name">
</div>
<div class="form-group">
<label>Description:</label>
<textarea class="form-control" id="description" placeholder="Descrpition" rows="8"></textarea>
</div>
<div class="form-group">
<label>Price:</label>
<input type="text" class="form-control" id="price" placeholder="Price">
</div>
<button type="submit" class="btn btn-primary Right" onClick="submitForm()">Submit</button>
</form>
</div>
</body>
</html>
You need to get the value of the elements, like
var x=document.getElementById("#name").value;
Else you would send the DOM elements (which, converted to a string, would only be 'object')

JQuery Ajax - File and Data Upload

I am trying to create a form which uploads data and an image in the same submission. I've look all over and I can only seem to find people that are having trouble to upload files alone with JQuery. If I make content-type false then the data dosen't go through only the file. Here is the code:
<form action="/secret/includes/add_listing.php" id="listingfrm" name="listingfrm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div>
<label for="title">Title</label>
<div class="right">
<div class="row">
<div class="col-cst-1">
<input type="text" name="title">
</div>
</div>
</div>
</div>
<div>
<label for="content">Description</label>
<div class="right">
<div class="row">
<div class="col-cst-1">
<textarea name="content" rows="5"></textarea>
</div>
</div>
</div>
</div>
<div>
<label for="image">Upload a Thumbnail</label>
<!-- Browse to Upload Image (No more than 1MB) -->
<div class="right">
<div class="row">
<div class="col-cst-1">
<input type="file" name="listing_thumb" id="listing_thumb">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
function ajax(url, type, data) {
var request
if (type != "none") {
request = $.ajax({
url: url,
type: type,
data: data,
});
} else {
request = $.ajax({
url: url
});
}
return request;
}
$(document).ready(function() {
$(document).on("submit", "#listingfrm", function(event) {
event.preventDefault();
var form = $(this);
var inputs = GetInputs(form);
var serializedForm = form.serialize();
inputs.prop("disabled", true);
var request = ajax("includes/add_post.php", "post", serializedForm)
request.done(function(response, textStatus, jqXHR) {
console.log(response)
})
request.fail = ajax(function(jqXHR, textStatus, errorThrown) {
console.error("Login Error: " + textStatus + " : " + errorThrown)
})
request.always(function() {
inputs.prop("disabled", false);
})
});
});
When using this the title and the description don't go through to the PHP file however if I don't then the image dosen't.

Categories