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.
Related
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);
}
});
};
Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution
The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
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
}
});
Hello i trying to to save response from htmlpage and save the content of this page, but i always getting an error.What i am doing wrong?
<script type="text/jscript">
var page = "";
$.ajax({
url: "https://www.bbvanetcash.com/local_kyop/KYOPSolicitarCredenciales.html",
type: "GET",
cache: false,
crossDomain: true,
cache: false,
contentType: "application/json; charset=utf-8",
data: {},
jsonp: 'jsonCallback',
dataType: "jsonp",
success: function (data) {
page = data;
console.log("Good");
},
error: function (e) {
console.log("Error");//here where i am stuck
}
});
</script>
"https://www.bbvanetcash.com/local_kyop/KYOPSolicitarCredenciales.html" - i think its URL belong from other domain not from your home/base domain url. that's why you getting error.
You can not make a AJAX http request for NON HOME url.
NON HOME: Its means you can only access your Base domain content though ajax.
Below is my jquery ajax call. I see from fire bug that I am getting the json response.
Content-Type application/json
{x:1363590711.97,y:0.277528026651}
However...I cant event pop up and alert of the data? How do I get the parsed json object so i cna start working iwth it?
$.ajax({
type: 'GET',
url: 'ajax_test',
crossDomain: false,
dataType: 'json',
success: function(responseData) {
alert(responseData);
//seriesJsonData[0]['data'].push({y: responseData.y, x: responseData.x});
}
});
Your return data is already parsed when you request dataType: 'json'
$.ajax({
type: 'GET',
url: 'ajax_test',
crossDomain: false,
dataType: 'json',
success: function(responseData) {
alert(responseData.x + " " + responseData.y);
seriesJsonData[0]['data'].push(responseData);
}
});