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

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

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

How to submit a popup form with ajax request in laravel

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
}

Laravel 5.6 unable access user details after login with Ajax

I have login modal in view and want to login with Ajax in Laravel 5.6. Ajax returns me 'Success' message, but when I refresh window location with JS, User data is not accessible from blade template. Here is my code
My Controller
protected function authenticated(Request $request)
{
$auth = false;
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
$auth = true; // Success
$request->session()->put('current_user',Auth::user());
}
if ($request->ajax()) {
return response()->json([
'success' => true,
'auth' => $auth,
'intended' => URL::previous()
]);
} else {
return redirect()->intended(URL::route('contact'));
}
return redirect(URL::route('login_page'));
}
My Ajax
$(document).ready(function () {
var loginForm = $("#loginForm");
loginForm.submit(function(e){
e.preventDefault();
var formData = loginForm.serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"{{ route('ajax_login') }}",
type:'POST',
data:formData,
success:function(data){
// console.log(data);
window.location.href = '/'
},
error: function (data) {
console.log('failed');
}
});
});
My Route
Route::post('/user-login', 'Auth\LoginController#authenticated')->name('ajax_login');
It's because when you refresh using window.location.reload all the javascript files will be reloaded and the variables will be cleaned.
You can store your data in the local storage window.localStorage.putItem('key', object) or directly use your data using jQuery, it depends on yout need.
Hopes it helps.

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/

How not to redirect page on ajax submit codeigniter

So, i have a following ajax code and controller code, my problem is i want to insert comment withouth refreshing the page and not redirecting to another page, and it seems that whenever i hit btnCommentSubmit it is redirecting me to my controller page, how to prevent that?
Ps. The insertion is working
//AJAX CODE
$('#btnComment').click(function(e){
var comment_identifier = $(this).data("value");
var comment_by = $(this).data("id");
$('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/'+comment_identifier+"/"+comment_by);
});
$('#btnCommentSubmit').click(function(){
var url = $('#formAddComment').attr('action');
var addCommentTxt = $('#addCommentTxt').val();
$.ajax({
type: 'post',
url: url,
data: {addCommentTxt:addCommentTxt},
success: function(){
alert('success');
},
error: function(){
console.log(data);
alert('Could not add data');
}
});
});
});
//Controller code
public function addComment(){
$cIden = $this->uri->segment(3);
$cBy = $this->uri->segment(4);
$data = array(
"comment_identifier" => $cIden,
"comment_by" => preg_replace('/[^a-zA-Z-]/', ' ', $cBy),
"comment" => $this->input->post('addCommentTxt'),
"comment_at" => time()
);
if ($this->Crud_model->insert('comments',$data)) {
return true;
}else{
return false;
}
}
Add e.preventDefault() in the beginning of your function:
$('#btnCommentSubmit').click(function(e){
e.preventDefault();
...
}
You may want to use jQuery form plugin. It submit form to our controller without any page refresh/redirect. I use it all the time.
https://jquery-form.github.io/form/
Example usage:
$('#form').ajaxForm({
beforeSubmit: function() {
//just optional confirmation
if (!confirm('Are you sure want to submit this comment?')) return false;
show_loading();
},
success: function(status) {
hide_loading();
if (status == true) {
alert('success');
} else {
alert('Could not add data');
}
}
});
You can use javascript:void(0); like href="javascript:void(0);"

Categories