How to update database with AJAX & Laravel 5.2? - javascript

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

Related

Laravel SortableJS AJAX - How to rearrange order

I just implemented SortableJS in my Laravel project and want to rearrange the order of some elements. I have a list of "Blocks" which all have a database field of "Order" which is an integer. I show these blocks in descending order based on the value of the "Order" field.
Now I want to update these values with SortableJS using Ajax. How can I accomplish this?
Currently, I have a simple list
<div class="block-order-list">
#foreach($blocks as $block)
<div class="list-group-item"><i class="far fa-arrows handle mr-3"></i> {{$block->name}}</div>
#endforeach
</div>
And call an Ajax request like so:
$('.block-order-list').sortable({
animation: 150,
handle: '.handle',
store: {
set: function (sortable) {
let order = sortable.toArray();
console.log(order);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ route('change_order', ['url', $page->url]) }}',
type: 'POST',
data: order,
success: function(data){
console.log(data)
}
})
}
}
});
To my PageController which contains
public function changeOrder($data)
{
return $data;
}
The request now only returns a string that says url which I find odd. In the url of the ajax request, I give a parameter called URL which I need to find the blocks attached to this specific page. My blocks database table looks like this
How can I accomplish this?
I guess you must use ID in your HTML list :
<div class="block-order-list">
#foreach($blocks as $block)
<div class="list-group-item" data-id="{{ $block->id }}>
<i class="far fa-arrows handle mr-3"></i> {{ $block->name }}
</div>
#endforeach
</div>
Then in your JS, build an array with ID => order :
let order = {};
$('.list-group-item').each(function() {
order[$(this).data('id')] = $(this).index();
});
Then in your ajax call :
$.ajax({
url: '{{ route('change_order', ['url', $page->url]) }}',
type: 'POST',
data: {order: order},
success: function(data){
console.log(data)
}
})
And in your controller :
public function changeOrder(Request $request)
{
foreach($request->get('order') as $id => $order) {
Block::find($id)->update(['order' => $order]);
}
}

Problems with Ajax-request via Laravel

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

Laravel & Ajax - Insert data into table without refreshing

First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.

Ajax upload not working codeigniter

I am using codeigniter 3.1 . I want to post upload data using ajax.
Ajax upload file not working. But when i post the simple form without ajax, it working fine.
I don't know why but no error in console.
HTML
<?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?>
<input type="file" name="userfile" value="">
<input type="submit" value="Submit" />
<?php echo form_close() ?>
JAVASCRIPT
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this)
});
});
CONTROLLERS
public function post()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE
));
$this->upload->do_upload('userfile');
$data = $this->upload->data();
$image_file = $data['file_name'];
}
Another approach to this would be passing to PHP the file encoded in base64:
get the selected file from #userfile field using $('#userfile').prop('files')[0];
transform the contents of that file into a base64 encoded string using FileReader.readAsDataURL(). We're going to call this content; Here's a similar question showing how to do and expanding the answer & possibilities;
send the AJAX passing both the filename and content strings;
now on CI, fetch the POST data;
base64_decode() the content;
fwrite() the result into a file using the filename.
That way also you could avoid POSTing all form fields.
try this..
Post data using FormData() formdata post file also.
To get all your form inputs, including the type="file" you need to use FormData object.
$('#post').on('click', function (e) {
var file_data = $("#userfile").prop("files")[0];
var form_data = new FormData();
form_data.append("userfile", file_data)
$.ajax({
url: window.location.href+'/post',
type: 'POST',
data: form_data,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
For more...https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
One of the issues is that file uploading uses a different mechanism than the other form <input> types. That is why $this->input->post("userfile") isn't getting the job done for you. Other answers have suggested using javascript's FormData and this one does too.
HTML
A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit".... Doing so makes it a lot easier for the javascript to use the FormData object.
FormData documentation
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-2.2.2.js"></script>
<title>Upload Test</title>
</head>
<body>
<?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
<input type="file" name="userfile">
<p>
<input type="submit" value="Upload">
</p>
<?php echo form_close() ?>
<div id="message"></div>
<script>
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
</script>
</body>
</html>
JAVASCRIPT
Use FormData to capture the fields.
Note that instead of handling the button click we handle the submit event.
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
//uncomment the next line to log the returned data in the javascript console
// console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
CONTROLLER
I've added some code that "reports" results to ajax and will display it on the upload page.
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(['form', 'url']);
}
public function index()
{
$this->load->view('upload_v');
}
public function post()
{
$this->load->library("upload");
$this->upload->initialize(array(
"upload_path" => './uploads/',
'allowed_types' => 'gif|jpg|png|doc|txt',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$successful = $this->upload->do_upload('userfile');
if($successful)
{
$data = $this->upload->data();
$image_file = $data['file_name'];
$msg = "<p>File: {$image_file}</p>";
$this->data_models->update($this->data->INFO, array("image" => $image_file));
} else {
$msg = $this->upload->display_errors();
}
echo json_encode(['result' => $successful, 'message' => $msg]);
}
}
This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.
I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.
Controller
public function upload()
{
$this->load->library('upload');
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']))
{
if ($_FILES['myfile']['error'] != 4)
{
// Image file configurations
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->upload->initialize($config);
$this->upload->do_upload('myfile');
}
}
}
View
<form id="myform" action="<?php base_url('controller/method'); ?>" method="post">
<input type="file" name="myfile">
("#myform").submit(function(evt){
evt.preventDefault();
var url = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
},
error: function (error) {
console.log(error);
}
}); // End: $.ajax()
}); // End: submit()
Let me know if any query
you need to submit the form not on click but on submit ... give the form an id and then on submit put ajax
HTML
<?php $attributes = array('id' => 'post'); ?>
<?php echo form_open_multipart(site_url("upload/post",$attributes), ?>
<input type="file" id="userfile" name="userfile" value="">
<button id="post">Submit</button>
<?php echo form_close() ?>
JAVASCRIPT
$('#post').on('submit', function () {
var formData = new FormData();
formData.append("userfile",$("#userfile")[0].files[0]);
$.ajax({
url: window.location.href+'/post',
type: "POST",
data: formData
});
CONTROLLERS
public function post()
{
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$data = $this->upload->data();
$image_file = $data['file_name'];
$this->data_models->update($this->data->INFO, array(
"image" => $image_file
)
);
}

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