Multi AJAX Request in Laravel - ajax

Goodtime
I write this code but when i send for database only submit one query "sad" !
çi use
$request->has('happy') or ... no working
Can anyone help me?
for sample
**$request->has('happy') ** submit 'happy' or **$request->has('love') ** submit 'love'
I'm tired of searching
thanks to stackoverflow and members
<form method="post">
{{csrf_field()}}
<button type="submit" value="happy" id="happy" class="border-0 btn-submit">
<img src="/assets/images/reactions/happy.png" />
</button>
<button type="submit" value="angry" id="angry" class="border-0 btn-submit">
<img src="/assets/images/reactions/angry.png" />
</button>
<button type="submit" value="ill" id="ill" class="border-0 btn-submit">
<img src="/assets/images/reactions/ill.png" />
</button>
<button type="submit" value="love" id="love" class="border-0 btn-submit">
<img src="/assets/images/reactions/in-love.png" />
</button>
<button type="submit" value="quiet" id="quiet" class="border-0 btn-submit">
<img src="/assets/images/reactions/quiet.png" />
</button>
<button type="submit" value="sad" id="sad" class="border-0 btn-submit">
<img src="/assets/images/reactions/sad.png" />
</button>
<!-- <input type="text" name="studentName" id="studentName" class="form-control" placeholder="please type in your name"> -->
<input type="hidden" value="{{$article->id}}" id="post_id">
<input type="hidden" name="_token" value="{{csrf_token()}}">
</form>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit").click(function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var sad = $("#sad").val();
var quiet = $("#quiet").val();
var love = $("#love").val();
var ill = $("#ill").val();
var angry = $("#angry").val();
var happy = $("#happy").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: {
post_id: post_id,
sad: sad,
quiet: quiet,
love: love,
ill: ill,
angry: angry,
happy: happy
},
success: function(data) {
alert(data.success);
}
});
});
</script>
</div>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Reaction;
use Illuminate\Support\Facades\Auth;
class AjaxController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequest()
{
return view('ajaxRequest');
}
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequestPost(Request $request, Reaction $reaction)
{
$input = $request->all();
\Log::info($input);
if ($request->ajax()) {
if (!Auth::user()) { // Check is user logged in
$must_login = "you must login";
return response()->json(['success' => $must_login]);
} else {
$date = date('Y-m-d');
$user_id = Auth::user()->id;
$output = "Your reaction Submited";
$post_id = $request->input('post_id');
// Checker
$checker = Reaction::select('*')->where([
['post_id', '=', $post_id],
['user_id', '=', $user_id],
['date', '=', $date]
])->first();
if ($checker == null) {
if ($request->has('sad') == true) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'sad',
'date' => $date,
]);
} elseif ($request->has('love')) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'love',
'date' => $date,
]);
} else {
echo "fuck";
}
return response()->json(['success' => $output]);
} else {
return response()->json(['success' => 'You Befor Submited Your Rection']);
}
}
}
}
}

This should work:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("form").on('submit', function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var reaction = $(".btn-submit").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: { post_id, reaction },
success: function(data) {
alert(data);
}
});
});
public function ajaxRequestPost(Request $request)
{
$data = $request->all();
return response()->json($data);
}

Related

I'm trying in laravel to log in with my phone number but it doesn't work

I changed the login by mail to login with phone number in a laravel system, but it does not log in in any way. either it doesn't find it in the database or I'm doing something wrong. I asked chatgpt and searched many forums but still no success. where am i doing wrong?
LoginController
namespace App\Http\Controllers;
use Exception;
use App\Models\User;
use App\Helper\Reply;
use App\Models\Social;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
use App\Events\TwoFactorCodeEvent;
use App\Traits\SocialAuthSettings;
use Froiden\Envato\Traits\AppBoot;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use \Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
use AppBoot, SocialAuthSettings;
protected $redirectTo = 'account/dashboard';
public function checkEmail(LoginRequest $request)
{
exit ;
$user = User::where('mobile', $request->mobile)
->select('id')
->where('status', 'active')
->where('login', 'enable')
->first();
if (is_null($user)) {
throw ValidationException::withMessages([
Fortify::username() => __('messages.invalidOrInactiveAccount'),
]);
}
return response([
'status' => 'success'
]);
}
public function checkCode(Request $request)
{
$request->validate([
'code' => 'required',
]);
$user = User::find($request->user_id);
if($request->code == $user->two_factor_code) {
// Reset codes and expire_at after verification
$user->resetTwoFactorCode();
// Attempt login
Auth::login($user);
return redirect()->route('dashboard');
}
// Reset codes and expire_at after failure
$user->resetTwoFactorCode();
return redirect()->back()->withErrors(['two_factor_code' => __('messages.codeNotMatch')]);
}
public function resendCode(Request $request)
{
$user = User::find($request->user_id);
$user->generateTwoFactorCode();
event(new TwoFactorCodeEvent($user));
return Reply::success(__('messages.codeSent'));
}
public function redirect($provider)
{
$this->setSocailAuthConfigs();
return Socialite::driver($provider)->redirect();
}
public function callback(Request $request, $provider)
{
$this->setSocailAuthConfigs();
try {
try {
if ($provider != 'twitter') {
$data = Socialite::driver($provider)->stateless()->user();
}
else {
$data = Socialite::driver($provider)->user();
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
return redirect()->route('login')->with('message', $errorMessage);
}
$user = User::where(['email' => $data->email, 'status' => 'active', 'login' => 'enable'])->first();
if ($user) {
// User found
DB::beginTransaction();
Social::updateOrCreate(['user_id' => $user->id], [
'social_id' => $data->id,
'social_service' => $provider,
]);
DB::commit();
Auth::login($user, true);
return redirect()->intended($this->redirectPath());
}
else {
return redirect()->route('login')->with(['message' => __('messages.unAuthorisedUser')]);
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
return redirect()->route('login')->with(['message' => $errorMessage]);
}
}
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/login';
}
public function username()
{
return 'mobile';
}
}
Here blade code;
<label for="mobile">#lang('auth.mobile')</label>
<input tabindex="1" type="text" name="mobile"
class="form-control height-50 f-15 light_text" autofocus
placeholder="#lang('auth.mobile')" id="mobile">
<input type="hidden" id="g_recaptcha" name="g_recaptcha">
</div>
#if ($socialAuthSettings->social_auth_enable)
<button type="submit" id="submit-next"
class="btn-primary f-w-500 rounded w-100 height-50 f-18 ">#lang('auth.next') <i
class="fa fa-arrow-right pl-1"></i></button>
#endif
<div id="password-section"
#if ($socialAuthSettings->social_auth_enable) class="d-none" #endif>
<div class="form-group text-left">
<label for="password">#lang('app.password')</label>
<x-forms.input-group>
<input type="password" name="password" id="password"
placeholder="#lang('placeholders.password')" tabindex="3"
class="form-control height-50 f-15 light_text">
<x-slot name="append">
<button type="button" data-toggle="tooltip"
data-original-title="#lang('app.viewPassword')"
class="btn btn-outline-secondary border-grey height-50 toggle-password"><i
class="fa fa-eye"></i></button>
</x-slot>
</x-forms.input-group>
</div>
<div class="forgot_pswd mb-3">
#lang('app.forgotPassword')
</div>
<div class="form-group text-left">
<input id="checkbox-signup" type="checkbox" name="remember">
<label for="checkbox-signup">#lang('app.rememberMe')</label>
</div>
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v2_status == 'active')
<div class="form-group" id="captcha_container"></div>
#endif
#if ($errors->has('g-recaptcha-response'))
<div class="help-block with-errors">{{ $errors->first('g-recaptcha-response') }}
</div>
#endif
<button type="submit" id="submit-login"
class="btn-primary f-w-500 rounded w-100 height-50 f-18">
#lang('app.login') <i class="fa fa-arrow-right pl-1"></i>
</button>
#if ($setting->allow_client_signup)
<a href="{{ route('register') }}"
class="btn-secondary f-w-500 rounded w-100 height-50 f-15 mt-3">
#lang('app.signUpAsClient')
</a>
#endif
</div>
</div>
</div>
</div>
</div>
</section>
</form>
<x-slot name="scripts">
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v2_status == 'active')
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async
defer></script>
<script>
var gcv3;
var onloadCallback = function () {
// Renders the HTML element with id 'captcha_container' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'gcv3'.
gcv3 = grecaptcha.render('captcha_container', {
'sitekey': '{{ $setting->google_recaptcha_v2_site_key }}',
'theme': 'light',
'callback': function (response) {
if (response) {
$('#g_recaptcha').val(response);
}
},
});
};
</script>
#endif
#if ($setting->google_recaptcha_status == 'active' && $setting->google_recaptcha_v3_status == 'active')
<script
src="https://www.google.com/recaptcha/api.js?render={{ $setting->google_recaptcha_v3_site_key }}"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('{{ $setting->google_recaptcha_v3_site_key }}').then(function (token) {
// Add your logic to submit to your backend server here.
$('#g_recaptcha').val(token);
});
});
</script>
#endif
<script>
$(document).ready(function () {
$('#submit-next').click(function () {
const url = "{{ route('check_email') }}";
$.easyAjax({
url: url,
container: '#login-form',
disableButton: true,
buttonSelector: "#submit-next",
type: "POST",
data: $('#login-form').serialize(),
success: function (response) {
if (response.status === 'success') {
$('#submit-next').remove();
$('#password-section').removeClass('d-none');
$("#password").focus();
}
}
})
});
$('#submit-login').click(function () {
const url = "{{ route('login') }}";
$.easyAjax({
url: url,
container: '.login_box',
disableButton: true,
buttonSelector: "#submit-login",
type: "POST",
blockUI: true,
data: $('#login-form').serialize(),
success: function (response) {
if (response.two_factor == false) {
window.location.href = "{{ session()->has('url.intended') ? session()->get('url.intended') : route('dashboard') }}";
} else if (response.two_factor == true) {
window.location.href = "{{ url('two-factor-challenge') }}";
}
}
})
});
#if (session('message'))
Swal.fire({
icon: 'error',
text: '{{ session('message') }}',
showConfirmButton: true,
customClass: {
confirmButton: 'btn btn-primary',
},
showClass: {
popup: 'swal2-noanimation',
backdrop: 'swal2-noanimation'
},
})
#endif
});
</script>
</x-slot>
</x-auth> ```

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

ajax with jquery ui autocomplete

I have created an autosuggestion list using jquery and WordPress function. My autosuggestion working fine. I am giving my code here
Jquery Code
(function ($) {
$(document).ready(function () {
$('#my_ajax').autocomplete({
// minChars: 1,
source: function(request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: devel_ajax.ajaxurl,
data: 'action=my_ajax'+'&name='+request.term,
success: function(data) {
response( $.map( data, function( item ) {
return {
label: item.title,
value: item.title
}
}));
}
});
},
minLength: 3,
});
})(jQuery);
PHP Code
function user_autocomplete($value){
global $wpdb;
$name = $wpdb->esc_like(stripslashes($value));
$users = $wpdb->get_results("SELECT DISTINCT
$wpdb->users.ID
FROM $wpdb->users
WHERE LOWER($wpdb->users.user_login) LIKE LOWER('".$name."%')");
$autocomplete = array();
foreach($users as $key => $user){
$user_info = get_userdata($user->ID);
$firstname = $user_info->first_name;
$lastname = $user_info->last_name;
if(!empty($firstname) || !empty($lastname)){
$username = ucfirst($firstname) . ' '. ucfirst($lastname);
}else{
$username = $user_info->user_login;
}
$email = $user_info->user_login;
$website = $user_info->website;
$autocomplete[$user->ID] = array(
'ID' => $user->ID,
'Name' => $username
'email' => $email
'website' => $website
);
}
return $autocomplete;
}
HTML Code
<form action='' method='POST' role="form" class="bottom-space">
<div class="form-group">
<input id="my_ajax" autofocus="" value="" type="text" name="q" placeholder="my_ajax" style="width:100%;max-width:600px;outline:0" autocomplete="off">
<input id="firstname" name="firstname" type="hidden" value=''>
<input id="lastname" name="lastname" type="hidden" value=''>
<input id="id" name="user_id" type="hidden" value=''>
<input id="email" name="email" type="hidden" value=''>
<input id="website" name="email" type="hidden" value=''>
</div>
<submit type="submit" class="btn btn-default">Submit
Button</submit>
</form>
But the problem is I can not set others hidden input Field. Any kind of help or suggestions highly appreciable.
The code is not tested. But I think this should be work for you. I am giving you some code snippet.
(function ($) {
$(document).ready(function () {
$('#my_ajax').autocomplete({
// minChars: 1,
source: function(request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: devel_ajax.ajaxurl,
data: 'action=my_ajax'+'&name='+request.term,
success: function(data) {
response( $.map( data, function( item ) {
var object = new Object();
object.label = item.Name;
object.value = item.Name;
object.ID = item.ID;
object.email = item.email;
object.website = item.website;
return object
}));
// response( $.map( data, function( item ) {
// return {
// label: item.title,
// value: item.title
// }
// }));
}
});
},
select: function (event, ui) {
$("#my_ajax").val(ui.item.value);
$("#firstname").val(ui.item.value);
$("#id").val(ui.item.ID);
$("#email").val(ui.item.email);
$("#website").val(ui.item.website);
}
});
});
})(jQuery);

How to AJAX work

I am new in AJAX. but I am trying to learn How this is working.
I am using symfony2 with fos user bundle and I want implement AJAX to my login form.
so I was doing this :
login.html.twig
<script>
$('#_submit').click(function(e){
e.preventDefault();
$.ajax({
type : $('form').attr( 'method' ),
url : $('form').attr( 'action' ),
data : $('form').serialize(),
success : function(data, status, object) {
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
window.location.href = data.targetUrl;
}
}
});
</script>
<div id="tab-1" class="login_form">
<form action="{{ path("fos_user_security_check") }}" role="form" method="post">
<label for="username"><strong>User Name / Email Address</strong>
<input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</label>
<label for="password"><strong>Password</strong>
<input type="password" id="password" name="_password" required="required" />
</label>
<label for="password"><strong>Remember Me</strong>
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
</label>
<input type="submit" class="submitBut" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</form>
</div>
And when submit then go this file :-
<?php
namespace XXXX\UserBundle\Handler;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
protected $router;
protected $security;
protected $userManager;
protected $service_container;
public function __construct(RouterInterface $router, SecurityContext $security, $userManager, $service_container)
{
$this->router = $router;
$this->security = $security;
$this->userManager = $userManager;
$this->service_container = $service_container;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
if ($request->isXmlHttpRequest()) {
$result = array('success' => true);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
else {
// Create a flash message with the authentication error message
$request->getSession()->getFlashBag()->set('error', $exception->getMessage());
$url = $this->router->generate('fos_user_security_login');
return new RedirectResponse($url);
}
return new RedirectResponse($this->router->generate('anag_new'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
$translator = new Translator('fr_FR');
//$result = array(
// 'success' => false,
// 'function' => 'onAuthenticationFailure',
// 'error' => true,
// 'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
//);
$result = array('success' => false);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
When submit the form then show me in login_check url:
{"success":false}
But I want when result false then return same form where I was trying to login(I mean same popup div)?
What's wrong my code ajax or action return ?
Or I am return correct ?
window.location will reload the entire page. That's not the desired result I suppose since you are using AJAX ( the hole point of AJAX is to not reload the page) instead you could display an error message if the login is not successful.
I suggest you add an error div in your html form
<div class='error' style="display:none" > ooups an erro occured </div>
and then in the ajax call just show it or add a significant message error :
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
$('.error').show();
}

Resources