MethodNotAllowedHttpException when trying to post data to controller via ajax in laravel - javascript

I'm trying to send dynamically generated data to controller via ajax in laravel. When user select an option from the dropdown then along with selected option and other data should be sent to controller.
I've tried to send data to controller when an option from dropdown is selected. But every time i try this error,
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
and in the error
REQUEST_METHOD is GET
This is the where i call the ajax function
$(document).on('change', '.route-code-selector', function() {
var selectorID = $(this).attr('id');
addRoutePlanDetails(selectorID);
});
AJAX function
function addRoutePlanDetails(selectorID) {
var routePlanCode = document.getElementById("routeplanno").value;
var driver = $("#selectDriver").val().split('|');
var salesman = $("#selectSalesman").val().split('|');
var router_01 = $("#selectRouter01").val().split('|');
var router_02 = $("#selectRouter02").val().split('|');
var vehicle_no = document.getElementById("enterVehicleNo").value;
var route_code = document.getElementById(selectorID).value;
var date = document.getElementById("date").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: 'addNewRoute',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
}
Route
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get ('route-plan', 'RoutePlanController#index');
Route::get ('excludePorterRes', 'RoutePlanController#excludePorterRes');
Route::get ('retreiveRouteData', 'RoutePlanController#retrieveRouteCodeData');
Route::get ('retreiveUserData', 'RoutePlanController#retreiveUserData');
Route::get ('retreiveNewRouteData', 'RoutePlanController#retreiveNewRouteData');
Route::post('addNewRoute', [
'uses' => 'RoutePlanController#insertNewRoute',
'as' => 'addNewRoute'
]);
});
controller
public function insertNewRoute(){
$routeplan = new Routeplan;
$user_email = auth()->user()->email;
$routeplan->RouteplanCode = Input::get('routePlanCode');
$routeplan->RouteCode = Input::get('route_code');
$routeplan->DriverID = Input::get('driver');
$routeplan->SalesmanID = Input::get('salesman');
$routeplan->Routercode1 = Input::get('router_01');
$routeplan->Routercode2 = Input::get('router_02');
$routeplan->VehicleNo = Input::get('vehicle_no');
$routeplan->Date = Input::get('date');
$routeplan->Createuser = $user_email;
$routeplan->Status = 'TEMP';
$routeplan->save();
}
when user select an option all the data should be stored in the db.

Try it once
url: '{{ route('addNewRoute') }}',

The issue is here:
url: 'addNewRoute',
here you are calling the route in a wrong manner, use it like:
url: '{{ url('admin/addNewRoute') }}',
you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin, so you have to append that to while calling it.

If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. (before .js file is loaded);
Example var url = '{{ route('addNewRoute') }}'
$.ajax({
url: url',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
If you using ajax in the blade, you can use directly route as ajax request url.
$.ajax({
url: "{{ route('addNewRoute') }}",
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});

You forgot / in your routes.
Route::group(['prefix' => 'admin'], function () {
Add / in admin/
Route::group(['prefix' => 'admin/'], function () {
Then you can try this in your ajax
url: '{{ url('admin/addNewRoute') }}',
or
url: 'admin/addNewRoute',
Try if this will work.

You have used prefix for your routes. So all your route in group will be prefix/uri.
So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type
$.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
In ajax for specifying HTTP Verb use type not method.

if your script is in blade file then use route() to set url in ajax:
$.ajax({
url: '{{route('addNewRoute')}}',
method: 'POST',
dataType: 'json',
...
});

Try this:
Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'.

As many of you said.. I changed method to type.. And it still didn't work. But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. And that's why it still gave me the 500 error. After I changed the syntax and do the corrections. It worked !! Anyways thanks for helping guys! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone.

Related

Send pdf from python(pyramid) to jquery ajax

how to send PDF file that can be rendered to jinja2??
write both codes (.py) and (.js) if possible.
here is my ajax code
$("#print").click(function(event) {
$.ajax(
{
type: "POST",
url: "/printledgerreport",
global: false,
async: false,
dataType : 'json',
//contentType : 'application/pdf'
data: {"backflag":0,"accountcode":$("#accountcode").val(),"calculatefrom":$("#calculatefrom").val(), "calculateto":$("#calculateto").val(),"financialstart":sessionStorage.yyyymmddyear1,"projectcode":$("#projectcode").val(),"monthlyflag":false,"narrationflag":false},
beforeSend: function(xhr)
{
xhr.setRequestHeader('gktoken',sessionStorage.gktoken );
},
success: function(data){
window.open("ledgerReport.pdf");
}
});
});
please tell me how to write pyramid code
Now here is my new pyramid code:
#view_config(route_name="printledgerreport", renderer="")
def printLedgerReport(request):
filepath = ("ledgerReport.pdf")
response = FileResponse(filepath)
response.headers['Content-Disposition'] = ("attachment; filename=ledgerReport.pdf")
return response
Try this. I'm on my 5th margarita. It should work. :) Remember to add route for "download_PDF".
#view_config(route_name="download_PDF", renderer="")
def download_view(request):
filepath = ("pathtomyfile/test.pdf")
response = FileResponse(filepath)
response.headers['Content-Disposition'] = ("attachment; filename=test.pdf")
return response
Whoops. This just downloads the file. Maybe you can make it work with jinja. Again. too many margaritas: )

Can not seem to pass more than one variable with jquery to mysql

I have seen several examples and can't seem to get the hang of passing more than one variable to mysql using jquery. Here is my situation:
I have a page with 2 cascading drop downs,( they work great using jquery to update second drop down based on the first drop down.)
when the first drop down is selected jquery updates the second drop down AND passes the customer id to a php script that creates a new record in the tblinvoice table (this also works great no problems.)
when the second drop down is selected I need to pass that value along with the invoice number to my php script so I can update the record with the instid.(this is the part that don't work)
If I only pass the instid and manually put the invoice number in the where clause of the query all works fine. If I omit the where clause all records are updated as expected. I need to know what I am doing wrong or what is missing.
I will try to post the code here
jquery code
$(document).ready(function() {
$("select#cust").change(function() {
var cust_id = $("select#cust option:selected").attr(
'value');
var test = $("#test").val();
var din = $("#idate").val();
$("#inst").html("");
if (cust_id.length > 0) {
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
$('#inst').html(
'<img src="loader.gif" alt="" width="24" height="24">'
);
},
success: function(html) {
$("#inst").html(html);
}
});
if (test == 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
},
success: function(html) {
$("#invoice").html(html);
$("#test").val(1);
var inum = $("#inv").val();
$("#invnum").val(din +
"-" + inum);
}
});
}
}
});
$("select#inst").change(function() {
var inst_id = $("select#inst option:selected").attr(
'value');
var custid = $("select#cust option:selected").attr(
'value');
var invid = # ("#inv").val()
if (inst_id.length > 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: {
inst_id: inst_id,
}
cache: false,
beforeSend: function() {
},
success: function() {
}
});
}
});
});
I have tried using data: {inst_id:inst_id,custid:custid,invid:invid,} (no update to the table like this)
I also tried data: "inst_id="+inst_id+"&custid="+custid+"&invid="+invid,(this also gives no results.)
Can someone PLEASE look at this jquery and see if I am making a simple error?
Try this format:
data: { inst_id: inst_id, custid: custid, invid: invid },
You can post a JSON object to the server so long as you serialize it and then let the server know the data type.
First you need to define your JSON object:
var postData = { inst_id: inst_id, custid: custid, invid: invid };
Then update your ajax to use the serialized version of that object and let the server know the data type:
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: JSON.stringify(postData),
contentType: "application/json",
..continue the rest of your ajax....

Passing post variables through ajax

I have a link:
<a class="tag" wi_id="3042" wl_id="3693" for_user_id="441" href="#a">
which triggers an ajax call
$(".tag").click(function() {
var for_user_id = $(this).attr("for_user_id");
var wl_id = $(this).attr("wl_id");
var wi_id = $(this).attr("wi_id");
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': 'for_user_id',
'wl_id': 'wl_id',
'wi_id': 'wi_id'
},
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
return false;
});
But in the console I see the following:
TypeError: e is undefined
The ajax file gets processed but the POST data is blank, and the success actions do not happen, so it gets posted with zeros and classes are not changed
I have stared and stared... anything obvious?
this is not passed automatically to the AJAX callback function. You can use the context: parameter to tell jQuery to pass it:
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': for_user_id,
'wl_id': wl_id,
'wi_id': wi_id
},
context: this,
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
You're sending your data wrong, don't call your variables inside single quotes.
$(".tag").click(function() {
var for_user_id = $(this).attr("for_user_id");
var wl_id = $(this).attr("wl_id");
var wi_id = $(this).attr("wi_id");
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': for_user_id,
'wl_id': wl_id,
'wi_id': wi_id
},
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
return false;
});

ASP MVC basic AJAX Json request returns null

I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.

Categories