i am trying to update password in Laravel, password is updating but when i try to login it shows wrong details, i am not sure what i am doing wrong here.
public function passwordupdate(Request $request, $id)
{
$user = User::find($id);
// Column updating with incorrect Hash
$user->password = Hash::make($request->password);
$user->setRememberToken(Str::random(60));
$user->active = 0; // This value is updating correctly
$user->save();
return response()->json(['msg' => 'password updated']);
}
As I mentioned my request was posting a null value so I am adding Ajax code to figure why.
Ajax
$('.update_password').on('click', function (e) {
console.log('Update password clicked!')
e.preventDefault();
$.ajax({
type: "POST",
dataType: 'json',
data: $(this).serialize(),
url: "/users/" + $('#user_pwid').val(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
if (data.msg) {
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
}
});
});
View/Blade
<form method="post" id="policy-form">
#csrf
<input type="hidden" value="">
<select name="name" id="user_pwid" class="form-control user_pwid border border-secondary border-dark" required>
<option selected value="">SELECT USER</option>
#foreach($users as $user)
<option value="{{$user->id}}"> {{$user->name}}</option>
#endforeach
</select>
<input type="password" name="password" id="password">
<button type="click" class="btn btn-danger btn-sm update_password rounded text-center" value="{{$user->id}}"
id="update-password"></button>
</form>
Try This:
Controller Code:
public function passwordupdate(Request $request,$id) {
$user = User::find($id);
if(!is_null($user)){
$user->password = Hash::make($request->password);
$user->setRememberToken(Str::random(60));
$user->active =0;
$user->save();
return response('success');
}
else{
return response('failed');
}
}
Ajax Code:
$('#update-password').on('click', function(e) {
e.preventDefault();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
type: "post",
url: "/users/" + $('#user_pwid').val(),
data :{
password : $('#password').val(),
},
success: function (data) {
if(data == 'success'){
alert('password changed successfully');
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data);
}
else{
alert('failed');
}
},
});
});
Try this it'll work
Does $request->password actually have the intended password? Are you sure you haven't written a mutator on the model that is double hashing the password?
Is there a good reason you're creating your own password reset controller instead of using the one that Laravel ships with? Also - you really don't want to send the password back to the user in JSON.
Related
i am using ajax to store the info but when i store or not store it returns a json page and i don't want it to return a json i want to add the item without relead the page and using calidation also
please help
here is my code
my route
Route::resource('products',App\Http\Controllers\ProductController::class);
my form
<form method="POST" id="productform">
#csrf
#method('POST')
<ul id="showerrors">
</ul>
<div class="form-group">
<label for="">name</label>
<input type="text" name="name" class="form-control">
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
and my ajax code
<script>
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var data = {
'name' : $("input[name='name']").val(),
'_token' : $("input[name='token']").val(),
}
// console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:data,
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
Try this solution
add id to input field
<input type="text" name="name" class="form-control" id="name">
changes in script
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:{
name: name
},
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
in your controller store function
suppose your model name is Product
public function store(Request $request)
{
...
$product = Product::create($request->only('name));
return response()->json([
'status' => 200,
'message' => 'Product created successfully.'
]);
}
i have a login form to login a user i want to know about how to get laravel response in ajax success function. if submit the form i was got a object('status':'msg') in http://127.0.0.1:8000/login page. but i want to just redirect user correct page after login with macing alert. please help me to learn laravel with ajax function.
form
<form id="loginForm" method="POST" action="{{ route('login') }}">
#csrf
<input id="email" type="email" class="form-control name="email" value="{{ old('email') }}"
required autocomplete="email" autofocus>
<input id="password" type="password" class="form-control name="password" required
autocomplete="current-password">
<button type="submit" class="btn btn-primary">LOGIN</button>
</form>
ajax: after document ready
$('#loginForm').submit(function(e){
e.preventDefault();
var formInput = $(this);
$.ajax({
type:'POST',
url: 'login',
data: formInput.serialize(),
dataType: 'json',
cache: false,
success:function(status){
if(status== "success"){
alert("your in");
}
},
error:function(status){
if(status== "error"){
alert("no data found");
}
}
})
});
Route:
Route::post('login','loginController#login')->name('loginData');
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Session;
class loginController extends Controller
{
public function login(Request $request){
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// print_r($request->all());
session()->put('role', Auth::user()->Role);
$request->session()->flash('message', 'New customer added successfully.');
$request->session()->flash('message-type', 'success');
return response()->json(['status'=>'success']);
return back();
}else{
$request->session()->flash('message', 'you have entered an invalid email address or password. please try again');
$request->session()->flash('message-type', 'danger');
return response()->json(['status'=>'error']);
return back();
}
}
}
You can return more data in your AJAX response than just a status. If you wanted to, you could also return a location to redirect to like:
return response()->json([
'status' => 'success',
'redirect' => '/user/dashboard'
]);
Then in your javascript, when you get success, you can then do:
success: function(response) {
if(response.status === "success") {
alert("your in");
window.location.href = response.redirect;
}
},
I'm trying to send data to back-end and i'm getting 404 error with this explanation in network tab:
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
Route
Route::middleware('verified')->group(function () {
Route::post('/snaptoken/{id}', 'Admin\PayController#token')->name('securepaymentnow');
});
Controller
public function token(Request $request, $id)
{
//Find project
$project = Project::findOrFail($id);
//rest of data
}
Blade
//form and button
<form id="payment-form" method="POST" action="{{route('securepaymentnow', $project->id)}}">
#csrf
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<button class="btn-sm bg-success pay-button" data-id="{{$project->id}}" type="submit"><i class="fas fa-fas fa-shield-alt"></i> Secure Payment</button>
//javascript
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/securepaymentnow")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
}
});
});
Any idea?
.........................................................................................................................
if you are using url() function, you should use the {{ url('/snaptoken') }}.
But if you want to use the "name" from the "securepaymentnow", use route() function with this example {{ route('securepaymentnow', $theId) }}.
Both should works.
Refer Laravel NamedRoute for details.
I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.
I need to create auth from any pages over ajax. If i'm send wrong login and empty pass(or vice versa) - will be return json errors (it's ok). If i'm send wrong login and wrong pass(or right login and path) - will be return redirect.
How to change backend for get response json anyway?
my frontend code js:
$("#authform").submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(data) {
console.log(data);
}, "json");
});
html:
<form id="authform" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="email" name="email" value="{{ old('email') }}">
<input type="password" name="password">
<input type="checkbox" name="remember">
<button type="submit">Login</button>
</form>
routes.php:
Route::post('auth/login', 'Auth\AuthController#postLogin');
This is not an answer. First try this then we should
$('#authform').on('submit',function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: $(#authform).attr("action"),
data: $('#authform').serialize(),
success: function(data) {
console.log(data);
},
});
return false;
});
And have you tried this link How to create AJAX login with Laravel
I'm sure there is a better solution for this problem, but what I did was:
Create a new route for loging in
Route::post('/login', 'Auth\AuthController#signIn');
In App\Http\Controllers\Auth\AuthController I added two new methods:
public function signIn(Request $request) {
$this->validateLogin($request);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponseJSON($request);
}
AND
protected function sendFailedLoginResponseJSON(Request $request)
{
return response()->json(['username' => $this->getFailedLoginMessage()], 422);
}
It's basically the same as the login method from AuthenticatesAndRegistersUsers trait, except for the last line, the login method uses
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
which sends back a redirect with the error.
If you want both ajax and non-ajax, you can do
if($request->ajax()){
return $this->sendFailedLoginResponseJSON($request);
}
return $this->sendFailedLoginResponse($request);
in the new sign in method.