I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (USD)</label>
<div class="input-group">
<div class="input-group-addon">USD</div>
<input id="moneyAmount" type="number" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" name="months" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal </label>
<!-- Radio -->
<input type="file" name="statements" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">USD<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!</span></button>
</div>
</form>
that i am using to post a file and some data via formData. This is the jquery code
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php',
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
and finally the php script
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$rawData = file_get_contents("php://input");
return print_r($rawData);
?>
On the client side, the console.log(data) is empty. Why am i not able to get the posted data?.
Actually php://input allows you to read raw POST data but
php://input does not work when enctype="multipart/form-data"
for detailed info :
http://php.net/manual/en/wrappers.php.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
echo '<pre>'l
// for upload data
print_r($_FILES);
echo '<br>';
// for posted data
print_r($_POST);
echo '</pre>';
?>
jQuery supported get all form data with function serialize or serializeArray.
In your code use
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
var formData = $( "#home" ).serialize();
$.ajax({
url: 'http://example.com/home.php',
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
});
In PHP use var_dump($_REQUEST) to get all input without file type. With file type you can read PHP Upload File
Form which you are sending through ajax is not correct.
You can give your whole form to FormData() for processing
var form = $('#home')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
use this formData to send with ajax
Related
I have a jQuery function that does the insert of an image with other fields to the database. Currently my function only inserts the image but does not insert the other form fields. I am using formData object and I don't understand how to append my fields together with the image file so I can pass it to the ajax request body.
Here is what I have tried so far:
// submit function
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
var firstname_h = $("#firstname_h").val();
var middlename_h = $("#middlename_h").val();
formData.append(firstname_h, middlename_h);
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// html form
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" id="firstname_h" placeholder="First name" />
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" id="middlename_h" placeholder="Middle name" />
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>
The image name is succesfully inserted in the db and the image is uploaded to the required target location,However, the fields - firstname and middlename are not inserted and I don't understand how to append these properties to the formData.
How can I pass these fields to the formData please?
You can use the following approach for storing the data with image.
1.In PHP API write logic for Upload image to server using move_uploaded_file() & Insert image file name with server path in the MySQL database using PHP.
2.In JS/JQuery, Read all HTML element & create an object & POST it to the API using AJAX Call.
your JS code should be like this. Hope this will help you to fix the issue.
var RegObj = {
'Field1': $("#Field1").val(),
'Field2': $("#Field2").val(),
'logo': $("#company_logo").attr('src'),
}
console.log(RegObj);
$.ajax({
url: "API_PATH_HERE",
type: "POST",
data: JSON.stringify(RegObj),
headers: {
"Content-Type": "application/json"
},
dataType: 'text',
success: function (result) {
//
},
error: function (xhr, textStatus, errorThrown) {
}
});
Like #Professor Abronsius suggested in the comments section I only needed to add the "name" tag to the form elements and remove the append from my function thus, I have edited the function and the form as follows:
// since I have added the name tag to the form elements, there is now
// no need to use the append() thus, I have commented out the append
// lines.
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
// var firstname_h = $("#firstname_h").val(); // removed this
// var middlename_h = $("#middlename_h").val(); // removed this
//formData.append(firstname_h, middlename_h); // removed this
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// added the "name" tag to the form elements
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" name="firstname_h" id="firstname_h" placeholder="First name" /> // added name="firstname_h"
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" name="middlename_h" id="middlename_h" placeholder="Middle name" /> // added name="middlename_h"
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>
I want to POST and upload image via AJAX with Google reCaptcha v2 validation. but I am facing an issue that I am not not able to send image with caption text with google recaptcha token in Ajax. I coded two function as I know but both was not working. The function I made is the code snippet.
Please help me how I send Image with text in Ajax with reCaptcha token in PHP / jQuery/ AJAX.
$(document).ready(function() {
$("form#addbanner").unbind("submit").bind("submit", function(e) {
//debugger;
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('MY_RECAPTCHA_CODE', {
action: 'add_web_banner'
}).then(function(token) {
/*let formData = {
imagehere : $('input[name="imagehere"]').val(),
bannertitle : $('input[name="bannertitle"]').val(),
action : 'add_web_banner',
type: 'add_web_banner'
};*/ //not working
/*let formData = {
var formData = new FormData($("form#addWeb-Banner")[0]);
formData.append('token': token);
};*/ //not working
//*POST Image sent in (binary way), I dont want to use JSON in types*//
$.ajax({
type: 'POST',
data: formData,
cache: false,
success: function(response) {
hide_loader();
if (response.status == "success") {
$("form#addWeb-Banner")[0].reset();
alert("Great");
} else {
alert("Ops!");
}
},
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="bs-example form-horizontal AddWebBanner" id="addbanner" enctype="multipart/form-data" method="POST">
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Upload Image</label>
<div class="col-lg-8">
<input type="file" class="form-control" title="Upload Photo" id="BannerImage" name="imagehere" accept="image/png,image/jpg,image/jpeg" />
</div>
</div>
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Caption of Banner</label>
<div class="col-lg-8">
<input type="text" class="form-control" title="Caption of Banner" name="bannertitle" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-lg-12">
<button type="submit" name="submit" class="btn btn-sm btn-default pull-right" id="addBannerBtn">POST</button>
</div>
</div>
</form>
Change your HTML and formData to the following
Give an id selector your caption banner.
<input type="text" class="form-control" id="caption_banner" title="Caption of Banner" name="bannertitle" />
Store using the formData like this and then sent formData via ajax
var formData = new FormData();
//Append Image
formData.append('file', $('#BannerImage')[0].files[0]);
//Append banner caption
formData.append('caption', $('#caption_banner').val());
You can also use jQuery .serialize method to send data to your backend via ajax
var formData = $('form#addbanner').serialize()
thank for #AlwaysHelping but there was one mistake but I has been fix that..below are the correct answer for future user troubles..
I not mentioned processData: false, contentType: false, in ajax.. so the final code will be..
var formData = new FormData();
formData.append('file', $('#BannerImage')[0].files[0]);
formData.append('caption', $('#caption_banner').val());
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (response) { ... }
peace :)
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.
I have form, with ajax, that contain textarea and upload file field
I can submit only one of them.
how can I fix that?
I want to send "info" + "filesData" to the server.
Please advise.
Thank you in advanced
AJAX :
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var files_data = form_data;
alert(files_data);
var act = 'add';
var $form = $("#addCommentForm");
var info = $form.serialize();
info += '&act=' + act ;
alert(info);
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: files_data,
success: function(data)
{
// alert(data); // show response from the php script.
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false;
});
});
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-8 col-xs-12">
<textarea class="form-control" name="post[text]"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-xs-12">
<input type="file" class="form-control" name="file" id="files">
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label" for="textinput"></label>
<div class="col-md-8 col-xs-12">
<a class="btn btn-primary" id="submit">submit</a>
</div>
</div>
</form>
PHP
print_r ($_FILES);
print_r ($_POST);
In $.ajax call, subtitute the value of data parameter (filesData) by:
{ field1 : field1value, field2 : field2value, .... }
use as many field/value pairs as you need
you also can get the values directly like this:
{ field1 : $('#commentsBox').text(), field2 : $('#yourinput').val(), .... }
I have a form in which Ajax is used to send data to a php file.
THE DATA SENDS PROPERLY...EVERYTHING WORKS FINE...
BUT an "Error loading page" message pops up (using jquerymobile)
html file
<div data-role="page" id="cc">
<div data-role="header">
<h1>Home</h1>
</div>
<div data-role="content">
<form id="cname" align="left" action="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="" />
<input type="submit" value="Submit" data-inline="true">
</form>
<div id="result" style="visibility: hidden"></div>
</div>
</div>
<script type="text/javascript">
$("#cname").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.clubbedin.isadcharity.org/createclub.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#cname").serialize(),
success: function (data) {
$("#result").html(data);
},
});
});
</script>
php file
header("access-control-allow-origin: *");
$name = $_POST['name'];
Your form must also have have this attribute:
data-ajax="false"
Without it jQuery Mobile will initialize its own ajax logic for form posting and you don't want that. Read more about it here or read my other answer on how to properly handle forms in jQuery Mobile.
Try adding this in your JavaScript:
jQuery.support.cors = true;
Try adding
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, *
to your header