AJAX:
$.ajax({
type:"POST",
url: "{{url('/post/add')}}",
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('hi');
}
}
});
Laravel Controller: I have checked for the ajax request in the controller.
public function add(Request $request)
{
if($request->ajax())
{
// codes
echo json_encode(TRUE);die;
}
}
but, I noticed that I do not require to check for ajax request? And without checking if the ajax request how am i getting the alert?
public function add(Request $request)
{
// codes
echo json_encode(TRUE);die
}
The check is simply one additional measure of a valid request. It is not necessary as you've noticed, but if you'd like to verify that the request is coming via an AJAX request as you'd expect - you may.
You should use $request->ajax() to determine if the request is the result of an AJAX call. If you're working only with AJAX requests in your method, you can omit this check.
It just depends on you. You can do different things based on if the request is AJAX request or not. For example returning JSON or a normal view.
If you want your routes to be accessed by only AJAX requests maybe you can protect those routes with a middleware. Check this answer for more information about that.
Related
I want to declare a global variable. Here are my actions
BaseController
protected $header_data;
public function __construct()
{
$this->header_data = HeaderData::all();
View::share('data', $this->header_data);
}
Next, in the Blog page controller, let's say I write this
$this->header_data;
And on the page itself in php.blade
<h1>{{ $data }}</h1>
But I get completely all the data from the model, and I only need a field data
[{"id":3,"url":"\/blog","data":"<title>Blog<\/title>\n<meta name=\"description\" content=\"Blog\" \/>","created_at":"2021-10-19T11:24:41.000000Z","updated_at":"2021-10-19T11:24:41.000000Z"}]
when I click on the like to update the data, I reload the page using
window.location.reload();
Can this somehow be done without reloading the page?
Yes, by not using window.location.reload();.
$.ajax({
url: href,
type: 'POST',
success: function () {
$(this).addClass('active');
},
error: function (jqXhr, status, error) {
alert(error);
},
});
Change your PHP so it doesn't return the complete page for POST requests to the /article/...?type=heart route.
In case of a "like" functionality, you practically only need feedback whether it has worked (the like was registered), or not (in which case you might want to display an error).
Your server could simply respond with status code 204 (No Content) in the success case.
I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:
I wanted to submit a for using ajax call in laravel 5.
In view i wrote something like
$("#updateSubmit").on('submit',function(e){
e.preventDefault();
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
method:'POST',
url: '/account/updateForm',
//dataType: 'json',
data: {accountId:'1111', _token: '{{csrf_token()}}'},
success: function( data )
{
alert(data)
return false;
}
},
error: function(error ){
alert("There is some error");
}
});
and on controller side
public function update(Request $data )
{
return Response()->json(['success' => true],200);
}
while in route for post method
Route::post('account/updateForm', 'AccountController#update')->name('account/updateForm');
its working till ajax. on Submission of ajax it goes to controller action.
but it does not retrun back as ajax comes back in normal form submisson.
it just go to controller and stops there with {"success":true} line.
I want ajax to come back to view form so that I can perform different dependent actions.
Do you mean that when you submit your form, you just have a white page with {"success": true} ?
If that's the case, maybe the error is on your javascript.
Maybe your jQuery selector is wrong, or maybe your js isn't compiled ?
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.
I am using ajax post action. In this action i have used HttpContext.User.Identity.Name to get the user id. Based on the user id i get some records related to that user id in database and return that values through json type.
Sometimes session got expired, in this case the HttpContext.User.Identity.Name value became empty. If it is empty or null it will throw the exception.
So I need to null or empty check the HttpContext.User.Identity.Name value, if it is null or empty i need to redirect it to login page.
But redirecting action not works inside the ajax post action. how to solve this problem?
i need to authorize the ajax post action. Can any one give solution for that?
Regards,
Karthik.
But redirecting action not works inside the ajax post action. how to solve this problem?
You could start by decorating your controller action with the [Authorize] attribute. This ensures that only authenticated users can access it and you are guaranteed that inside User.Identity.Name will never be null:
[Authorize]
public ActionResult SomeAction()
{
string username = User.Identity.Name; // this will never throw
...
return Json(...);
}
then take a look at the following blog post by Phil Haack. Inside its post Phil presents a nice plugin that allows you to configure ASP.NET to send 401 HTTP status code when an AJAX request to a protected action is made. So in your jQuery code you could very easily detect this condition and redirect:
$.ajax({
url: '/SomeAction',
type: 'POST',
statusCode: {
200: function (data) {
alert('200: Authenticated');
// Bind the JSON data to the UI
},
401: function (data) {
// the user is not authenticated => redirect him to the login page
window.location.href = '/login';
}
}
});
And of course to avoid writing this 401 condition in all your AJAX requests you could very easily use the global .ajaxError() handler to centralize this redirection logic for all your AJAX requests in case of 401 status code returned by the server:
$(document).ajaxError(function(e, jqxhr, settings, exception) {
if (jqxhr.status == 401) { // unauthorized
window.location.href = '/login';
}
});
and now your AJAX requests become pretty standard:
$.ajax({
url: '/SomeAction',
type: 'POST',
success: function(data) {
// do something with the data returned by the action
}
});