Problem with AJAX Post request in laravel - ajax

I have a select box and when each item is selected, a ajax request is sent.
but my code does not work. i'm get status 404 and this error is displayed in the console
exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException", file: "F:\\source\\boiler\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RouteCollection.php", line: 179, …
my route :
Route::group(['namespace' => 'BuyCrypto' , 'prefix' => 'crypto'], function() {
Route::post('/calculateBuyAmount' , [BuyCryptoController::class , 'calculateAmount'])->name('calculate.amount');
});
ajax code :
$("select#user_select_crypto").change(function(e) {
$('#calculat_user_buy').block({
message: '<i class="icon-spinner4 spinner"></i>',
overlayCSS: {
backgroundColor: '#fff',
opacity: 0.8,
cursor: 'wait'
},
css: {
border: 0,
padding: 0,
backgroundColor: 'transparent'
}
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
$.ajax({
url: "panel/crypto/calculateBuyAmount",
dataType: 'json',
data: {
user_select_crypto: $("input[name=user_select_crypto]").val(),
user_value_request: $("input[name=user_value_request]").val(),
},
success: function(result) {
console.log(result)
},
error: function(result) {
console.log(result)
},
});
});
what is problem?

this is because laravel not getting the full URL of your giving route. you have to give the correct route. for this, you can use your named route like below.
url: "{{ route('calculate.amount') }}",
or in case you are in a javascript file and can't use blade than just give URL with / slash. all is going to work. Its happen with a post request.
you can give URL like below
url: "/panel/crypto/calculateBuyAmount",
Updated
Now you facing methodNotAllowedException because now you sending a get request because you are not mentioning in ajax side you are doing a post request. by default ajax will send a get request. so you need to tell ajax use post method. like that type: "POST" like below
$.ajax({
url: "/panel/crypto/calculateBuyAmount",
dataType: 'json',
type : 'POST'
data: {
user_select_crypto: $("input[name=user_select_crypto]").val(),
user_value_request: $("input[name=user_value_request]").val(),
},
success: function(result) {
console.log(result)
},
error: function(result) {
console.log(result)
},
});

In this kind of situation, it is good to use named route as you give your route a name.
$.ajax({
url: "{{ route('calculate.amount') }}", // use your name route here
type : 'POST', // need to add your request type post
dataType: 'json',
data: {
user_select_crypto: $("input[name=user_select_crypto]").val(),
user_value_request: $("input[name=user_value_request]").val(),
},
success: function(result) {
console.log(result)
},
error: function(result) {
console.log(result)
},
});

Related

How can I start datatable at another page after ajax request success?

This is my datatable:
var table = $('.table').DataTable({
"serverSide": true,
"ajax": '{{ path('json') }}',
});
On an ajax request success, I would like to start at another page:
$.ajax({
method:'POST',
data: {
"id": id,
},
url:'{{ path('json') }}',
success : function (data) {
table.displayStart( 20 ).draw();
}
});
But it is not working.
You can use the page() function.
table.page(20).draw('page');

Ajax get response body data name with space

I am able to read specific data from responses with ajax GET example by using data.investing.
but one of my data name is unrest and war and i am unsure how do i write it inside my javascript, as i tried data.unrest and war and it didnt work.
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: "https://agile-bayou-24340.herokuapp.com/users/getTodayData",
contentType: 'application/json',
dataType: 'json',
responseType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'application/json',
},
success: function (data) {
console.log(data.investing[0].title);
$('#div1').html((data.investing[0].title));
},
error: function (error) {
console.log("Error");
}
});
});
});
this is my current code
You can parse Json to Array and use key's
success: function (data) {
data = $.parseJSON(data)
console.log(data['investing'][0]['title']);
$('#div1').html((data['investing'][0]['title']));
},

AJAX Post request in laravel 5.4

Have anyone got issue in ajax post request in laravel 5.4. I am unable to get request data in controller.
Ajax request is something like this:
$.ajax({
data: { 'selected_data':[2,4,5] },
type: "POST",
url: "{{ url('test') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (res) {
console.log(res)
},
});
In controller method, i am just doing
dd($request->all());
But getting empty array. can anyone help me with this issue?
Thanks!
Instead of this:
$.ajax({
data: { 'selected_data':[2,4,5] },
type: "POST",
url: "{{ url('test') }}",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (res) {
console.log(res)
},
});
Try this:
$.ajax({
data: { selected_data:[2,4,5], _token: "{{csrf_token()}}" },
type: "POST",
url: "{{ url('test') }}",
success: function (res) {
console.log(res)
},
});

Typeahead not work in dialog edit of jqGrid

I tried to response the json from server like the official demo.
But the dropdown suggesion doesn't show up.
Could anyone tell me what I missed?
I only change the url from the demo code:
{
label: 'Ship Name2',
name: 'ShipName2',
width: 150,
editable: true,
edittype: "text",
editoptions: {
dataInit: function (element) {
$(element).attr("autocomplete","off").typeahead({
appendTo : "body",
source: function(query, proxy) {
$.ajax({
url: 'mysite',
dataType: "jsonp",
data: {term: query},
success : proxy
});
}
});
}
}
}, {
label: 'Ship Name',
name: 'ShipName',
width: 150,
editable: true,
edittype: "text",
editoptions: {
dataInit: function (element) {
$(element).attr("autocomplete","off").typeahead({
appendTo : "body",
source: function(query, proxy) {
$.ajax({
url: 'http://trirand.com/blog/phpjqgrid/examples/jsonp/autocompletepbs.php?callback=?&acelem=ShipName',
dataType: "jsonp",
data: {term: query},
success : proxy
});
}
});
}
}
}
P.S. My servlet return the same json which is exact the same as demo's.
Thanks!!
Edit 1: Is it possible that if I want to use typeahead in this demo, the response should not just be a json?
If I execute the url in the demo, I would get the following javascript instead of json:
<script type='text/javascript'>
jQuery(document).ready(function() {
if(jQuery.ui) {
if(jQuery.ui.autocomplete){
jQuery('ShipName').autocomplete({
"appendTo":"body",
"disabled":false,
"delay":300,
"minLength":1,
"source":function (request, response){
request.acelem = 'ShipName';
request.oper = 'autocmpl';
$.ajax({
url: "autocompletep.php",
dataType: "json",
data: request,
type: "GET",
error: function(res, status) {
alert(res.status+" : "+res.statusText+". Status: "+status);
},
success: function( data ) {
response( data );
}
});
}});
jQuery('ShipName').autocomplete('widget').css('font-size','11px');
jQuery('ShipName').autocomplete('widget').css('z-index','1000');
}
}
});
</script>
Could anyone tell me why?
The demo uses JSONP to obtain the data. If you are in local site you will need to remove calcback=? parameter.
The very basic testis is not to use ajax in typeahead, but array as data source. This way you will be sure that this work correct

How can I get imgur.com album images using ajax request

I used this code :
(function($){
var albumID = 'NNbeO';
var albumAPI = "https://api.imgur.com/3/album/" + albumID + "/images";
$.ajax({
url: albumAPI,
headers:{
'Authorization':'xxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
},
type: 'GET',
dataType: 'json',
success: function(data) {
alert(data.data[0].link);
},
error: function() { console.log("ERRORZ"); }
});
})(jQuery);
But I got this error :
{
"data": {
"error": "Malformed auth header",
"request": "\/3\/album\/NNbeO\/images",
"method": "GET"
},
"success": false,
"status": 403
}
I got my solution. It works fine now. Below is my working code. It's problem was, I've not added Client-ID text with Authorization headers.:
(function($){
var albumID = 'NNbeO';
var albumAPI = "https://api.imgur.com/3/album/" + albumID + "/images";
$.ajax({
url: albumAPI,
headers:{
'Authorization':'Client-ID xxxxxxxxxxxxx'
},
type: 'GET',
dataType: 'json',
success: function(data) {
alert(data.data[0].link);
},
error: function() { console.log("ERRORZ"); }
});
})(jQuery);

Resources