Routing to pass parameters Laravel 5.3 and AJAX - ajax

I have to pass parameters per post with ajax but not working on the console I get this:
POST http://localhost:8000/prueba2 405 (Method Not Allowed)
This is my routing:
Route::get('prueba2', 'HomeController#index');
This is my ajax:
$.ajax({
url: '{{url('prueba2')}}',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
This is my controller:
public function index(){
return 'hola';
}
All this is a test and is not the final driver nor the final ajax, but it seems to be some response by the controller. But unfortunately I get a 405.
If someone can help me with this serious problem it would be a lot of help

You are receiving a MethodNotAllowedException because you defined a GET route with Route::get('prueba2', 'HomeController#index');, but you do a POST request.
Change your AJAX type to GET or use Route::post().
The last one would look like:
Route::post('prueba2', 'HomeController#index');

Related

Laravel 5.6: Why does AJAX POST to Controller not show data load in Controller?

I have been working on this for hours,and not getting anywhere. Essentially, my Ajax call appears to be working well. I am pulling in form data from a view. I can see the XHR data when I look into Chrome Network. I have a status 200, and "OK". However, no matter what I do, I can not get any data to show in my controller. I have tested my route by commenting it out and sure enough I get an error, so that is positive. Also the XHR data shows the correct url as well. But even just a simple dd($request) inside the controller gives me nothing, not even an empty []. I have tried every option and Googled this to death. What am I doing wrong - Thanks !
Abbreviated HTML
<form action="" method="POST" id="formData">
<fieldset>
{{ Form::hidden('customer_id',$customer[0]->id,['id'=>'customer_id'])}}
{{ Form::hidden('lastname1',$customer[0]->lastname1,['lastname1'=>'lastname1'])}}
{{ Form::hidden('reference',$quotation[0]->reference,['id'=>'reference'])}}
</fieldset>
</form>
AJAX
$("#editsubmit").on('click', function () {
event.preventDefault();
var formData =$("#formData").serialize();
var id = $("#reference").val();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
contentType:'JSON',
processData: false,
url: '/save_edit/'+id,
data: {
"_method": 'POST',
"result": formData,
},
error: function () {
alert('there has been a system level error - please contact support')
}
});
});
Route
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Controller
public function save_quote_edited(Request $request){
dd(json_decode($request->getContent(), true));
}
To process forms you should not be calling $request->getContent() you should be calling $request->all() to get all parameters, $request->get('foo') or $request->foo to get a single parameter, or $request->get(['foo','bar','baz') to get multiple parameters.
And for bonus points if you used Laravel's Form Request Validation you could call $request->validated() and get only the parameters which passed the validation checks.
Your route requires a parameter of "id" but you do not have that parameter in your controller method.
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Try :
public function save_quote_edited(Request $request, $id){
*** insert code here ***
}

Method not Allowed error on Ajax Post request (500 error) Laravel Framework

I am working on a Post Ajax request Function. Where the function takes some data and send it through an enabled CSRF_token post Request to a controller and then after evaluations on controller a message sent back to the view. but it seems i miss a small thing in my code.
My controller
public function PostMessage(Request $request){
$message=$request->someData; //getting data from request variable
return response()->json($message);
}
My jquery Ajax request function
$('.SendAjaxPostRequest').on('click', function() {
var value=$('.MessageHolder').val();
$.ajax({
method: 'POST',
url:'{{route('SVCate')}}', //SVCate is my route to the controller
dataType: 'JSON',
data: {_token:token,'someData':value,}
// #token gets it's value from a local view javaScrip Variable
})
.done(function (data) {
console.log(data);
})
});
My route function
Route::post('SendMessage','NessageController#PostMessage')->name('SVCate');
Check your apostrophes in the url. You are ending the string and beginning the string around SVCate change it to url:"{{route('SVCate')}}" to make sure that SVCate stays a string and does not break your string.

Ajax Routing Calling Controller Name Twice

I am trying to do a simple call to my controller via ajax. The RouteConfig has not been changed and set to the default values. When I make ajax call, the Url that is requested in the "Network" debugging tools is:
'http://localhost:59275/Leaderboard/Leaderboard/GetPosition'
This is causing a 404 because the Controller, Leaderboard, is being added into the Url twice. The correct url should be
'http://localhost:59275/Leaderboard/GetPosition'
My ajax call is as follows:
$.ajax({
url: 'Leaderboard/GetPosition',
type: "GET",
dataType: 'xml',
success: function (data) {
$('#results').html(data);;
}
});
and my controller is as follows:
public class LeaderboardController : Controller
{
[Webmethod]
public static DataTable GetPosition()
{
// do stuff
}
}
If the root URL of the page that request the ajax is "Leaderboard" then the url on the ajax call should only "GetPosition"
Or you can use "/Leaderboard/GetPosition" with "/" in front
Use Url.Action helper for generating correct url.
Change this:
url: 'Leaderboard/GetPosition'
to this:
url: '#Url.Action("GetPosition","Leaderboard")'

Codeigniter ajax gives 404 not found

I'm trying to use ajax with Codeigniter, but I'm getting a 404 (not found) error.
For ajax I do this:
$.ajax({
type: "POST",
url: "/index.php/ajax/user-sign-up-via-email",
data: {
email: email,
password: password
}
});
For my Routes.php I have this:
$route['ajax/user-sign-up-via-email'] = "UserSignUpViaEmailAjaxController";
Am I missing something specific to Codeigniter?
Is it related to first URL parameter being the controller, second parameter being the function to call within the controller?
As per comments:
Make sure that the controller you are calling (UserSignUpViaEmailAjaxController) has an index() function. Since you are remapping the uri directly to a controller without specifying a function it will default to the index() function and will 404 if it can't find one.
i do this normally .. u can try this also
url: "<?php echo site_url('customersController/addCustomer'); ?>",

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

Resources