Ajax and store session in Laravel - php

I Like to store a id in session using AJAX in laravel,In normal php and jQuery i am using the following method ,& how to attain the same in laravel
Normal Method:
$('.action').click(function(){
var editaction=($(this).attr("id"));
$.ajax({
type:"POST",
url:"test_session.php",
data:"test_id="+editaction,
success:function(results){
window.location.href="newredirect.php"
}
});
});

You can use same js code for Laravel. But you need to change "test_session.php" with your route url and "newredirect.php" with redirect route url.
Example Code:
$('.action').click(function(){
var editaction=($(this).attr("id"));
$.ajax({
type:"POST",
url:"ROUTE URL",
data:"test_id="+editaction,
success:function(results){
window.location.href="REDIRECTED ROUTE URL"
}
});
});
Here is example how to save session in Laravel Controller:
public function ExampleRoute(Request $request){
$username = Input::get('username');
if($username){
$request->session()->put('username', $username);
return 'success';
}
}
If you want to get your session, you can use that controller example:
public function ExampleRouteOfGetSession(Request $request){
$username = $request->session()->get('username');
return $username;
}
You can see Laravel Documentation for more information - https://laravel.com/docs/5.4/session#using-the-session

Related

404 error file not found while insert data into database using laravel 5.4

I am new in laravel I am simply wants to insert form input field data into database using jquery ajax but now problem is that when I click on submit button it show 404 error but when I write localhost/practice/public/save in url then (1/1) MethodNotAllowedHttpException. I don't know whay and where I am doing wrong? Please help me.
app/http/controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use DB;
class UserController extends Controller
{
public function save(Request $request)
{
$username = $request->input('username');
$password = $request->input('password');
$confirm_id = md5($username);
$data = array(
'username'=>$username,
'password'=>$password,
'confirm_id'=>$confirm_id
);
print_r($data);
}
}
resources/view/index.blade.php
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
username = $("#email").val();
password = $("#password").val();
$.ajax({
type:"POST",
data:{"username":username,"password":password,"_token":"{{csrf_token()}}"},
url:"{{URL::to('save')}}",
success:function(data){
$("#success").html(data);
}
});
});
});
</script>
route/web.php
<?php
Route::get('/',function(){
return view('index');
});
Route::post('save','UserController#save');
You can't open a post request directly in URL. It will always return MethodNotAllowedHttpException(The GET method is not supported for this route. Supported methods: POST)
So something wrong in ajax request.
url:"{{URL::to('save')}}",
Try to replace this url: {{ url('save') }}

Failed to load resource errors(405) when send Ajax data to php

I have error ->
"Failed to load resource: the server responded with a status of 405
(Method Not Allowed)"
when send Ajax data to PHP in larval.
(I made route)
Ajax code
function insertData()
{
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
insertData();
and my php code "insertContentData.php"
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>
why not work this?
Thanks for your help.
In the http world the "METHOD" normally used is "GET" which is simply pulling data from the server. When you want to send data from the user to the server you used "POST". These are the two most commonly used methods.
The errors says that the METHOD IS NOT ALLOWED. You are AJAX code shows that you are using the POST method.
In Laravel you need to define a route that allows for the POST method. So instead of Route::get($uri, $callback); it would be Route::post($uri, $callback); Some more information can be found in the Laravel Routing documentation. However I think you are missing some concepts based on the primitive PHP code you posted, that code should be inside a controller.
Try to run like this. I hope it works.
function insertData(){
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
window.onload = function(){
insertData();
}
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>

Laravel How to delete session on the homepage

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 );
}

Pass a variable with JQuery to the Controller - PHP Codeigniter

I am working on a project using PHP Codeigniter. I want to know how can I sent a variable with JQuery to the controller. Below is my code
<script>
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id", {id: id}, function(page_response)
{
$(".modal-body").html(page_response);
});
}
</script>
Here I'm first getting the variable 'id' from function parameter. But when I run this code, it return the string 'id' instead of the actual user id from database. I want to view the user id. Below is my function from the controller..
public function Reset_User_Password()
{
$data['admin_id'] = $this->uri->segment(3);
$this->load->view('admin/user/reset_user_password', $data);
}
Send data by POST method is not append in url as GET method. So you can't get is using $this->uri->segment().
Instead use
$data['admin_id']=$this->input->post('id');
Use
$this->input->post('id');
Don't use $this->uri->segment(3); because you are posting id by post method if you want to use $this->uri->segment(3); then do a minior miodification in your function
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/"+id, function(page_response)
{
$(".modal-body").html(page_response);
});
You can take help with this code. It is working perfectly at my end
function Reset_User_Password(){
var currentpwd= document.getElementById("currentpwd").value;
var newpwd = document.getElementById("newpwd").value;
var cnfrmnewpwd = document.getElementById("cnfrmnewpwd").value;
var url = "<?php echo base_url('user/changepwd'); ?>"
$.ajax({
type:"POST",
data:{currentpwd:currentpwd,newpwd:newpwd,cnfrmnewpwd:cnfrmnewpwd},
url:url,
success:function(data){
if(data){
$('#newsleter').html(data);
}
}
});
}
try below code
you should get that id variable from GET method on the controller.
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id="+id
$(".modal-body").html(page_response);
});

Sending variable by ajax in use of laravel

I am trying to send two variables through ajax into the php script in laravel.
It is actually not clear to me how to move these variables.
Would you mind guys to give me some advice on it? the newComment contains some string, and id is just a number.
var newComment = document.getElementById('newComment').value;
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id},
success:function(){
alert('success');
},
error:function(){
alert('failure');
}
});
});
Here is my route:
Route::any('/editcomment/{id}/{newComment}', 'HomeController#editComment');
And here goes the function in homecontroller:
public function editComment(){
$aaa = Input::all();
return $aaa;
}
I am struggling with this for last 2 days, constantly looking at documentations and tutorials but have no idea how to do this.
You don't need to add the variables to the url for this request. The data you include in your ajax request will be send to the server as a post body.
Try changing the route to Route::any('/editcomment', 'HomeController#editComment');
And use
public function editComment(){
return Input::all();
}
This should display the id and the newComment
you have to change your route file like this :
Route::any('/editcomment', 'HomeController#editComment'); because yo dont need to ajax request parameter to send in route file.
And yes in your controller method editComment change like this:
public function editComment(){
if(Request::ajax()) {
return Input::all();
}
}
We have to check that requested by ajax call.
Try,
$_GET['newComment'] and $_GET['id']. This will work.
Thank you :)

Categories