Im using javascript in Homepage to pass variable to next page (Im using controller to store variable in session) , now how can I empty the session if loaded the home page again?
$(document).on('click', '.btn_getbids', function() {
$.ajax({
type: 'post',
url: 'addItem',
data: {
'_token': $('input[country=_token]').val(),
'country': $('input[name=country]').val() },
success: function(data) {
}, });
$('#country').val('');});
Controller
public function addItem(Request $request) {
$request->session()->put('country', $request->country);
return response ()->json ( $data );
}
Assuming you have an IndexController where you call the homepage function to call your home view.
public function homepage(Request $request){
//check if session exists
if($request->session()->has('country'){
//forget session
$request->session()->forget('country');
}
}
With this code, session country will be forgotten every time you go to the homepage.
For your additional reference Laravel Sessions
Have you tried:
public function addItem(Request $request) {
if($request->session()->has('country'){
$request->session()->forget('country'); //if you want to clear specific one
//$request->session()->flush //if you want to flush all
}
$request->session()->put('country', $request->country);
return response ()->json ( $data );
}
Related
I'm new in Laravel!!
I have a js that send a request DELETE to my controller:
$.ajax({
url: link,
method: 'DELETE',
data: {
_token: $('input#_token').val(),
},
Than my controller return redirect
public function destroy(User $user)
{
$this->repository->delete($user->id);
return redirect()->to(route('users.index'));
}
This route "users.index" has the "GET" method, but the redirect is considering the DELETE method, resulting in this error:
DELETE http://localhost:8000/users 405 (Method Not Allowed)
Can i change the method using in redirect?
Tks!
Ajax request will always follow redirects (actually, there's a work around), so you probably should change your controller to avoid redirects if this is an ajax request.
use Illuminate\Http\Request;
# [...]
public function destroy(Request $request, User $user)
{
$this->repository->delete($user->id);
if ($request->ajax()) {
return $user;
}
return redirect()->to(route('users.index'));
}
If this controller only receives ajax requests, you can make it simpler.
public function destroy(Request $request, User $user)
{
$this->repository->delete($user->id);
# or return whatever you want with: response()->json($contents);
return $user;
}
[UPDATED] Making redirects after ajax
As #PatricQ mentioned, you might want to make the redirect after the ajax call. If this is the case, I suggest that you create a response format that your javascript understands and makes a redirect.
An example would be to return the redirect URL:
return response()->json(['redirect' => true, 'to' => route('users.index')]);
This way, in your javascript you would check for the redirect flag.
$.ajax({
url: link,
method: 'DELETE',
data: {
_token: $('input#_token').val(),
},
success: function (response) {
if (response.redirect) {
window.location.href = response.to;
}
},
});
I am trying to pass a productId to a controllor in order to show the related product properties in a modal booststrap.
I would like tho show the pop up in the main page index. This is the related route:
Route::get('/', 'FrontendController#index');
This is tha ajax get call:
$("#getModal").on("click",function(){
$.ajax({
url: '{{url('./')}}',
type: 'GET',
data: { productId: 1 },
success: function(response)
{
console.log('Ajax submitted);
}
});
});
This is the request detected in the console:
localhost/SHOP-ONLINE/public/?productID=1
It seems everything is working fine. But, how can I pass the productId value in the controller? if I try following I cannot pass it:
public function index(Request $request) {
$productID = $request->productId
}
you need to use the get() method of the request object.
public function index(Request $request) {
$productID = $request->get('productID');
}
I think you can try this :
public function index(Request $request) {
$productID = $_GET['productID'];
}
Hope this work for you !!!
I'm using Yii2 and I have setup a login process which works fine (cookies as well) via the standard login page which is not AJAX.
I have built a dropdown login field which works fine at logging them in, however it doesn't seem to set the cookie as the user doesn't stay logged in and there is no bookie created.
I figured that this was because of AJAX and the cookie wasn't being created on the users system, but upon further reading it seems it should work.
I have verified that the cookie value is being set correctly, the only issue is the cookie doesn't seem to being created.
My login code:
JS:
function doLogin() {
// Set file to prepare our data
var loadUrl = "../../user/login/";
// Set parameters
var dataObject = $('#login_form').serialize();
// Set status element holder
var status_el = $('#login_status');
// Make sure status element is hidden
status_el.hide();
// Run request
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
if (response.result == 'success') {
//.......
} else {
//.......
}
})
.fail(function() {
//.......
});
// End
}
function getAjaxData(loadUrl, dataObject, action, type) {
if ($('meta[name="csrf-token"]').length) {
// Add our CSRF token to our data object
dataObject._csrf = $('meta[name="csrf-token"]').attr('content');
}
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
Controller:
public function actionLogin() {
// Check if they already logged in
if (!Yii::$app->user->isGuest and !Yii::$app->request->isAjax) {
return $this->redirect('/');
}
if (Yii::$app->request->isAjax) {
// Set our data holder
$response = ['output' => '', 'result' => 'error'];
}
// Let's send the POST data to the model and see if their login was valid
if (Yii::$app->request->isAjax and $this->user->validate() and $this->user->login()) {
$response['result'] = 'success';
} elseif (!Yii::$app->request->isAjax and Yii::$app->request->isPost and $this->user->validate() and $this->user->login()) {
//.......
} else {
//.......
}
if (Yii::$app->request->isAjax) {
echo Json::encode($response);
}
}
Model:
public function login() {
// Set cookie expire time
$cookie_expire = 3600 * 24 * Yii::$app->params['settings']['cookie_expire'];
return Yii::$app->user->login($this->getUser(), ($this->remember_me ? $cookie_expire : 0));
}
As I suspected (see my earlier comment) response might not be correctly generated in case of simply echoing the data. Or maybe Content-Type header matters. If someone can confirm this it will be great.
Anyway, I'm glad it works now (data needs to be returned).
And you can use Response handy format as well.
public function actionLogin() {
// ...
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $response;
}
}
I use resource make crud, and in the create page, I have to add a preview page
I tried to use ajax post data to admin/article/previewform then in route action controller method previewform catch data and store in variable with redirect to new page preview show it ...
I have problem
1. Why it doesn't redirect to new page ?
2. Why in js console.log get Faild to load resource … statu?s of 500
3. I also try return Redirect::to('admin/article/previewshow'); in previewform then still not redirect to.
But get js console.log with template show.blade.phpthat is in resource show method call.. ??
How to solve it?
js
$.ajax({
url: 'previewform',
type: 'POST',
data: {data: data},
})
.done(function(response) {
console.log(response);
});
route
//.. prefix=>admin
Route::resource('article','AdminArticleController');
Route::post('admin/article/previewform', 'AdminArticlePreviewController#previewform');
Route::get('admin/article/preview', 'AdminArticlePreviewController#preview');
AdminArticlePreviewController
class AdminArticlePreviewController extends AdminController
{
public function preview()
{
$input = Input::get('data');
return Redirect::route('admin/article/previewshow');
}
public function previewshow()
{
// return View::make('admin.article.preview')->with('data', $data)
}
}
It is not possible to make redirection in this way. For ajax requests you need to catch "redirection command" from the server side script (PHP) and execute it in the JS.
Instead:
return Redirect::route('admin/article/previewshow');
you can use:
return Response::make('/redirect/url', 301)
then JS code:
.done(function(response) {
console.log(response);
});
can be replaced by something like:
.done(function(data, statusText, xhr) {
if(xhr.status == 301) {
window.location = data;
}
});
On my website I am using ajax post request to show content around my site, this is done using this code,
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
var data = "calltype=full&url="+url;
$.ajax({
url:url,
type: "POST",
data: data,
success : function (html) {
$('#left-content-holder').html(html);
}
})
});
as you can see I am passing the url into the `$_POST' and I can access this in the method the javascript calls, this method is called get_content_abstract and looks like this,
public function get_content_abstract() {
$this->load->model('content_model');
if($this->input->post('calltype') == "abstract"){
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
elseif($this->input->post('calltype') == "full") {
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['full'] = $query;
}
$this->load->view('template/full-content', $data);
}
}
How ever I have no added a new function that will allow the user to save the content to 'bookmarking system', however in my method I cannot access the post using codeigniters $this->input-post('url') (where URL is the one of peices of data passed in the javascript), it says that the post is empty when I var dump it, this is done using this method,
public function love_this() {
die(var_dump($this->post->input('url')));
}
can anyone help as to why the post is empty in this love_this method?
Shouldn't:
public function love_this() {
die(var_dump($this->post->input('url')));
}
Actually be
public function love_this() {
die(var_dump($this->input->post('url')));
}
See:
http://codeigniter.com/user_guide/libraries/input.html