Post Updated Value Using Eloquent - php

I am learning AngularJS on Laravel, and I am making a simple app. So far the app displays rows from the DB in either a completed area, or a not completed area. If a user clicks the item, it moves to the opposite area.
$scope.move = function(item) {
item.has_item = !item.has_item;
};
The above moves the item on click, however for persistence I add:
$scope.move = function(item) {
var newState = !item.completed;
$http.post('/items', item).success(function() {
item.completed = newState;
});
};
Now, I just need a route to accept this post and insert the updated value of completed to the DB.
I've tried:
Route::post('items', function()
{
$completed = Input::get('completed');
return $completed->push();
});
However, I have had no luck. What do I need to do to insert the value into the DB?

$scope.move = function(item) {
item.has_skill = !item.has_skill;
$http.post('/items', item).success(function(data) {
item = data;
});
};
//in controller
$http.get('/items').success(function(data) {
$scope.items = data;
});
<ul>
<li ng-repeat="item in items" ng-click="move(item)">{{item.skill_name}}</li>
</ul>
Route::post('items', function() {
$id = Input::get('id');
$item = Skill::find($id);
$item->has_skill = Input::get('has_skill');
$item->save();
return Response::json($item);
});
Route::get('items', function() {
return Response::json(Skill::all());
});
http://jsbin.com/bavawiko/1/edit

Related

How can I add a confirmation to a delete action made through Jquery?

I have a function in JQuery that combined with PHP and SQL deletes rows from a table, deleting them from the database.
When I click on the delete button, the rows are instantly deleted, however, I'd like to add another level of confirmation that asks if you really want to delete it.
Section that deletes the rows by referring the function
$userObj = mysqli_query($conn , 'SELECT * FROM `shifts`');
if(isset($_POST['data'])){
$dataArr = $_POST['data'] ;
foreach($dataArr as $id){
mysqli_query($conn , "DELETE FROM shifts where id='$id'");
}
echo 'record deleted successfully';
}
JQuery function
<script>
$(document).ready(function(){
$('#checkAll').click(function(){
if(this.checked){
$('.checkbox').each(function(){
this.checked = true;
});
}else{
$('.checkbox').each(function(){
this.checked = false;
});
}
});
$('#delete').click(function(){
var dataArr = new Array();
if($('input:checkbox:checked').length > 0){
$('input:checkbox:checked').each(function(){
dataArr.push($(this).attr('id'));
$(this).closest('tr').remove();
});
sendResponse(dataArr)
}else{
alert('No record selected ');
}
});
function sendResponse(dataArr){
$.ajax({
type : 'post',
url : 'includes/dbh.inc.php',
data : {'data' : dataArr},
success : function(response){
alert(response);
},
error : function(errResponse){
alert(errResponse);
}
});
}
});
</script>
Javascript has the confirm function that will return a boolean based on the user's selection of yes or no. You can use this to make the user confirm they want to delete the records inside of your click function.
$('#delete').click(function(){
if (confirm("Are you sure you want to delete this?")) {
var dataArr = new Array();
if($('input:checkbox:checked').length > 0){
$('input:checkbox:checked').each(function(){
dataArr.push($(this).attr('id'));
$(this).closest('tr').remove();
});
sendResponse(dataArr)
}else{
alert('No record selected ');
}
}
});

Jquery click value check not working

I have a function that on click add/removes stuff from a SQL database.
I do a condition to check if it is refering to an add or remove and execute the code.
the add function works perfectly, but the remove not and its the same code, am i missing something obvious? And is this the best way to do this?
jquery:
//add card from list
$("#listcards a").click(function() {
if($(this).attr('add').length > 1) {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
//remove card from list
$("#listcards a").click(function() {
if($(this).attr('rem').length > 1) {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
html code:
<form id="listcards" method="post">
<input type='hidden' id='lcard' name='lcard' value=''>
<div>
bla bla -> imagem no + ? ou por algum efeito css+ | -<br>
coiso coiso + | -<br>
</div>
</form>
Do i also need to be in a form for the POST or a div would work too?
You've got two click handlers for the same elements, which could be causing a problem. You don't need to run both sets of code for each <a> element. Instead give the elements a class to show exactly what they do, and then limit your selectors to those elements
HTML:
+ | <a href="" class="remove" rem="bla bla">
Script:
$("#listcards a.add").click(function() {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
});
return false;
});
//remove card from list
$("#listcards a.remove").click(function() {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
});
You can use it like thisi will give only remove functionality. And oif possible add ajax.
$("#listcards .rem").click(function() {
var value = $(this).text();
if($(this).length()>1) {
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}});
Suppose you don't have any card when you're loading this page 1st time. Then you click add new & a new card get's added to your html.
Now for this newly added card, the "remove" method doesn't get bind as that was loaded on page load (when this new card element was not present). Hence your remove method is not working for newly added cards.
So to make it work, you need to bing the remove method on new cards too. You can do that by keeping you remove part in a js function which you would call in "add" part after putting new card into html.
function removeCard(){
// first unbind the click event for all cards if any & then bind it
$("#listcards a").off('click');
//remove card from list
$("#listcards a").click(function() {
if($(this).attr('rem').length > 1) {
var value = $(this).attr('rem');
$.post('searchc.php',{rem:value}, function(data){
$("#add_result").html(data);
});
return false;
}
});
}
And you add part should be like this:
//add card from list
$("#listcards a").click(function() {
if($(this).attr('add').length > 1) {
var value = $(this).attr('add');
$.post('searchc.php',{add:value}, function(data){
$("#add_result").html(data);
removeCard(); // adding remove method here
});
return false;
}
});
Follow up your code,
$("#listcards a").click(function() {
var action = $(this).attr("add") ? "add" : "rem";
var value;
if(action == "add")
value = $(this).attr('add');
if(action == "rem")
value = $(this).attr('rem');
var param = {};
param[action] = value;
$.post('searchc.php',param, function(data){
$("#add_result").html(data);
});
});
Use onclick function to do this
It can help you out
+
-<br>
function addthis(addthis) {
if(addthis.length > 1) {
alert(addthis);
// $.post('searchc.php',{add:addthis}, function(data){
// $("#add_result").html(data);
// });
return false;
}
}
function removethis(remthis) {
if(remthis.length > 1) {
alert(remthis);
// $.post('searchc.php',{reb:remthis}, function(data){
// $("#add_result").html(data);
// });
return false;
}
}

Laravel jQuery - Pagination and product filters, pagination URLs

I'm having some conflicting issues with my Laravel setup, specifically with the pagination and product filters.
Both pagination and product filters is being handled via jQuery so the page doesn't completely refresh.
This is my jQuery pagination code, working with the standard Laravel ->paginate functionality.
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
var page_number = $(this).attr('href').split('page=')[1];
getProducts(page_number);
window.history.pushState("", "", url);
});
function getProducts(page_number) {
$.ajax({
url : '?page=' + page_number
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
This works great, the issue is when we filter the products, and then try and go to another page on the filtered results.
Right after filtering, the paginate links are correct for example /devices/filter?filter=1&page2, however on clicking this the page loads all devices without the filter, even though if I copy that url and load that page, it succesfully goes to page 2 with the filters included.
Then the paginate URL's are completely ignoring the filter afterwards, and is /devices?&page=2. I figured it must be to do with me rendering and appending the paginate links in the view, but am unsure what I am doing wrong:
{!! $devices->appends(Input::all())->render() !!}
This is my controller:
public function devicesByFilter(Request $request) {
$type = 'devices';
$types = Input::get('types');
$devices = Device::where('type', '=', $type)->where('approved', '=', 1);
if(!empty($types)) {
$url = 'filter';
$check = 0;
foreach($types as $deviceType) {
if($check == 0) {
$devices = $devices->where('device_type', 'LIKE', $deviceType);
} else {
$devices = $devices->orWhere('device_type', 'LIKE', $deviceType);
}
$url = $url.'&types%5B%5D='.$deviceType;
$check++;
}
}
$devices = $devices->orderBy('match_order', 'asc')->paginate(10);
$devices->setPath('filter');
if ($request->ajax()) {
return view('devices.ajax.loadfilter', ['devices' => $devices, 'type' => $type, 'types' => $types])->render();
}
return View::make('devices.all', compact('devices', 'type'));
}
And this is my filter jQuery code:
$(document).ready(function () {
var types = [];
// Listen for 'change' event, so this triggers when the user clicks on the checkboxes labels
$('input[name="type[]"]').on('change', function (e) {
e.preventDefault();
types = []; // reset
if ( document.location.href.indexOf('filter') > -1 ) {
var url = '../devices/filter?type=device';
} else {
var url = 'devices/filter?type=device';
}
$('input[name="type[]"]:checked').each(function()
{
types.push($(this).val());
url = url+'&types%5B%5D='+$(this).val();
});
if ( document.location.href.indexOf('filter') > -1 ) {
$.get('../devices/filter', {type: 'devices', types: types}, function(markup)
{
$('.devices-holder').html(markup);
});
} else {
$.get('devices/filter', {type: 'devices', types: types}, function(markup)
{
$('.devices-holder').html(markup);
});
}
window.history.pushState("", "", url);
});
});
So at a poor attempt to clarify:
Pagination jQuery works perfect
Filtering works perfect
Trying to go another page after filtering displays all devices not just the filtered ones, even though the URL is correct and if I load this URL again on another tab, it has the right results.
After trying to go to another page of filtered results, the pagination links are missing the append input.
It's very difficult to debug this from here, anyone who can point in the right direction or something to try/test would be great.
Fixed it by changing
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
var page_number = $(this).attr('href').split('page=')[1];
getProducts(page_number);
window.history.pushState("", "", url);
});
function getProducts(page_number) {
$.ajax({
url : '?page=' + page_number
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
to
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
getProducts(url);
window.history.pushState("", "", url);
});
function getProducts(url) {
$.ajax({
url : url
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});

Using Custom Javascript and pHp to send email to myself when a user clicks on an input button but only works on Chrome, IE, and Micorosft Edge

So I am using jQuery and pHp together to send an email to myself whenever a user clicks on the update button of their Ultimate Member form. However, the email only sends when a user is using Chrome, IE, and Microsoft Edge. When using Safari and Firefox, it doesn't work. I am using a click event listener to send JSON to my pHp file. The JSON was originally an object that was created by a function that checks for the differences between two different objects. These objects were created using DOM traversal. In that pHp file is a mail() function that sends me the aforementioned JSON to my email. I've tried replicating the process on a test site and noticed that when I didnt add the jQuery that comes before my click listener, emails do indeed get sent from Safari and Firefox. However, if I add the jQuery code and THEN remove it and test again it won't send! It's as if my server gets permanently rejected. Here is my JS code:
(function($){
$(document).ready(function(){
console.log('mailajax is enqueued, showing on firefox');
var ogArray = new Array(),
newArray = new Array(),
dropOgArray = new Array(),
dropNewArray = new Array(),
difference,
username = $('.um-name').find('a').attr('title');
function diffObject(a, b) {
return Object.keys(a).reduce(function(map, k) {
if (a[k] !== b[k]) map[k] = b[k];
return map;
}, {});
}
$('input.um-form-field').each(function() {
var $key = $(this).closest('.um-field').find('label').text();
var $value = $(this).val();
ogArray[$key] = $value;
});
console.log(ogArray);
setTimeout(function(){
$('span.select2-chosen').each(function() {
var $key = $(this).closest('.um-field').find('label').text();
var $value = $(this).text();
// console.log($value);
dropOgArray[$key] = $value;
});
console.log(dropOgArray);
},1000);
$('input.um-form-field').on('keyup', function(){
$('form').find('input.um-form-field').each(function() {
var $key = $(this).closest('.um-field').find('label').text();
var $value = $(this).val();
newArray[$key] = $value;
});
console.log(newArray);
console.log(diffObject(ogArray, newArray));
difference = diffObject(ogArray, newArray);
});
$('select.um-form-field').on('change', function(){
setTimeout(function(){
$('form').find('span.select2-chosen').each(function() {
var $key = $(this).closest('.um-field').find('label').text();
var $value = $(this).text();
dropNewArray[$key] = $value;
});
console.log(diffObject(dropOgArray, dropNewArray));
dropDifference = diffObject(dropOgArray, dropNewArray);
}, 1000);
});
$('.um-profile-body .um-button').on('click', function(e) {
$('form').on('submit', function(){
console.log('form was sent successfully');
var ajaxurl = 'http://www.reformeducators.org/wp-content/themes/NATE/admin-ajax.php';
stringDifference = JSON.stringify(difference);
stringDropDifference = JSON.stringify(dropDifference);
stringUsername = String(username);
$.post(ajaxurl, {'Name': stringUsername, 'Changes Made': stringDifference, 'Drop Down Menu Changes': stringDropDifference});
});
});
});
})(jQuery);
And here is my pHp code:
<?php
$message = "User Information has been changed\r\n";
$message .= print_r($_POST, true);
$to = "testing#domain.com";
$subject = "User information has been changed!";
$headers = "From: ";
mail($to, $subject, $message, $headers);
?>
I think this might be a server issue, but if anyone has any experience doing something like this, I would really appreciate some feedback or help.
So turns out that on Safari and Firefox, the page would refresh before the email got sent out. As a workaround I just created another button that the user has to click on before clicking on the actual button that updates their profile information. The click event handler on that first button is being used to send out the information to the php file now. It solved the problem and now I'm getting emails no matter what browser the user is updating their profile from!
Heres's the javascript:
(function($){
$(document).ready(function(){
// console.log('mailajax is enqueued, showing on firefox');
setTimeout(function(){
if($('html').hasClass('user-section')){
// console.log('this is a user page');
$('input.um-button').hide();
$('.um-profile .um-col-alt .um-left.um-half').prepend('<a id="custom-update-btn">Approve Changes</a>');
}
var ogArray = new Array(),
newArray = new Array(),
dropOgArray = new Array(),
dropNewArray = new Array(),
difference,
username = String($('.um-name').find('a').attr('title'));
function diffObject(a, b) {
return Object.keys(a).reduce(function(map, k) {
if (a[k] !== b[k]) map[k] = b[k];
return map;
}, {});
}
$('input.um-form-field').each(function() {
var $key = $(this).closest('.um-field').find('label').text(),
$value = $(this).val();
ogArray[$key] = $value;
});
$('span.select2-chosen').each(function() {
var $key = $(this).closest('.um-field').find('label').text(),
$value = $(this).text();
dropOgArray[$key] = $value;
});
$('input.um-form-field').on('keyup', function(){
$('form').find('input.um-form-field').each(function() {
var $key = $(this).closest('.um-field').find('label').text(),
$value = $(this).val();
newArray[$key] = $value;
});
});
$('select.um-form-field').on('change', function(){
setTimeout(function(){
$('form').find('span.select2-chosen').each(function() {
var $key = $(this).closest('.um-field').find('label').text(),
$value = $(this).text();
dropNewArray[$key] = $value;
});
// console.log(diffObject(dropOgArray, dropNewArray));
}, 1000);
});
$('a#custom-update-btn').on('click', function(e){
// console.log('update btn has been clicked on');
var ajaxurl = 'http://www.reformeducators.org/wp-content/themes/NATE/admin-ajax.php',
stringDifference = JSON.stringify(diffObject(ogArray, newArray)),
stringDropDifference = JSON.stringify(diffObject(dropOgArray, dropNewArray));
$.post(ajaxurl, { 'Name': username, 'Changes Made': stringDifference, 'Drop Menu Changes': stringDropDifference});
$('a#custom-update-btn').hide();
$('.um-profile-body .um-button').show();
});
}, 1000);
});
})(jQuery);

search function in ecommerce in laravel 5

I am creating the search functionality in my laravel 5 ecommerce web application.
I want the user to move the cursor with the arrow keys on the search results, but I am failing to achieve this.
Here's the controller:
public function searchProduct(Request $request)
{
$productName = $request->input('name');
if($productName !== '')
{
$products = Product::where('name', 'LIKE', '%' . $productName . '%')->where('display', 'Enabled')->get();
return view('partials.search', compact('products'));
}
return false;
}
The search results:
#foreach($products as $product)
<li>
<a href="{{ url('/store/'.$product->code .'/'.Safeurl::make($product->name)) }}" class="link_scheme_color_main">
{{ $product->name }}
</a>
</li>
#endforeach
And the AJAX:
$('.searchProduct').keydown(function(e) {
var name = $(this).val();
var inputData = $('.formSearchProduct').serialize();
var prodList = $('.showProds');
var countList = prodList.find('ul li').length;
var prd = prodList.find('ul li');
if(name.length === 0) {
prodList.hide();
} else {
$.ajax({
url: '{{ url('/store/product/search') }}',
type: "POST",
data: inputData
})
.done(function(m) {
if (m) {
prodList.show();
prodList.find('ul.searchedProducts').html(m);
prodList.find('ul li').first().addClass('activeProduct');
} else {
prodList.hide();
}
});
}
});
The css:
.activeProduct {background: #ccc !important;}
I have made this application live. You can check it here. The application is still in the development stage and not in production.
What I want to achieve is:
When the user searches for the product, he/she can use the up and down arrow keys to navigate the search results, and on click of any of the results, he/she should go to the product page.
When the user searches and removes the search keyword(s), all the products are shown, I don't want that.
UPDATE 1:
I have added this code and it seems there is a bug, where I don't know. The bug is that I can only move to the second list item when pressing the down arrow key and at the very next second, it moves back to the first list item.
$('.searchProduct').keydown(function(e) {
var prodList = $('.showProds');
var countList = prodList.find('ul li').length;
var prd = prodList.find('ul li');
var active = prodList.find('ul li.activeProduct');
console.log(e.keyCode);
if (e.which === 40) {
var next = active.removeClass('activeProduct').next('li');
next = next.length > 0 ? next : $('li:eq(0)');
next.addClass('activeProduct');
}
});
UPDATE 2:
I have got it working to a certain extent. I have removed the code of update 1 and added the below code to done() method.
if (m) {
prodList.show();
prodList.find('ul.searchedProducts').html(m);
prodList.find('ul li').first().addClass('activeProduct');
if(e.keyCode == 40) {
prodList.find('ul li').prev().removeClass('activeProduct');
prodList.find('ul li').next().first().addClass('activeProduct').focus();
}
} else {
prodList.hide();
}
But this moves only to the second list item on every time the down arrow key is pressed. You can have a look at the link that I provided above.
Kindly help me out with this. Thanks.

Categories