How to send data from view to controller laravel with ajax? - javascript

I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
my html code is :
I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
<ul name="ali" id="singleFieldTags" class="tagit ui-widget ui-widget-content ui-corner-all">
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">reza</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">ali</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-new">
<input type="text" class="ui-widget-content ui-autocomplete-input" autocomplete="off">
</li>
</ul>
<form id="form" method="post" action="/save_new" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="choose-file" class="custom-file-upload" id="choose-file-label">
Click Here to upload image
</label>
<br/>
<br/>
<label >no image selected !</label>
<input name="uploadDocument" type="file" id="choose-file"
accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
</div>
<div class="form-group">
<label for="title">Description</label>
<textarea name="meta_description" class="form-control"></textarea>
</div>
<div class="form-group">
<label >keywords</label>
<input name="tags" id="mySingleField" value="reza,ali" type="hidden" disabled="true">
<ul name="ali" id="singleFieldTags"></ul>
</div>
<button type="submit" onclick="myF()" class="btn btn-success pull-left"> save</button>
</form>
in my javascript
<Script type="text/javascript">
function myF() {
var data2 = [];
var inputs = $(".tagit-choice");
for (var i = 0; i < inputs.length; i++) {
data2[i] = $(inputs[i]).text();
}
$.ajax({
url:'/save_new',
type: 'POST',
dataType:'json',
// data: JSON.stringify(data2),
data: JSON.stringify(data2),
contentType: 'application/json; charset=utf-8',
success: function( data ){
console.log('ok');
console.log(data);
},
error: function (xhr, b, c) {
console.log('error');
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
}
when i send data from ajax i have error in console
error reza:263:37
xhr=[object Object] b=error c=
but in Request JSON
i see
0 "reza×"
1 "ali×"
Please help me Thanks
my controller is :
public function save_new(Request $request){
// dd($request->all());
dd($request->getContent());
}
my route is :
Route::POST('/save_new','Backend\AdminPostController#save_new')->name('save_new');
edit:
my problem is solved thans you all
var fd = new FormData();
var file = $("#form input[name=uploadDocument]")[0].files;
fd.append('file', file[0]);
fd.append('title', $("#form input[name=title]").val());
fd.append('description', $("#form textarea[name=meta_description]").val());
fd.append('tags', JSON.stringify(data2));
$.ajax({
type: 'post',
url: '/ok2',
contentType: false,
processData: false,
data: fd,
success: function(response) {
},
error: function (response) {},
});

I'm not sure about your work but this is one of the basic method to send data via jquery make sure to put ajaxSetup in document.ready function
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#form').on('submit',function(){
$.ajax({
type:'post',
url:$("#form").attr('action'),
data:$("#form").serializeArray(),
success:function(data){
//response
console.log(data);
}
});
});

Related

Send input type file without using submit button

I have the form to attach the document and the js to send the data to php as follows:
function update_estado()
{
var dadosajax = {
'Fornecedor' : $("#Fornecedor3").val(),
'arquivo': $("#arquivo").val(),
}
$.ajax({
url: 'pedencom.php',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
swal("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
},
success: function(result2)
{
$('.limp9')[0].reset();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" class="limp9" id="forarq" method="post" enctype="multipart/form-data">
<div class="form-group col-md-3">
<select class="form-control1 spoiler4" name="Fornecedor" id="Fornecedor3" required>
<option value="xxxxxx#hotmail.com">xxxxxx#hotmail.com</option> </select>
<label class="label1" for="Fornecedor3">Email Fornecedor</label>
</div>
<div class="row clearfix" style="margin-top: -1%;">
<span class="btn fileinput-button" style="color: black;">
<i class="glyphicon glyphicon-plus" style="color: black;"></i>
<span style="color: black;">Add Arquivo...</span>
<input type="file" class="form-control" style="height: 62%;" id="arquivo" name="arquivo">
</span>
</div>
<div class="h4 mb-4" style="float:right; line-height: 2;">
<button type="button" class="btn btn-raised btn-default ripple-effect" onclick="update_estado()">Gravar <i class="fa fa-paper-plane"></i></button>
</div>
</form>
The variable with the email sends, but the input type file variable is empty.
I want to send both variables without submitting by clicking the save button.
you can do this
function update_estado()
{
// here is my code
var pedpront = [];
$.each($("input[name='updorc1[]']:checked"), function(){ pedpront.push($(this).val()); });
let formData = new FormData(document.querySelector("#forarq"))})
// get the values here and insert in key value pair down below
formData.append("pedprontData",pedpront)
$.ajax({
url: 'pedencom.php',
type: 'POST',
cache: false,
data:,formData
error: function(){
$(".error_message").removeClass('hide');
swal("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
},
success: function(result2)
{
$('.limp9')[0].reset();
}
});
}
You can use this function and keep in mind that reader.result is file content string
base64encoded which means you need to decode it on server-side to get original content and save it.
function update_estado()
{
var file = $('#arquivo')[0].files[0];
var filename = file.name;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload=function() {
var dadosajax = {
'Fornecedor' : $("#Fornecedor3").val(),
'arquivo': reader.result,
}
$.ajax({
url: 'pedencom.php',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
swal("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
},
success: function(result2)
{
$('.limp9')[0].reset();
}
});
}
}

AJAX formData not working

I'm struggling with formData in Ajax calls. I read everything I could with the same information, tried get the form with this, getElementById and nothing works (even tried several solutions from SO).
I have a form with id add-lang-form:
<form class="js-validation-addlang" method="post" enctype="multipart/form-data" id="add-lang-form" name="add-lang-form">
<div class="form-group row">
<label class="col-6 col-form-label">Language Name</label>
<label class="col-6 col-form-label">Language Code</label>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="lang_name" name="lang_name">
<span class="input-group-addon"><i class="fa fa-file"></i></span>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="lang_code" name="lang_code">
<span class="input-group-addon"><img src="/assets/img/flags/def.png" id="flag-icon"/></i></span>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-12" for="lang_tags">Language Tags</label>
<div class="col-lg-12">
<div class="input-group">
<input type="text" class="form-control" id="lang_tags" name="lang_tags">
<span class="input-group-addon"><i class="fa fa-list"></i></span>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-12">Image</label>
<div class="col-md-12">
<input type="file" id="lang_img" name="lang_img" class="dropify" />
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<button type="submit" class="btn btn-alt-primary pull-right">Submit</button>
</div>
</div>
</form>
And I have a function that is called after form validation with submitHandler:
function AddLang(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var form = document.getElementById('add-lang-form');
var formData = new FormData(form);
$.ajax({
url: 'PHP_FILE',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: {
dados: formdata,
caller: 'addlang',
},
type: 'POST',
beforeSend: function() {
$("#login_btn").html('<i class="fa fa-2x fa-cog fa-spin"></i>');
$("#login_btn").attr("disabled", true);
},
success: function(output) {
if (output == "OK") {
alert("OK");
} else {
alert(output);
}
}
});
};
I tried creating the formData directly, everything and nothing works.
The $_POST['dados'] is not set. Any clue of whats going on?
you can't use a FormData object as the value of a parameter, it has to be the entire data: value. If you want to add additional parameters, use FormData.append().
function AddLang(e) {
//var data = $("#add-lang-form").serialize();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var form = document.getElementById('add-lang-form');
var formData = new FormData(form);
formData.append('caller', 'addlang');
$.ajax({
url: 'PHP_FILE',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: formData,
type: 'POST',
beforeSend: function() {
$("#login_btn").html('<i class="fa fa-2x fa-cog fa-spin"></i>');
$("#login_btn").attr("disabled", true);
},
success: function(output) {
if (output == "OK") {
alert("OK");
} else {
alert(output);
}
}
});
};

I'm trying to upload a file using node and ajax but the ajax call isn't working?

I'm facing error on Upload xml and upload csv am a rookie so please can you provide me a elaborate answer
I've tried debugging the code on clicking upload button till upload function is working fine on jumping to uploadxml() function the data is not sent.
My HTML code
<div class="file-upload">
<form id="file-upload-form">
<div class="upload">
<div class="col-lg-6">
<div class="input-group" id="one">
<input type="text" class="form-control" id="t1" placeholder="Select an xml file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="xmlbtn">Browse</button>
</span>
</div>
<input type="file" accept=".xml" class="hidden" id="xmlPicker" name="xmlFile"/>
</div>
<div class="col-lg-6">
<div class="input-group" id="two">
<input type="text" class="form-control" id="t2" placeholder="Select an csv file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="csvbtn">Browse</button>
</span>
</div>
<input type="file" class="hidden" accept=".csv" id="csvPicker" name="csvFile"/>
</div>
</div>
<div class="uploadfooter">
<button class="btn btn-default center" type="button" id="upload">Upload</button>
</div>
</form>
</div>
My Js
$(document).ready(function () {
$(".ts-sidebar-menu li a").each(function () {
if ($(this).next().length > 0) {
$(this).addClass("parent");
};
})
var menux = $('.ts-sidebar-menu li a.parent');
$('<div class="more"><i class="fa fa-angle-down"></i></div>').insertBefore(menux);
$('.more').click(function () {
$(this).parent('li').toggleClass('open');
});
$('.parent').click(function (e) {
e.preventDefault();
$(this).parent('li').toggleClass('open');
});
$('.menu-btn').click(function () {
$('nav.ts-sidebar').toggleClass('menu-open');
});
$('#zctb').DataTable();
$("#input-43").fileinput({
showPreview: false,
allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
elErrorContainer: "#errorBlock43"
// you can configure `msgErrorClass` and `msgInvalidFileExtension` as well
});
$("#xmlbtn").bind("click", function(){
$("#xmlPicker").trigger("click");
});
$("#xmlPicker").bind("change", function(e){
$("#t1").val($("#xmlPicker")[0].files[0].name);
})
$("#csvbtn").bind("click", function () {
$("#csvPicker").trigger("click");
});
$("#csvPicker").bind("change", function (e) {
$("#t2").val($("#csvPicker")[0].files[0].name)
})
$("#upload").on("click",function () {
var firstfile = $("#t1").val();
var secondfile = $("#t2").val();
if(!firstfile || firstfile != null){
updateXml();
}
if(!secondfile || secondfile != null){
updatecsv();
}
})
function updateXml(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
function updatecsv(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
});
This line here:
var form = $("#file-upload-form").val()
A form does not have a value, its inputs have one. FormData expects a form, so you need to give it a reference to it.
var form = $("#file-upload-form");
var data = new FormData(form[0]); //expects a DOM form

Sending file together with form data via ajax post

I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.
Undefined Index :- File
Here's my code.
HTML
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
Ajax
$("#add_product").click(function(e) {
e.preventDefault();
product_name = $("product_name").val();
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $("#add_new_product").serialize(),
success: function(response) {
//
alert(response);
}
})
});
PHP
if (0 < $_FILES['file']['error']) {
echo ":!";
} else {
echo "ASa";
}
What am I missing here?
Can you try using FormData():
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The above is a sample code, but you may use it to modify it.
you can use FormData
$("#add_product").click(function(e) {
e.preventDefault();
var fdata = new FormData()
fdata.append("product_name", $("product_name").val());
if ($("#file")[0].files.length > 0)
fdata.append("file", $("#file")[0].files[0])
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: fdata,
contentType: false,
processData: false,
success: function(response) {
//
alert(response);
}
})
});
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
We need to acknowledge first is that we need to APPEND both Form Input Data and Form File(s) into a single FormData variable.
Here is my solution in which I have enabled Multi File option so that this solution can fit for all examples.
It is Important to include name attribute in the input controls to make it work properly on server side in most of cases. If you are using C# then you can use simply Request.Form["nameAttribute"] to simply get the function. It is similar for Java and other languages.
My Sample Code is
$(document).ready(function () //Setting up on Document to Ready Function
{
$("#btnUpload").click(function (event) {
//getting form into Jquery Wrapper Instance to enable JQuery Functions on form
var form = $("#myForm1");
//Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
var params = form.serializeArray();
//Getting Files Collection
var files = $("#File1")[0].files;
//Declaring new Form Data Instance
var formData = new FormData();
//Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
//Now Looping the parameters for all form input fields and assigning them as Name Value pairs.
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
//disabling Submit Button so that user cannot press Submit Multiple times
var btn = $(this);
btn.val("Uploading...");
btn.prop("disabled", true);
$.ajax({
url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc
method: "post",
data: formData,
contentType: false,
processData: false,
success: function () {
//Firing event if File Upload is completed!
alert("Upload Completed");
btn.prop("disabled", false);
btn.val("Submit");
$("#File1").val("");
},
error: function (error) { alert("Error"); }
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" id="myForm1">
<p><textarea id="TextArea1" rows="2" cols="20" name="TextArea1"></textarea></p>
<p><input id="File1" type="file" multiple="multiple" /></p>
<input id="btnUpload" type="button" value="Submit" />
</form>
For a working example (asp.net C# with handlers) you can visit sample code on https://github.com/vibs2006/HttpFileHandlerFormDataSample

Pass an image through AJAX [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....

Categories