commenting module by ajax not working in laravel 5 - ajax

i am working on commenting module in my project by ajax. i am getting this error
POST http://127.0.0.1:8000/comments 500 (Internal Server Error)
and the data not post. what i am doing wrong? My route is a resource route and i want to display it without refreshing the page .
Form
<form action="{{route('comments.store')}}" method="post">
{{ csrf_field() }}
<div class="col-md-11 col-sm-11">
<div class="form-group">
<textarea name="comment-msg" id="comment-name" cols="30" rows="1" class="form-control" placeholder="comment here..."></textarea>
<input type="hidden" id="eventID" name="eventID" value="<?php echo $eventData->id; ?>">
<input type="hidden" id="userID" name="userID" value="<?php echo Auth::user()->id; ?>">
</div>
</div>
<div class="col-md-12">
<button type="submit" id="submit-comment" class="btn-primary pull-right">Comment</button>
</div>
</form>
Ajax Call
<script>
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});
$( '#submit-comment' ).click(function() {
var formData = {
'message' : $('#comment-msg').val(),
'eventID' : $('#eventID').val(),
'userID' : $('#userID').val(),
};
$.ajax({
type : 'POST',
url : '{{route('comments.store')}}',
data : formData,
dataType : 'json',
encode : true,
success: function (response) {
console.log(response);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
event.preventDefault();
} );
</script>
Controller
public function store(Request $request)
{
$content = $request->input( 'comment-msg' );
$userID = $request->input( 'userID' );
$eventID = $request->input( 'eventID' );
$response=Comment::create([
'user_id' => $userID,
'event_id' => $eventID,
'message' => $content,
]);
return response()->json($response);
}
Route
Route::resource('comments', 'CommentsController');

Related

Laravel How to handle file upload: Can't save image filename

So I want to upload a picture but it only store its description correctly. The file is stored as "noimage.jpg" which means the filename isn't read. I'm using modal btw. My database is named galleries and the migration contains these:
$table->id();
$table->timestamps();
$table->string('upload');
$table->longtext('description')->nullable();
CONTROLLER:
public function store(Request $request)
{
$galleries=new Gallery;
// Handle File Upload
if($request->hasFile('upload')){
// Get filename with the extension
$filenameWithExt = $request->file('upload')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('upload')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.$extension;
// Upload Image
$path = $request->upload('upload')->storeAs('public/upload', $fileNameToStore);
// make thumbnails
$thumbStore = 'thumb.'.$filename.'_'.time().'.'.$extension;
$thumb = Image::make($request->file('upload')->getRealPath());
$thumb->save('storage/upload/'.$thumbStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$galleries->description = $request->input('description');
$galleries->upload = $fileNameToStore;
$galleries->save();
}
FORM:
<form id="uploadForm">
<div class="modal-body">
<input type="hidden" name="id" id="id">
<!-- Upload image input-->
<div class="input-group mb-3 px-2 py-2 rounded-pill bg-secondary shadow-sm">
<input type="file" name="upload" id="upload" onchange="readURL(this);" class="form-control border-0">
<label id="upload-label" for="upload" class="font-weight-light text-muted">Choose file</label>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
</div>
</div>
<!-- Uploaded image area-->
<p class="font-italic text-white text-center">The image uploaded will be rendered inside the box below.</p>
<div class="image-area mt-4 bg-white"><img id="imageResult" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
<label>Caption</label>
<input type="textarea" class="form-control text-white" name="description" id="description">
</div>
</form>
AJAX
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//ADD PICTURE
$('#btnUpload').click(function(){
$('#uploadModal').modal('show');
});
$('#btnSave').click(function(){
$.ajax({
data: $('#uploadForm').serialize(),
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
});
//Image reader to show pic when selected
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function () {
$('#upload').on('change', function () {
readURL(input);
});
});
var input = document.getElementById( 'upload' );
var infoArea = document.getElementById( 'upload-label' );
input.addEventListener( 'change', showFileName );
function showFileName( event ) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
});
</script>
Assuming you're using ajax to upload the file, you'll need to use a FormData object instead of .serialize()
$.ajax({
data: new FormData($('#uploadForm').get(0)), // use formdata object
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
contentType: false, // required for
processData: false, // jquery ajax file upload
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
You don't add "enctype" in form tag.
Change your code:
<form id="uploadForm">
with:
<form id="uploadForm" enctype='multipart/form-data'>
If this above not working then:
1.install this package by following command:
composer require "laravelcollective/html":"^5.2.0"
2.In config/app add this line:
'providers' => [
// ...
**Collective\Html\HtmlServiceProvider::class,**
// ...
],
and
'aliases' => [
// ...
**'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,**
// ...
],
3.Change Form:
{!! Form::open([ 'action'=> 'NameofController#store', 'method' => 'POST','enctype' => 'multipart/form-data' ]) !!}
<div class="form-group">
{{Form::text('name','' , ['class' =>'form-control'])}}
</div>
<div class="form-group">
{{Form::text('phone','' , ['class' =>'form-control', 'placeholder' => 'phone' ])}}
</div>
<div class="form-group">
{{Form::file('image_name')}}
</div>
{{Form::submit('Submit' , ['class' =>'btn btn-primary' ])}}
{!! Form::close() !!}
you can this way to store your file with custom name:
$path = $request->file('upload')->store('public/upload/' .$fileNameToStore);

WordPress AJAX 400 Bad request while submitting form

I am poor in AJAX and trying to submit the form and insert the record to the custom table since a couple of days but not getting it to work.
I am getting 400 Bad request error on console. Please have a look at the code.
In fact, I have tried multiple ways to submit data but none of them
works.
HTML
<form class="addtocartform" id="gsAddToCart" method="POST">
<label class="gs-label" for="options">Options</label>
<select class="gs-select-box" id="product_option" name="product_option">
<option value="0">Somnath</option>
<option value="1">Dwarka</option>
<option value="2">Rameshwaram</option>
</select>
<label class="gs-label" for="qty">Qty.</label>
<input class="gs-number" id="qty" min="1" name="qty" step="1" type="number" value="1">
<button class="gs-button order-button add-to-cart-button">
<i class="fa fa-cart-plus"></i>
<span class="gs-button-label">Add to Cart</span>
</button>
<input id="product" name="product" type="hidden" value="160"/>
<input id="group_id" name="group_id" type="hidden" value="194"/>
</input>
</form>
WordPress Hooks - Enqueue scripts
function gs_enqueue_ajax_scripts()
{
wp_register_script('gs-ajax', GROUP_SHOP_ROOT . 'public/js/add-to-cart-ajax.js', ['jquery'], 1.0, TRUE);
wp_localize_script('gs-ajax', 'ajax_vars', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('gs_nonce'),
]);
wp_enqueue_script('gs-ajax');
}
add_action('wp_enqueue_scripts', 'gs_enqueue_ajax_scripts');
WordPress Hooks - Process and Insert Data
function gs_add_to_cart_ajax()
{
check_ajax_referer('gs_nonce', $_POST[ 'nonce' ], FALSE);
// validating stuffs ..
$cart = new Group_Shop_Cart();
$cart->add_to_cart($_POST[ 'group_id' ], $_POST[ 'product' ], $_POST[ 'qty' ], $_POST[ 'product_option' ]);
wp_die();
}
add_action('wp_ajax_gs_add_to_cart_ajax', 'gs_add_to_cart_ajax');
add_action('wp_ajax_nopriv_gs_add_to_cart_ajax', 'gs_add_to_cart_ajax');
Javascript
(function ($) {
$(document).on("click", ".add-to-cart-button", function () {
let data = JSON.stringify({
action: 'gs_add_to_cart_ajax',
group_id: $('#group_id').val(),
product: $('#product').val(),
qty: $('#qty').val(),
product_option: $('#product_option').val(),
});
$('form.addtocartform').on('submit', function (e) {
e.preventDefault();
$.ajax({
method: 'POST',
dataType: 'json',
nonce: ajax_vars.nonce,
url: ajax_vars.ajax_url,
data: data,
success: function (response) {
alert("Success");
}
});
});
});
})(jQuery);
I have no idea what is wrong in this code that not submitting.
Modified Code
$.ajax({
method: 'POST',
dataType: 'json',
nonce: ajax_vars.nonce,
url: ajax_vars.ajax_url,
data: {
action: 'gs_add_to_cart_ajax',
group_id: $('#group_id').val(),
product: $('#product').val(),
qty: $('#qty').val(),
product_option: $('#product_option').val(),
},
success: function (response) {
alert("Success");
}
});

Laravel 5.5 Multilanguage validation

Please tell me, I ran into a problem. There is a site based on Laravel 5.5. The site has a multilanguage (two languages en/ru). For multilanguage I'm using:
dimsav/laravel-translatable
mcamara/laravel-localization
Added language files to the directory resources/lang/ru. The problem is the validation of the form. The site has a feedback form in the modal window, working with ajax (sending and validating), error messages are displayed only in the default language, the default language is en. I tried to send data from the form without the help of ajax, everything works well, messages are displayed in both Russian and English.
reoutes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::get('/', 'PagesController#getProfile')->name('profile');
Route::get('/skills', 'PagesController#getSkills')->name('skills');
Route::get('/portfolio', 'PagesController#getPortfolio')->name('portfolio');
Route::get('/resume', 'PagesController#getResume')->name('resume');
Route::post('/contact', 'PagesController#contact');
});
controller
public function contact(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
if ($validator->passes()) {
Mail::to('mycontactform#mail.ru')->send(new Contact($request));
return response()->json(['success'=>'Message sent successfully!']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
js
$(document).ready(function() {
$(".btn-send-message").click(function(e){
e.preventDefault();
$.ajax({
url: "/contact",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
});
var $success_msg = $(".print-success-msg");
var $error_msg = $(".print-error-msg");
function printSuccessMsg() {
$success_msg.html('Message sent successfully!');
$success_msg.css('display','block');
$success_msg.delay(5000).fadeOut(350);
$('#contact-form')[0].reset();
}
function printErrorMsg (msg) {
$error_msg.find("ul").html('');
$error_msg.css('display','block');
$.each( msg, function( key, value ) {
$error_msg.find("ul").append('<li>'+value+'</li>');
});
$error_msg.delay(5000).fadeOut(350);
}
});
form
<div class="modal-body col-md-8 offset-md-2">
<div class="alert alert-danger print-error-msg" style="display:none">
<strong>Errors:</strong>
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none"></div>
{!! Form::open(['id'=>'contact-form']) !!}
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Your Name">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Your Email">
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="3"></textarea>
</div>
<button type="button" class="btn btn-success btn-send-message"><i class="fas fa-paper-plane"></i>
Send Message <span id="loading" style="display: none;"><img class="loader"
src="{{ asset('images/loading.gif') }}"></span>
</button>
{!! Form::close() !!}
</div>
Use LaravelLocalization::getLocalizedURL() which returns an URL adapted to $locale.
So your ajax code will be.
$.ajax({
url: "{{ LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(),'/contact') }}",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
When you return your response try to use this helper __('translated_string')
To use this helper, you have to create some translate.php file in those folders resources/lang/en and resources/lang/en
For example:
File resources/lang/en/translate.php should contain this array
return [
'success_message' => 'Message sent successfully!',
];
File:
resources/lang/ru/translate.php should contain this array
return [
'success_message' => 'Сообщение успешно отправлено!',
];
For example:
return response()->json(['success'=> __('translate.success_message') ]);
To get some translated string, use dot notation for this helper;
Laravel localization helper

Laravel AJAX Form 405 Error

I'm receiving this error when attempting to submit via AJAX. When not using AJAX, the form submits just fine to it's specified url. I've read this error can happen because the form is trying to submit in the browser along with the AJAX request. I've tried using onsubmit="event.preventDefault()".
ROUTE:
Route::post('/post/{id}', [
'uses' => '\App\Http\Controllers\PostController#postMessage',
'as' => 'post.message',
'middleware' => ['auth'],
]);
FORM:
<form id="post" role="form" action="{{ route('post.message', ['id' => $user->id]) }}" onsubmit="event.preventDefault()">
<div class="feed-post form-group{{ $errors->has('post') ? ' has-error' : ''}}">
<textarea class="form-control feed-post-input" rows="2" id="postbody" name="post" placeholder="What's up?"></textarea>
<div class="btn-bar">
<!-- <button type="button" class="btn btn-default btn-img btn-post" title="Attach an image"><span class="glyphicon glyphicon-picture"></span></button> -->
<!-- <input type="file" id="img-upload" style="display:none"/> -->
<button class="btn btn-default btn-post" title="Post your message"><span class="glyphicon glyphicon-ok"></span></button>
</div>
#if ($errors->has('post'))
<span class="help-block">{{ $errors->first('post') }}</span>
#endif
</div>
<input type="hidden" name="_token" value="{{ CSRF_token() }}">
</form>
CONTROLLER:
public function postMessage(Request $request, $id)
{
$this->validate($request, [
'post' => 'required|max:1000',
]);
if(Request::ajax()){
Auth::user()->posts()->create([
'body' => $request->input('post'),
'profile_id' => $id
]);
}
}
JS:
$('#post').submit(function(){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
var postRoute = '/post/'+profileId;
var dataString = "body="+body+"&profile_Id="+profileId;
$.ajax({
type: "POST",
url: postRoute,
data: dataString,
success: function(data){
console.log(data);
}
});
});
try this, remove
onsubmit="....." attribute from form
and update your submit method like this
$('#post').submit(function(event){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
var postRoute = '/post/'+profileId;
var dataString = "body="+body+"&profile_Id="+profileId;
$.ajax({
type: "POST",
url: postRoute,
data: dataString,
success: function(data){
console.log(data);
}
});
//this will prevent your default form submit
event.preventDefault();
});
I hope this will work for you

Wordpress AJAX Login

I am trying to build a custom wordpress ajax login form but I can't get it sorted. Here is the codes I use:
HTML:
<form class="well form-inline" id="login">
<div class="rowmargin">
<h4>Login</h4>
</div>
<div class="rowmargin">
<input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
<input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
</div>
<a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#loginButton").click(function() {
var username = $('#loginUsername').val();
var password = $('#loginPassword').val();
var rememberme = "forever";
var redirect = '<?php bloginfo('url'); ?>';
var data = {
user_login: username,
user_password: password,
remember: rememberme,
redirect_to: redirect
}
$.ajax({
url: '<?php bloginfo('url'); ?>/wp-login.php',
data: data,
type: 'GET',
dataType: 'jsonp',
success: function( result ) {
if (result.success==1) {
alert("Ok!");
} else {
alert("Not Ok!");
}
}
});
});
});
</script> <!-- Login Script --->
Can someone tell me what am I doing wrong here?
WordPress: Simple Ajax Login Form
<form id="login" action="login" method="post">
<h1>Site Login</h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username">
<label for="password">Password</label>
<input id="password" type="password" name="password">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<input class="submit_button" type="submit" value="Login" name="submit">
<a class="close" href="">(close)</a>
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
--
<?php
//add this within functions.php
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
Create a file ajax-login-script.js within theme's directory and paste this js
jQuery(document).ready(function($) {
// Show the login dialog box on click
$('a#show_login').on('click', function(e){
$('body').prepend('<div class="login_overlay"></div>');
$('form#login').fadeIn(500);
$('div.login_overlay, form#login a.close').on('click', function(){
$('div.login_overlay').remove();
$('form#login').hide();
});
e.preventDefault();
});
// Perform AJAX login on form submit
$('form#login').on('submit', function(e){
$('form#login p.status').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': $('form#login #username').val(),
'password': $('form#login #password').val(),
'security': $('form#login #security').val() },
success: function(data){
$('form#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
You would need to use wp function for login.
http://codex.wordpress.org/Function_Reference/wp_signon
Then use ajax to access this function to log in. You could write a log in function in functions.php
Click below to see how to use ajax in wordpress.
http://wpmu.org/how-to-use-ajax-with-php-on-your-wp-site-without-a-plugin/
<form class="well form-inline" id="login">
<div id="message"></div>
<div id="loading" style="display:none;"></div>
<div class="rowmargin">
<h4>Login</h4>
</div>
<div class="rowmargin">
<input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
<input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
</div>
<a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>
jQuery(document).ready(function(){
jQuery('#loading').hide();
jQuery("#loginButton").click(function() {
jQuery('#message').hide().html('');
jQuery('#loading').hide();
var input_data = jQuery('#login').serialize();
var logUser = jQuery('#loginUsername').val();
var logPass = jQuery('#loginPassword').val();
if(logUser == '' && logPass != ''){ jQuery('#message').show().html('Your Username is empty!'); return false; }
if(logPass == '' && logUser != ''){ jQuery('#message').show().html('Your Password is empty!'); return false; }
if(logUser == '' && logPass == ''){ jQuery('#message').show().html('Your Username and Password is empty!'); return false; }
jQuery('#loading').show();
jQuery.ajax({
type: "POST",
url: "<?php echo site_url('wp-login.php','login_post'); ?>",
data: input_data,
success: function(msg) {
// login success. redirect users to some page.
jQuery(location).attr('href', '<?php echo home_url( '/thank-you/' ); ?>');
},
error: function(msg) {
// login error.
jQuery('#message').show();
jQuery('#message').html("<?php _e('Your login is not correct. Please try again.'); ?>");
jQuery('#loading').hide();
}
});
return false;
});
});
All AJAX-requests in WordPress must go though wp-admin/admin-ajax.php. wp-login.php won't respond.
http://codex.wordpress.org/Class_Reference/WP_Ajax_Response
There is a set of actions available but none of them comes close to a login-method. You could register your own actions though and handle the login process yourself if you know what you are doing.
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add_action('wp_ajax_my_login_action','my_action');
add_action('wp_ajax_nopriv_my_login_action','my_action');
function my_action(){
$userdata = array(
'user_login' => $_POST['user_login'],
'user_password' => $_POST['user_password']
);
$user = wp_signon($userdata);
$response = array();
if ( is_wp_error( $user)) {
$response = array('status'=>'fail', 'msg' => $user->get_error_message() );
}
else{
$response = array('status'=>'pass');
}
echo json_encode($response);
die;
}
add_shortcode('login','loginfunction');
function loginfunction()
{
if( is_user_logged_in() ){
echo 'logout';
}
?>
<center>Login Form:</center>
<form action="" method="post" id="login">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control form-control-sm" id="user_login" aria-describedby="emailHelp" name="user_login">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control form-control-sm" id="user_password" aria-describedby="emailHelp" name="user_password">
</div>
<input type="hidden" name="action" value="my_login_action">
<button type="submit" class="btn btn-primary btn-block">log in</button>
<div class="sign-up">
Don't have an account? Create One
</div>
</form>
<script>
var ajax_url= '<?php echo admin_url('admin-ajax.php');?>';
jQuery(document).ready(function($){
$("#login").submit(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url: ajax_url,
data:{
action:'my_login_action',
user_login:$('input[name="user_login"]').val(),
user_password:$('input[name="user_password"]').val()
}
}).done(function(response){
let result = JSON.parse(response);
if(result.status=='pass')
{
window.location.href='http://localhost/check_wp/';
}
else{
// alert(result.msg);
alert('Sorry Password is worrng');
}
})
});
});
</script>
<?php
}

Resources