How to submit a popup form with ajax request in laravel - php

My Ajax Code
Query(document).ready(function(){
jQuery('#password_form').click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/changepassword') }}",
method: 'post',
data: {
password: jQuery('#password').val(),
new_password: jQuery('#new_password').val(),
password_confirmation: jQuery('#password_confirmation').val()
},
success: function(result){
console.log(result);
}});
});
});
My Controller:
public function changepassword(Request $request){
$user = Auth::guard()->user();
$request_data = $request->All();
$validator = $this->admin_credential_rules($request_data);
if($validator->fails()) {
$errors = $validator->errors();
$errors = json_decode($errors);
return response()->json([
'success' => false,
'message' => $errors
], 422); } else {
$current_password = $user->password;
if(md5($request_data['password']) == $current_password) {
$user_id = $user->id;
$obj_user = User::find($user_id);
$obj_user->password = md5($request_data['new_password']);
$obj_user->save();
return \Illuminate\Support\Facades\Redirect::to('mujucet')
->with("modal_message_success", "Password has been changed successfully");
} else {
return \Illuminate\Support\Facades\Redirect::to('mujucet')
->with("modal_message_danger", "wong old password");
}
}
}
I am have a popup a there is three fields
1- password
2- new_password
3- password_confirmation
Before ajax my form was submitting but i want to submit form with ajax so my page should not be reload and my success and error message should be shown on my popup form but here when i hit button its reload and also values are not submitted.
I dont know what is wrong with my ajax request.
Your help will be highly appreciated!
Thanks in advance please need your help.

$("#myform").submit(function(e){
e.preventDefault();
//put your ajax here
});
You need to prevent the form from submitting using the code above.

Your popup submit button should be button not submit
<button type="button" class="btn btn-primary" title=""
id="btn_submit">add</button>
<script>
$('#btn_submit').click(function () {
var type = $('#contain-type').val(); // take your all values you want to send
/*ajax call*/
$.post(baseUrl + '/admin/confirmation-mail(your route)',{"_token": "{{
csrf_token() }}", id: parameter, subject: parameter},
function (data, status) {
alert(data);
});
)};
</script>
Controller
public function name(Request $request){
dd(request->all()); //add your php code
}

Related

Codeigniter validation not working with ajax but without ajax working well

when submitting the form using ajax codeigniter validation not working please resolve this issue i am facing this problem from last week
jQuery code that i am using for submitting form
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
data: contactForm.serialize(),
success: function(response){
}
});
});
});
Controller
public function add_account() {
if($this->form_validation->run('add_account')) {
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
} else {
$this->login();
}
}
Here is just the concept. I have not tried codeigniter but am php professional.
You will need to retrieve records as json and pass it to ajax. At codeigniter
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'Account Created Successfully !');
echo json_encode($result);
hence the code might look like below
public function add_account(){
if($this->form_validation->run('add_account')){
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'ok');
echo json_encode($result);
//$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
}else{
$this->login();
}
}
in ajax you can set datatype to json to ensure that you can get response from the server and then let ajax handle the response....
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function(response){
alert(response.message);
console.log(response.message);
//display success message if submission is successful
if(response.message =='ok'){
alert('message submited successfully');
}
}
});
});
});
You have a misunderstanding about what an ajax responder can and cannot do. One thing it cannot do is use PHP to make the browser redirect to a new page. You will have to send a clue back to the success function and then react appropriately.
A few minor changes to the answer from #Nancy and you should be good.
public function add_account()
{
if($this->form_validation->run('add_account'))
{
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post))
{
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
echo json_encode(array("result" => 'ok'));
return;
}
$message = '<span class="error">Account Not Created!</span>';
}
else
{
$message = validation_errors('<span class="error">', '</span>');
}
echo json_encode(array("result" => 'invalid', 'message' => $message));
}
In the Javascript, handle the various responses in the success function of $.ajax
$(function () {
$("#registratiom_form").on('submit', function (e) {
var contactForm = $(this);
e.preventDefault();
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function (response) {
console.log(response); // so you can examine what was "echo"ed from the server
if (response.message=='ok') {
// Simulate an HTTP redirect: to the right page after successful login
window.location.replace( "https://example.com/frontend/somepage");
} else {
//stay on the same page but show the message in some predefined spot
$('#message').html(response.message);
}
}
});
});
});

Laravel Update Database with ajax

Hey guys I'm using laravel 5.7 and I'm attempting to make a ajax post request to update my database. The ajax would post based on a checkbox on change function. Example if i toggle off the checkbox it would send a request and update my status to Inactive in my User table. After attempting it, i had an error of 405 (Method Not Allowed). Anyone able to note what am i doing wrong? Sorry if there are some wrong codes or syntax in my codes as I'm very new to Ajax. Any help would be appreciated.
Ajax
$(document).ready(function(){
$.ajax({
type:'get',
url:'{!!URL::to('findStatus')!!}',
success:function(data){
for(var i=0;i<data.length;i++){
var checkBox = document.getElementById('switch-'+data[i].u_id);
console.log(checkBox);
if(data[i].status == "Active"){
$('#switch-'+data[i].u_id).prop('checked',true);
}
else if(data[i].status == "Inactive")
{
$('#switch-'+data[i].u_id).prop('checked',false);
}
$('#switch-'+data[i].u_id).change(function(){
$.ajax({
type: "POST",
url : '{!!URL::to('admin/{admin}')!!}',
success:function(data){
console.log(data);
}
});
});
}
},
error:function(data){
console.log('ERROR');
}
});
});
Route
Route::resource('admin','AdminController'); << I'm using the update method from the resource controller
Controller
public function update(Request $request, $id)
{
$user = User::find($id);
if($user->status == "Active"){
$user->status = "Inactive";
$user->save();
}else{
$user->status = "Active";
$user->save();
}
return response()->json($user);
}
Form
{!!Form::open(array('action'=>['AdminController#update',$item->u_id],'method'=>'POST','id'=>'update'))!!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="u_id" id="u_id" value="{{$item->u_id}}">
<label class="custom-control custom-checkbox">
<input type="checkbox" id="switch-{{$item->u_id}}" class="custom-control-input">
<span class="custom-control-indicator"></span>
</label>
{{-- <button class="btn btn-primary">Update</button> --}}
{{Form::hidden('_method','PUT')}}
{!!Form::close()!!}
UPDATE
I have managed to "pass" the u_id to my post request by getting the id through target.id and splitting it with -. It is not the most elegant way but it works. But now im getting an error
POST http://manageme.test/admin/%7B2%7D 500 (Internal Server Error)
Here is what i have updated in my codes.
$('#switch-'+data[i].u_id).change(function(e){
console.log(e.target.id);
var s = e.target.id;
var split = s.split('-')[1];
$.ajax({
type: "POST",
url: `{!!url('admin/')!!}/{${split}}`,
data: { _token: "{{ csrf_token() }}", _method: "PUT" },
success:function(data){
console.log(data);
}
});
});
these are inside my update controller
public function update(Request $request, $id)
{
$user = User::find($id);
if($user->status == "Active"){
$user->status = "Inactive";
$user->save();
}else{
$user->status = "Active";
$user->save();
}
return response()->json($user);
}
I have also looked at the error inside the network tab of the dev tools the error message from laravel is message: "Trying to get property 'status' of non-object". I think it cant find any $user inside the update method
Instead of:
"{!!URL::to('admin/{admin}')!!}"
write :
`{!!url('admin/')!!}/${data[i].u_id}`
and add _token and _method params to your ajax data
and write like this:
$(document).ready(function () {
$.ajax({
type: 'get',
url: '{!!url('findStatus')!!}',
success: function (data) {
data.forEach(d => {
console.log(d);
if (d.status == "Active") {
$(`#switch-${d.u_id}`).prop('checked', true);
}
else if (d.status == "Inactive") {
$(`#switch-${d.u_id}`).prop('checked', false);
}
$(`#switch-${d.u_id}`).change(function () {
console.log(d);
//changed###########
$.ajax({
type: 'POST',
url: `{!!url('admin/')!!}/${d.u_id}`,
data: { _token: "{{ csrf_token() }}", _method: "PUT" },
success: function (data) {
console.log(data);
}
});
//###################
});
});
},
error: function (data) {
console.log('ERROR');
}
});
});
Solution
I managed to fix it the problem was coming from the route trying to pass the u_id of the user and finding the user's data. So instead of typing the url inside, i made a variable to pass the route and u_id together. Here are the codes
Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'get',
url:'{!!url('findStatus')!!}',
success:function(data){
for(var i=0;i<data.length;i++){
var checkBox = document.getElementById('switch-'+data[i].u_id);
if(data[i].status == "Active"){
$('#switch-'+data[i].u_id).prop('checked',true);
}
else if(data[i].status == "Inactive")
{
$('#switch-'+data[i].u_id).prop('checked',false);
}
$('#switch-'+data[i].u_id).change(function(e){
var s = e.target.id;
var split = s.split('-')[1];
var url = '{{route('admin.update','split')}}';
$.ajax({
type: 'POST',
url: url,
data: { _token: "{{ csrf_token() }}", _method: "PUT" ,u_id: split},
success: function(data) {
console.log(data['message']);
}
});
});
}
},
error:function(data){
console.log('ERROR');
}
});
Update method
public function update(Request $request, $id)
{
$user = User::find($request['u_id']);
if($user->status == "Active")
{
$user->status = "Inactive";
$user->save();
return response()->json(['message' => 'Update to Inactive']);
}else{
$user->status = "Active";
$user->save();
return response()->json(['message' => 'Update to Active']);
}
}
DONT forget to add the meta tag onto the document header for csrf token
<meta name="csrf-token" content="{{ csrf_token() }}">

How to validate input data using ajax in laravel

testAjax function inside PostsController class:
public function testAjax(Request $request)
{
$name = $request->input('name');
$validator = Validator::make($request->all(), ['name' => 'required']);
if ($validator->fails()){
$errors = $validator->errors();
echo $errors;
}
else{
echo "welcome ". $name;
}
}
inside web.php file:
Route::get('/home' , function(){
return view('ajaxForm');
});
Route::post('/verifydata', 'PostsController#testAjax');
ajaxForm.blade.php:
<script src="{{ asset('public/js/jquery.js') }}"></script>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Name<input type="text" name="name" id="name">
<input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
}
});
/**Ajax code ends**/
});
});
</script>
So when click on submit button by entering some data then the output message(echo "welcome ". $name;) is printing. But when I click on submit button with empty text box then it does not print the error message from the controller and it throws a 422 (Unprocessable Entity) error in console. Why my approach is wrong here and how can I print the error message then. Please help. Thank you in advance.
Your approach is actually not wrong, it's just, you need to catch the error response on your ajax request. Whereas, when Laravel validation fails, it throws an Error 422 (Unprocessable Entity) with corresponding error messages.
/**Ajax code**/
$.ajax({
type: "post",
url: "{{ url('/verifydata') }}",
data: {name: name, _token: token},
dataType: 'json', // let's set the expected response format
success: function(data){
//console.log(data);
$('#success_message').fadeIn().html(data.message);
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
console.log(err.responseJSON);
$('#success_message').fadeIn().html(err.responseJSON.message);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
}
}
});
/**Ajax code ends**/
On your controller
public function testAjax(Request $request)
{
// this will automatically return a 422 error response when request is invalid
$this->validate($request, ['name' => 'required']);
// below is executed when request is valid
$name = $request->name;
return response()->json([
'message' => "Welcome $name"
]);
}
Here's a better approach to validation:
In your controller:
public function testAjax(Request $request)
{
$this->validate($request, [ 'name' => 'required' ]);
return response("welcome ". $request->input('name'));
}
The framework then will create a validator for you and validate the request. It will throw a ValidationException if it fails validation.
Assuming you have not overriden how the validation exception is rendered here's the default code the built-in exception handler will run
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
if ($e->response) {
return $e->response;
}
$errors = $e->validator->errors()->getMessages();
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()->withInput($request->input())->withErrors($errors);
}
Again this is handled for you by the framework.
On the client side you should be able to do:
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
},
error: function (xhr) {
if (xhr.status == 422) {
var errors = JSON.parse(xhr.responseText);
if (errors.name) {
alert('Name is required'); // and so on
}
}
}
});
/**Ajax code ends**/
});
});
</script>
best way for handle in php controller :
$validator = \Validator::make($request->all(), [
'footballername' => 'required',
'club' => 'required',
'country' => 'required',
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
return response()->json(['success'=>'Record is successfully added']);
The code for form validation in Vannilla Javascript
const form_data = new FormData(document.querySelector('#form_data'));
fetch("{{route('url')}}", {
'method': 'post',
body: form_data,
}).then(async response => {
if (response.ok) {
window.location.reload();
}
const errors = await response.json();
var html = '<ul>';
for (let [key, error] of Object.entries(errors)) {
for (e in error) {
html += `<li>${error[e]}</li>`;
}
}
html += '</ul>';
//append html to some div
throw new Error("error");
})
.catch((error) => {
console.log(error)
});
Controller
use Illuminate\Support\Facades\Validator;//Use at top of the page
$rules = [
'file' => 'image|mimes:jpeg,png,jpg|max:1024',
'field1' => 'required',
'field2' => 'required'
];
$validator = Validator::make($request->post(), $rules);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
session()->flash('flash', ['status' => 'status', 'message' => 'message']);
Jquery Code:
let first_name= $('.first_name').val();
let last_name= $('.last_name').val();
let email= $('.email').val();
let subject= $('.subject').val();
let message= $('.message').val();
$('.show-message').empty();
console.log('clicked');
$.ajax({
type : 'POST',
url : '{{route("contact-submit")}}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
first_name,
last_name,
email,
subject,
message,
},
success: function(data) {
console.log('data',data);
$('.show-message').html('Form Submitted');
},
error : function(data,data2,data3)
{
let response=data.responseJSON;
let all_errors=response.errors;
console.log('all_errors',all_errors);
$.each(all_errors,function(key,value){
$('.show-message').append(`<p>${value}</p>`);
});
}
});
Controller Code:
$validator=Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email',
'subject'=>'required',
'message'=>'required',
]);
if($validator->fails())
{
return response()->json([
'success'=>false,
'errors'=>($validator->getMessageBag()->toArray()),
],400);
}
return response()->json([
'success'=>true,
],200);
See More Details at: https://impulsivecode.com/validate-input-data-using-ajax-in-laravel/

e.preventDefault() does not work. AJAX / Laravel 5.4

I have an Ajax call which sends user form input to be processed in the back end. The controller in the back-end sends back result as JSON, when the form is submitted the page reloads and redirects to a blank page with raw JSON instead of the json being picked up by AJAX.
This is the Ajax call:
<script type="text/javascript">
$(document).ready(function(){
$('form').on('submit', '#topup-form', function(e){
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
method: 'post',
data: $('form').serialize(),
success: function(result){
alert(result);
},
error: function(errorData){
alert(errorData);
}
});
});
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
})
});
</script>
This is the Laravel controller, if the validation fails it sends Json, if the user is authenticated, it redirects the user, else it returns 401 asking user to login.
public function topupPost(Request $request) {
$validator = [
'topupAmount'=> 'required|integer|between:10,500',
'phonenumber'=> 'required|regex:/^05[602][0-9]{7}$/',
];
$inputs = $request->all();
Log::info($inputs);
$validator = Validator::make($inputs, $validator);
if($validator->fails()){
return Response::json([
'error' => true,
'message' => $validator->messages(),
'code' => 400
], 400);
}
elseif (Auth::check()) {
return view('pages.checkout', compact('inputs'));
}
return Response::json([
'error' => true,
'message' => "Please login first",
'code' => 401
], 401);
}
What happens is that nothing pops up as an alert but the user is redirected to a page with the raw JSON.
I had faced a similar issue
I solved it by changing the submit button type to "button" so that the form does not auto submit. my ajax code is below:
$(document).ready(function() {
$("#submit").click(function() {
var loginForm = $("#contactForm");
var formData = loginForm.serialize();
/*alert(formData);*/
$.ajax({
url: /*you URL*/,
type:'post',
data:formData,
success:function(data){
//alert(data); //for redirecting instead of alert try below code
if(data == "") { //True Case i.e. passed validation
alert('error')
}
else { //False Case: With error msg
alert(data); //$msg is the id of empty msg
}
},
error: function (data) {
/*console.log(data);*/
alert(data);
}
});
});
/*alert('Successfully Loaded');*/
});
also your php response handle seems fine. hope this helps

Laravel - Toggle value in database with checkbox and ajax

I want to toggle a boolean value in my table with a checkbox through jquery and ajax.
So whenever a user ticks the the checkbox it should toggle the value in table.
So far i came up with this but i need help:
$(document).ready(function(){
$("input:checkbox").change(function() {
var isChecked = $("input:checkbox").is(":checked") ? 1:0;
$.ajax({
type:'POST',
url:'/activation',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: $('.checkbox').serialize(),
success:function(data){
}
});
});
});
#andre's answer is correct but
if($user->active == 1){
$user->active = 0;
} else {
$user->active = 1;
}
this part can be done by a single line
$user->active = !$user->active;
The only thing I'd modify would be returning an answer to the ajax call to let it know what's happening.
public function activation(Request $request)
{
$user = User::findOrFail($request->user_id);
if($user->active == 1){
$user->active = 0;
} else {
$user->active = 1;
}
return response()->json([
'data' => [
'success' => $user->save(),
]
]);
}
And now in the front-end part:
$(document).ready(function(){
$("input:checkbox").change(function() {
var user_id = $(this).closest('tr').attr('id');
$.ajax({
type:'POST',
url:'/activation',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: { "user_id" : user_id },
success: function(data){
if(data.data.success){
//do something
}
}
});
});
});
jQuery Ajax documentation
in model create a method
function toggleActive ()
{
$this->active!=(int)$this->active;
return $this;
}
in controller
$model->toggleActive()->save();

Categories