Problems with Ajax-request via Laravel - javascript

I have a big problem with Ajax-request via Laravel. I can't understand why it is not Ajax. All resources here.
It is my Ajax-request.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var nickname = "<?php echo $name_user; ?>";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.subscribe').click(function() {
jQuery.ajax({
type: 'post',
url: "{{ route('postSubscribe', '<?php echo $name_user; ?>') }}", //Путь к обработчик
data: {'user_name': nickname},
response: 'text',
success: function(data) {
console.log(data['result']);
},
error: alert('Error');
})
})
</script>
It is my web-routes.
Route::group(['middleware' => 'auth'], function() {
Route::get('/', 'AccountController#redirectToAccountPage');
Route::get('/account', 'AccountController#showAccount')->name('account');
Route::get('/account/settings', 'AccountController#showSettings')->name('settings');
Route::post('/account/settings', 'AccountController#sendSetting');
Route::get('/account/subscribe', 'AccountController#showSubscriberForm')->name('subscriber');
Route::post('/account/subscribe', 'AccountController#findUser')->name('postFindUser');
Route::get('/account/load_image', 'AccountController#showLoadImage')->name('load_image');
Route::post('/account/load_image', 'Photos\LoadPhotoController#loadPhoto');
Route::post('/account/logout', 'AccountController#logout')->name('logout');
Route::post('/user/{user_name}/', 'AccountController#subscribe')->name('postSubscribe');
Route::get('/admin', 'AccountController#showAdminPanel');
});
It's my main request.
public function subscribe(Request $request, $name_user) {
if($request->ajax()) {
$query = 'SELECT id FROM subscriptions WHERE id_subscriber = ? AND id_subscribtion = ?';
$queryFindAnother = 'SELECT id From new_users WHERE nickname = ?';
$idAnotherUser = DB::select($queryFindAnother, [$name_user]);
if(!DB::select($query, [Auth::user()->id, $idAnotherUser[0]->id])) {
$query = 'INSERT INTO subscriptions (id_subscriber, id_subscribtion) VALUES (?, ?)';
dd('Я здесь');
//id_subscriber - тот, кто подписался.
//id_subscribtion - на кого подписан.
DB::insert($query, [Auth::user()->id, $idAnotherUser[0]->id]);
return response()->json([
'result' => '1', //всё прошло успешно, я подписан
]);
}
return back();
}
dd("It's not ajax");
return back();
}
As a result I got the message "It's not Ajax". Help me please!

I think the problem is in your form
Please update your form
<form>
{!! csrf_field() !!}
<button class="subscribe" name="user" type="button">Подписаться.</button>
</form>
Here, you don't need any action or method also does not need any form
because you passing the form data as ajax
and add the type of your button as button, by default its a submit type, so its submitting the form as normally.

Make sure you have imported the Request Facade on top

Related

I tried to pass value from ajax to codeigniter controller using post method but it is returning void

I tried to store ajax value in codeigniter controller variable using post method I used $this->input->post method in the controller but the variable in the controller is not getting the ajax value, the variable is returning as null, help me to find a solution for this error Thanks in advance.
Here is the code:
View:
<button type="button" class="btn btn-info btn-md edit-pdt" data-pid="<?php echo $row->product_id;?>"><i class="fa fa-pencil"></i></button>
Controller:
public function displayprodt()
{
$pid= $this->input->get('pid');
$data = array(
'title' => "Edit Product",
'result' => $this->ProductModel->displayprodt($pid)
);
$this->load->view('header',$data);
$this->load->view('navbar');
$this->load->view('sidebar');
$this->load->view('editproduct',$data);
$this->load->view('footer');
}
JQuery:
$('.edit-pdt').click(function(){
var base_url = $("#base_url").val();
var pid = $(this).attr("data-pid");
alert(pid);
$.ajax({
type: "GET",
url: base_url+"index.php/Product/displayprodt",
data: ({pid: pid}),
success: function(response) {
location.href = base_url+"index.php/product/displayprodt";
}
});
});
Model:
public function displayprodt($pid){
$this->db->select("*");
$this->db->from("todaysdeal_products");
$this->db->where("product_id",$pid);
$query = $this->db->get();
return $query->result();
}
problem is your page redirects whatever returned from first request. please try replacing location.href = base_url+"index.php/product/displayprodt"; with console.log(response); or alert(response);
You are using $this->input->post('pid') then you have to use POST in ajax.
change
1: type: "GET", to type: "POST",
2: data: ({pid: pid}), to data: {pid: pid},
i think you need to create controller to control ajax data i will give you example :
Controller
public function displayprodt()
{
$pid = $this->input->post('pid',true);
$data=array(
'error' =>false,
'title' => 'Edit Product',
'result' => $this->ProductModel->displayprodt($pid),
);
header('Content-Type: application/json');
echo json_encode($data ,JSON_PRETTY_PRINT);
}
Model
public function displayprodt($pid){
$this->db->select("*");
$this->db->from("todaysdeal_products");
$this->db->where("product_id",$pid);
$query = $this->db->get();
return $query->result();
}
Jquery
$('.edit-pdt').click(function(){
var base_url = $("#base_url").val();
var pid = $(this).attr("data-pid");
alert(pid);
$.ajax({
type: "POST",
url: base_url+"index.php/Api/displayprodt",
data: ({pid: pid}),
dataType: "JSON",
success: function(response) {
location.href = base_url+"index.php/product/displayprodt"; // or any url you want redirect.
}
});
});
I hope you find solution :')

Form submission using AJAX in Laravel 5.5

I am trying to submit a form using ajax in Laravel 5.5
The problem is the page is refreshing and not submitting data in the database. I need to store data in the database without refreshing the page.
Here is my code:
Controller
public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}
View
<form id="timeForm" class="form-horizontal form-material" >
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>
Ajax script
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//data:'_token = <php echo csrf_token() ?>',
success: function(data) {
console.log(data); //Please share cosnole data
if (data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg);
}
}
});
}
Router
Route::post('/new_timing_table','Timing_TableControoler#new_timing_table');
You got a typo or a mistake in your script.
jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});
My code is working now after adding beforeSend: function (request) in Ajax script
var getMessage = function(){
var timing_tables_name = $("#timing_tables_name").val();
console.log(timing_tables_name);
$.ajax({
type:'GET',
url:'/new_timing_table', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:
{
timing_tables_name
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-
token']").attr('content'));
},
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
and editing the controller to be simple as this one
public function new_timing_table(Request $request){
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
Thank you all for your help

Not able to display message after submitting form using ajax

I am trying to submit the form using AJAX in CodeIgniter. Values of the form are getting saved in DB but the reply that has been set in the controller is not getting displayed in console.log or alert in AJAX code.
Code of form
<form class="form-signup" id="signup-form" method="post">
<input type="email" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="password" id="password">
<button type="submit" class="btn btn-primary btn-lg btn-signup col-sm-offset-1" id="submit_form">SIGN UP</button>
</form>
Script code
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'json',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});
Controller code
public function register()
{
$data = array(
'email' => $this->input->post('email'),
'password'=>$this->input->post('password')
);
$email = $data['email'];
$password = $data['password'];
$this->db->where('email',$email);
$query = $this->db->get('student');
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
return $final;
}
}
Model code
public function register_user($data1)
{
$success=$insert_data = $this->db->insert('student', $data1);
if($success)
{
$result= "success ";
}
else
{
$result= "register unsuccessful";
return $result;
}
}
As shown in the code there are 3 messages
Email already exists
Success
Register unsuccessful
In AJAX, if I do console.log or alert, I want any 1 of the above 3 messages to get displayed according to the flow.
How to display the reply on front end?
You have to use echo instead of return for success.
Please change it as follows
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
echo $final;
}
and remove that 2 variables initialized together. That is unnecessary. This is fine.
$success = $this->db->insert('student', $data1);
Hope this can help you.
The ajax that you have used has datatype as json. So if you want data to be displayed on front end either encode the reply in json or you need to change or remove the json datatype from your ajax
Please change dataType:'json' to dataType: 'text'
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'text',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});

How to update database with AJAX & Laravel 5.2?

UPDATED QUESTION:
I want to update a database table column with AJAX and Laravel 5.2 framework. I have a button Delier when i will click on that button then it will update a column from Not Shipped to Shipped. I also using sweetAlert plugin for popup styling. I have searched a lot. But i didn't find perfect procedure of it. I have tried this way:
Routes:
Route::get('/winner/status/{id}', ['as' => 'winner.status', 'uses' => 'WinnerController#statusUpdate']);
WinnerController:
public function statusUpdate(Request $request, $id)
{
$winner = Winner::find($id);
$winner->product_stat = "Shipped";
$winner->save();
$request->session()->flash('alert-info', 'Product Status Updated!');
return Redirect::to('admin/winner/detail');
}
Script in View:
$(".action-button").click(function(){
swal({
type : 'warning',
title: 'Submit what you want',
input: 'text',
showCancelButton: false,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
allowOutsideClick: false
}).then(function (text) {
$.ajax({
type: "POST",
url : '',
success: function(data){
swal('Confirmed!','success')
}
});
})
});
Blade:
#foreach($dataQrDetails as $dataQr)
<tr>
<td> {{ $dataQr->product_name }} </td>
<td> {{ $dataQr->product_stat }} </td>
<td> {{ $dataQr->created_at }} </td>
<td> <a class="btn btn-info btn-xs action-button" href="{{route('winner.status',$dataQr->id)}}">Delier</a></td>
</tr>
#endforeach
Blade frontend:
This is updating column but after updated its redirected another page and its showing just popup its not need to submit confirm button of popup. Is there anyway to do this? Please could anyone answer my below question:
What will be the best procedure to using AJAX with Laravel.
What will be route call for update data?
How i define AJAX url?
Many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser
best ways to pass variable in ajax request in laravel]
your route is
Route::get('testUrl/{id}', 'TestController#getAjax');
ajax request
<script>
var Id = <?php echo $id; ?>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl/{id}',
type: 'GET',
data: { id: Id },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_GET['id'];
return $id // any value return as a response
}
What is do here is, when you load the form I'll save the user id in Hidden field and when i submit will pass that to controller as well
In Form
<input type="hidden" name="id" value="{{ $id }}">
In AJAX
$.ajax({
url: "/update-winner",
type:'POST',
data: {_token:_token, id:id, .....},
success: function(data) {
if($.isEmptyObject(data.error)){
swal('Confirmed!',data.success); # or swal('Confirmed!','success')
}else{
swal('error!',data.error); # or swal('error!','Errorrrrr')
}
}
});
In Route
Route::post('update-winner','HomeController#statusUpdate');
In Controller
function statusUpdate()
{
<!-- if need -->
$validator = Validator::make($request->all(), [
/....
]);
if ($validate->fails())
{
return response()->json(['error'=>$validator->errors()->all()]);
}
else
{
$id = $request->input("id");
$winner = Winner::find($id);
$winner->product_stat = "Shipped";
$winner->save();
return response()->json(['success'=>'Added new records.']);
}
}
Edit 01
In delete button add this data-delete="{{ id_fiedld_name}"
and in Ajax you can catch
var id = ($(this).data('delete'));

Ajax search - Laravel

I am trying to create a live search using jquery, ajax and laravel. I also use pjax on the same page, this might be an issue?. Quite simply it should query the database and filter through results as they type.
When using Ajax type:POST I am getting 500 errors in my console. I get zero errors using GET but instead of returning in #foreach it will a full page view (this might be because of pjax).
Where am I going wrong?
Route:
Route::post('retailers/{search}', array(
'as' => 'search-retailers', 'uses' => 'RetailersController#search'));
Controller:
public function search($keyword) {
if(isset($keyword)) {
$data = array('store_listings' => RetailersListings::search($keyword));
return $data;
} else {
return "no results";
}
}
Model:
public static function search($keyword)
{
$finder = DB::table('retailers_listings')
->Where('city', 'LIKE', "%{$keyword}%")
->orWhere('country', 'LIKE', "{$keyword}")
->orderBy('country', 'asc')
->get();
return $finder;
}
View (store.blade.php):
<div id="flash"></div> //loading
<div id="live"> // hide content
<div id="searchword"><span class="searchword"></span></div> //search word
<table class="table">
<tbody>
#foreach($store_listings as $store)
<tr>
<td></td> //echo out all fields eg: {{ $store->name }}
</tr>
#endforeach
</tbody>
</table>
</div>
Form:
<form method="get" action="">
<input type="text" class="search-retailers" id="search" name="search">
</form>
Ajax and JS:
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
var dataString = 'keyword='+ keyword;
if(keyword=='') {
} else {
$.ajax({
type: "GET",
url: "{{ URL::route('search-retailers') }}",
data: dataString,
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
Additional, Here is my controller for pjax, It is important to note I am using the view store.blade.php foreach in for the search and for this store listing.
public function stores($city)
{
$this->layout->header = $city;
$content = View::make('retailers.stores', with(new RetailersService())->RetailersData())
->with('header', $this->layout->header)
->with('store_listings', RetailersListings::stores($city));
if (Request::header('X-PJAX')) {
return $content;
} else {
$this->layout->content = $content;
}
}
Your route is Route::post('retailers/{search}', [...]) and there you go. You pass data to your ajax-call. In GET you get something like url?key=value but using POST the data are added to the request body not to the url.
Knowing this your route is no longer valid since it only looks up for retailers/{search} and not for retailers only (which is the url POST is using).
Well maybe it could help somebody.
As a first problem you are defining the route as POST and then in the ajax request the type GET so it would not work
Also when making POST request Laravel has the csrf check so in order to work, provide it. The js function will be like
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
if(keyword=='') {
} else {
$.ajax({
type: "post",
url: "{{ URL::route('search-retailers') }}",
data: {
'keyword': keywork,
'_token': '{{ csrf_token() }}';
},
dataType: 'html',
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
And you can test your PHP search method doing separate tests for it.

Categories