function edit_expense(val){
var id = val;
var amount = $('#expense_amount_'+id).val();
var image = $('#img_file_'+id)[0].files[0];
$.ajax
({
type:'post',
url:'{{route('edit_expense')}}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
data: { "_token": "{{ csrf_token() }}",'id':id, 'amount': amount,'image': image },
success:function(data)
{
$('.revnue_updated').removeClass('d-none');
$(".revnue_updated").fadeOut(3000);
}
});
};
Here it is my code , I am getting csrf token mismatch after adding header also. I want to send image value in data but is showing csrf mismatch
You have multiple solutions for this problem.
You can add your route to VerifyCsrfToken middleware (Open app/middleware/verifycsrftoken.php and append your route url to $except array
You can add meta tag to your layout blade meta name is "csrf-token" and content is {{ csrf_token() }}
and add this code to your ajax request
headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
In other hands you can add _token key to your ajax data and use {{csrf_token()}}
Use "Formdata()", below is the working code. I hope it helps.
function edit_expense(val){
var form_data = new FormData();
var id = val;
var amount = $('#expense_amount_'+id).val();
form_data.append('id', id);
form_data.append('amount',amount);
form_data.append('_token', '{{csrf_token()}}');
form_data.append('image',$('#img_file_'+id)[0].files);
$.ajax
({
type:'post',
url:'{{route('edit_expense')}}',
mimeType: "multipart/form-data",
async:true,
dataType: 'json',
cache: false,
processData: false,
contentType: false,
data: form_data,
success:function(data)
{
$('.revnue_updated').removeClass('d-none');
$(".revnue_updated").fadeOut(3000);
}
});
};
Related
I've got an ajax function:
$('#addSiteButton').on('click',function() {
let addSiteOption = $('#enterNewWebsiteLink').val();
const form = new FormData();
form.append('addSiteOption', addSiteOption);
$.ajax({
url: "includes/submit_site.php",
data: { 'data': form },
method: "POST",
contentType: false,
processData: false,
enctype: false,
cache: false,
datatype: "text",
success: function (response, data) {
}
});
My PHP file looks just like this:
if (isset($_POST['data'])) {
$websitelink = $_POST['addSiteOption'];
}
my HTML looks like this:
<input type="url" form="addsite" class="enterNewWebsiteLink"
id="enterNewWebsiteLink"
name="enterwebsitelink"
placeholder="Enter A New Website">
The error that I am getting is: Warning: Undefined array key "data"
I've tried outputting the variable addSiteOption and it outputs the URL correctly.
The frustrating thing, I've been checking/copying this against a previous project I did that I got it working in, and I can't make any difference between them now.
I get a 200 response from the server for the page.
You can't serialize FormData, and processData: false tells jQuery not to try to serialize the data: option.
You should just pass the FormData as the data: option. Then the keys of the FormData will become the $_POST keys.
JS:
$('#addSiteButton').on('click',function() {
let addSiteOption = $('#enterNewWebsiteLink').val();
const form = new FormData();
form.append('addSiteOption', addSiteOption);
$.ajax({
url: "includes/submit_site.php",
data: form,
method: "POST",
contentType: false,
processData: false,
enctype: false,
cache: false,
dataType: "text",
success: function (response, data) {
}
});
PHP:
if (isset($_POST['addSiteOption'])) {
$websitelink = $_POST['addSiteOption'];
}
You also had a typo: datatype: should be dataType:
I can do this:
$.ajax({
type: "GET",
async: true,
url: '/someurl/',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Web:
Route::get('/someurl','MyController#myfunction');
And it works just fine, but when I try the same with post:
$.ajax({
type: "POST",
async: true,
url: '/someurl/',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Route::post('/someurl','MyController#myfunction');
I get a 405 method not allowed error message in the console
POST using normal ajax need CSRF Token to be pass in POST Method
in your ajax
$.ajax({
type: "POST",
async: true,
url: '/someurl/',
dataType: 'json',
data : {"_token":"{{ csrf_token() }}"} //pass the CSRF_TOKEN()
success: function (data) {
console.log(data);
}
});
or
set head meta tag
<meta name="csrf_token" content="{{ csrf_token() }}" />
set header ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Add another route with
Route::post('/someurl','MyController#myfunction');
By the way u are not sending any data, in post we need to send data right..
Also check whether csrf token is being passed in data, if not as mentioned above try adding it manually.
If you are using {{Form...}} it would be automatically added to form data.
I am using laravel 5.4 and jquery Ajax to upload file and some form data.
I am using below code
function submitDocument(){
var formData = new FormData(); // Currently empty
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "documents",
method: "post",
data:{_token,formData},
}).done(function(data) {
});
return false;// Not to submit page
}
And I am getting error
Uncaught TypeError: Illegal invocation
How can I fix this ? Thanks in advance for your time.
I am able to get value in formData by using
console.log(formData.get('title'));
console.log(formData.get('doc'));
Try adding processData: false, contentType: false in your code
Replace your script with this:
function submitDocument(){
var formData = new FormData(); // Currently empty
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "documents",
method: "post",
data:{_token,formData},
cache : false,
processData: false,
contentType: false
}).done(function(data) {
});
return false;// Not to submit page
}
By default, data passed in to the data option as an object will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
<script>
$(document).ready(function() {
var url = "{{ url('/admin/file') }}";
var options = {
type: 'post',
url: url,
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
dataType: 'doc',
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert('Ok');
},
error: function (data) {
alert('Error');
}
};
$('#save').on('click', function() {
$("#form").ajaxSubmit(options);
return false;
});
});
</script>
Try this way
$(document).ready(function (){
$("#form").on('submit',(function(e){
e.preventDefault();
var formdata = new FormData(this);
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "/site/url",
type: "POST",
data:{token:_token,formData},
contentType: false,
cache: false,
processData:false,
success: function(data){
},
});
}));});
I trying to send two images with ajax (inside submitHandler) after using jquery validator plugin and i don't know hoy i cant take and send this image by ajax.
My code here:
var submitHandler = function(form) {
var formData = form[0];
var formData = new FormData(formData);
$.ajax({
url: 'function/savePreInscripcion.php',
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
alert(data);
}
});
};
but this dont work..
this display this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
var formData = new FormData(formData);
so.. what's worng here?
Thnx for the help!,
I resolve this..
Just change a little party on my code..
var submitHandler = function(form) {
$.ajax({
url: 'function/savePreInscripcion.php',
type: 'POST',
data: new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
alert(data);
}
});
};
Just I change the call to the form and put this directly on the data whit the next code: "data: new FormData(form)" and it work fine! =)
I have a webform which has x number of textboxes and y number of dropdowns etc
I am using this code to send data to webmethod at the server:
$.ajax({
type: "POST",
url: "SupplierMaster.aspx/RegisterSupplier",
data: JSON.stringify({
id: $('#txtbidderid').val(),
bidamt: $('#txtbidamt').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
Now the problem is that I also want to include file attachments on this form.
How do I add the files to data: of $.ajax method?
I do not want to use external plugins etc unless absolutely necessary.
Lets say I modify my data object to look like this :
var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );
What would the webmethod armument look like?
For example lets suppose it looks like this as of now:
[WebMethod] public static string SubmitBid(string id, string bidamt.....)
You can try something like this. You may need to manipulate content type.
var dataToSend = new FormData();
dataToSend.append( 'file', input.files[0] );
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
data: dataToSend,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You cannot send file as application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below.
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
type: 'POST',
data: new FormData(formElement),//Give your form element here
contentType: false,
processData: false,
success: function () {
//do success
}
});