How to change delete method to post method in ng-admin? - php

I want to change deleteMethod to POST method in ng-admin.
For changing createMethod from POST to PUT method I used:
user.createMethod('put');
I want to delete to post method.
user.deleteMethod('post');
The above is not working. Please help me.

if you want to delete selected items then you can go with batchActions and after that create a directory with the name you want and hit the post request.
.batchActions([
'<batch-approvee type="confirm" selection="selection"></batch-approvee>' ])
directive code:
angular.module('myApp').directive('batchApprovee',['Restangular','$q','notification','$state',function(Restangular, $q, notification, $state){
return {
restrict: 'E',
scope: {
selection: '=',
type: '#'
},
link: function(scope, element, attrs) {
scope.icon = attrs.type == 'accept' ? 'glyphicon-thumbs-up' : 'glyphicon-thumbs-down';
scope.updateStatus = function() {
var cItems = {};
var data = [];
var allConfirmData = scope.selection;
allConfirmData.forEach(function(confirmItem,index){
cItems.id = confirmItem._identifierValue;
cItems.status = 2;
data.push(cItems);
cItems = {};
});
var config = {
headers : {
'Content-Type': 'application/json;'
}
}
notification.getBatchApproval(data,config).then(
function(res){
if(res&&res.data){
alert("Inventory Confirmed");
}
},
function(err){
alert(err);
})
}
},
template: ` <span ng-click="updateStatus()"><span class="glyphicon {{ icon }}" aria-hidden="true"></span> Confirm</span>`
};

Related

Laravel Ajax Pagination: No request

I have some difficulties with my ajax pagination linked to a filter. Here's how it should work. The user can access via a specific page to a form. When clicking the submit button, a raw sql request is made in JS and a POST ajax request is achieved to get the results at the bottom of the page with a pagination menu. This part works. But I have some issues with the pagination menu because the links don't work. For example, by clicking the "page 2" link, nothing happens.
Here are the different parts of my code:
Routes
Route::get('articles/filter', 'ArticleController#filterx');
Route::post('articles/request/ajax/articles/filter', 'ArticleController#filtery');
Route::get('articles/request/ajax/articles/filter', 'ArticleController#filtery');
Controller
ArticleController
public function filterx() { // get filter page
return view('filter');
}
public function filtery(Request $request) { // filter ajax function
$articles = Article::paginate(2);
if($request->ajax()) {
// partial view returned in html
return $html = view('filterResults', compact('articles'));
}
}
Views
filter.blade.php
#extends('layouts/app')
#section('title')
Title
#endsection
#section('content')
<div class="container">
<!-- filter -->
<h2>Filter</h2>
<div class="content-card content">
<form method="POST" action="">
<!-- form code... -->
</form>
</div>
<div id="filter-results">
</div>
</div>
#endsection
filterResults.blade.php
#foreach($articles as $article)
<p>{{ $article->name }}</p>
#endforeach
{{ $articles->links() }}
Javascript
$("#submit-button").click(function(e) {
e.preventDefault();
// ajax request (raw mysql request)
var requestQuery = ...; // (quite long) raw request
console.log(requestQuery); // console verification of request
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
url: '../articles/request/ajax/articles/filter',
type: 'POST',
data: {
request: requestQuery
},
success: function(html) {
$("#filter-results").empty().html(html);
}
});
});
$(window).on('hashchange', function() {
// if hash in url
if (window.location.hash) {
// page contains hash value
var page = window.location.hash.replace('#', '');
if (page == Number.NaN || page <= 0) {
return false;
}
// if ok ->getData returned
else {
getData(page);
}
}
});
$(document).on('click', '.pagination a', function(e) {
e.preventDefault();
$('.pagination li').removeClass('active');
$(this).parent('li').addClass('active');
var url = $(this).attr('href');
var page = $(this).attr('href').split('page=')[1];
getData(page,url);
});
function getData(page,url) {
$.ajax(
{
url: url,
type: 'get',
datatype: 'html',
done: function(data) {
console.log('ok');
$('#filter-results').empty().html(data);
location.hash = page;
},
fail: function(jqXHR, ajaxOptions, thrownError) {
console.log('No response from server');
}
});
}
I don't understand why it is not working, I thing I misunderstood something.
Thanks and have a good day
Laravel uses the page value from the request, or query string, by convention. If you choose not to use that, you can set your own. If following convention, you'd need to append the query string page=# to your url in the ajax request.
The fourth argument of the Builder::paginate is the page number:
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
$results = ($total = $this->toBase()->getCountForPagination())
? $this->forPage($page, $perPage)->get($columns)
: $this->model->newCollection();
return $this->paginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
You could also define your own page resolver. The default is set in PaginationServiceProvider:
Paginator::currentPageResolver(function ($pageName = 'page') {
$page = $this->app['request']->input($pageName);
if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) {
return (int) $page;
}
return 1;
});
Route::get('articles/filter/{page}', 'ArticleController#filter');
public function filter(Request $request, int $page) {
$articles = Article::paginate($page);
}
it's all

jquery select2: error in getting data from php-mysql

I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.

Yii, Backbone save(), data did not passed through $_POST

This is my JavaScript in index.php:
MyModel = Backbone.Model.extend({
defaults: {
myID: "",
myName: ""
},
urlRoot: 'testAjaxAdd',
sync: function(method, model, options) {
options = options || {};
options['data'] = {};
options.data["myID"] = model.get("myID");
options.data["myName"] = model.get("myName");
options.data = JSON.stringify(options.data);
return Backbone.sync.apply(this, arguments);
}
});
MyView = Backbone.View.extend({
el: '.page',
render: function(){
var template = _.template($('#add-owner-template').html(), {});
this.$el.html(template);
},
events: {
'submit .create-owner-form': 'saveOwner'
},
saveOwner: function(events) {
var myName= $('input#myName').val();
var owner = new MyModel({
'myID': "111",
'myName': myName
});
owner.save({},{
success: function(model, response, options) {
console.log('success');
console.log(response); // show $_POST from actionSaveOwner in Controller
console.log(model.toJSON()); // show model
console.log(model.get('myID')); // show owner dbcID
console.log(model.get('myName')); // show owner userID
console.log(JSON.stringify(options)); // show options
console.log(options.data["myID"]); // this is shown undefined in console
console.log(options.data["myName"]); // this is shown undefined in console
},
error: function(model, response, options) {
console.log('error');
console.log(response);
console.log(model.toJSON());
}
});
}
});
I have put the code below in very first line within my javascript codes:
Backbone.emulateHTTP = true;
This is my html part of the form, it also a javascript template:
<script type="text/template" id="add-owner-template">
<form class='create-owner-form'>
<label>Name</label>
<input type="text" name="myName" id="myName"/>
<button type="submit" class="btn createcontbutton">Create</button>
</form>
</script>
This is my very simple action in Controller to test out if my backbone works or not:
public function actionTestAjaxAdd()
{
header('Content-type: application/json');
echo CJSON::encode($_POST);
}
However, this is what I see from console in POST tab:
Parameters application/x-www-form-urlencoded Do not sort
{"myID":"111","myName":"i...
But, the $_POST in controller action is nothing when i display it back in console from response.
I finally solved this myself using file_get_contents("php://input") .

AJAX throws error 500 only when PHP function is empty

I'm completely puzzled to why this happens, I've been messing on this for a few hours and I'm going crazyyyy! I am trying to update my DB when a checkbox is toggled on or off. The success response works if my PHP function I'm calling is empty, but fails whenever I add PHP. Note I'm on Laravel 3, and I've tried enabling or disabling CSRF filtering, no luck.
My JS:
$seenTD = $('td.seen_by_user');
$seenTD.each(function() {
$this = $(this);
var $seenLabel = $this.find('label');
var $seenInput = $this.find(':checkbox');
$seenInput.change(function() {
var _csrf = $('input[name="csrf_token"]').val();
var chkName = $(this).attr('name');
var checkVal = $(':checkbox[name='+chkName+']').prop('checked'); //true or false
var id = $this.find('input[name="reminder_id"]').val();
$.ajax({
url: 'update',
type: 'POST',
data: 'seen='+checkVal+'&reminder_id='+id+'&csrf_token='+_csrf,
success: function(data) {
console.log(data);
if($seenInput.is(':checked')) {
$seenLabel.removeClass('unchecked').addClass('checked');
$seenLabel.find('span').text('Oui');
}
else {
$seenLabel.removeClass('checked').addClass('unchecked');
$seenLabel.find('span').text('Non');
}
}
});
});
});
My PHP
public function post_update() {
$request = Request::instance();
$content = $request->getContent();
$id = $content['id'];
$seen = $content['seen'];
if($seen == 'true') {
$seen = 1;
}
if($seen == 'false') {
$seen = 0;
}
DB::table('reminders')->where('id', '=', $id)->update(
array(
'seen_by_user' => $seen
));
}
For the sake of maybe helping someone, as this is my first working AJAX, I'll explain how I got it to work, as well as supply working code. I'm not claiming this is the best way to do it, so if anyone has their word to say, don't hesitate :)
There were multiple issues, from Javascript insconsistency returning the row ID I needed for the database update, to the PHP function, and the way I was grabbing the POST data.
To get it to work, I played on Fiddler, retrieved the error message that Laravel throws at me. And I could debug from there :)
My working code is :
JS:
$('td.seen_by_user :checkbox').change(function() {
$this = $(this);
var $label = $this.siblings('label');
var id = $this.attr('data-id');
var _csrf = $this.siblings('input[name="csrf_token"]').val();
var value = $this.prop('checked');
$.ajax({
url: 'update',
type: 'POST',
data: {"seen_by_user": value, "id": id, "csrf_token": _csrf},
success: function(data) {
if($this.is(':checked')) {
$label.removeClass('unchecked').addClass('checked');
$label.find('span').text('Oui');
}
else {
$label.removeClass('checked').addClass('unchecked');
$label.find('span').text('Non');
}
}
});
});
PHP
function post_update() {
$id = $_POST['id'];
$seen = $_POST['seen_by_user'];
if($seen == 'true') {
$seen = 1;
}
if($seen == 'false') {
$seen = 0;
}
$update_reminder = DB::table('reminders')->where('id', '=', $id)->update(
array('seen_by_user' => $seen));
}
And my HTML (Blade Template from Laravel, where {{ }} brackets are simply echo's, and #foreach is a )
#foreach ($reminders as $reminder)
...
<td class="seen_by_user">
<form class="ajax" action="update" method="POST">
{{ Form::token() }}
{{ Form::checkbox('seen_'.$reminder->id, 1, $reminder->seen_by_user, array('id' => 'seen_'.$reminder->id, 'data-id' => $reminder->id)) }}
<label class="seen {{ ($reminder->seen_by_user == 1 ? 'checked' : 'unchecked' ) }}"for="{{ 'seen_'.$reminder->id }}"><i class="read"></i><span>{{ ($reminder->seen_by_user == 1 ? 'Oui' : 'Non') }}</span></label>
</form>
</td>
...
#endforeach
data should be an object like this
data: {"seen": checkVal, "reminder_id": id, "csrf_token": _csrf},
The $.ajax method will take care of the presentation and transmission.

How do you access data in php when the request method sent from backbone is delete?

I am using backbone.js for the first time and I am using in conjunction with php and mysql so that I can send and receive data from a database using backbone and I am having a problem with the delete request method. I cannot access the data that is sent along with the request method like I do with post and put. POST and PUT work perfectly in this script it is just delete I am having problems with.
Here is my code.
helloWorld.js
(function($) {
var Item = Backbone.Model.extend({
url: 'http://mysite.com/syncItem.php',
defaults: {
part1: 'hello',
part2: 'world',
}
});
var List = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li',
events: {
'click span.swap': 'swap',
'click span.delete': 'remove'
},
initialize: function() {
_.bindAll(this, 'render', 'unrender', 'swap', 'remove');
this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);
},
render: function() {
$(this.el).html('<span style="color:black;">' + this.model.get('part1') +' '+this.model.get('part2')+'</span> <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap parts]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
return this;
},
unrender: function() {
$(this.el).remove();
},
swap: function() {
var swapped = {
part1: this.model.get('part2'),
part2: this.model.get('part1')
};
this.model.set(swapped);
this.model.sync("update", this.model);
},
remove: function() {
this.model.sync("delete", this.model); //deletes Item from server DB
this.model.destroy(); //deletes Item from collection
}
});
var ListView = Backbone.View.extend({
el: $('div#backboneContainer'),
events: {
'click button#add': 'addItem'
},
initialize: function() {
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new List();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
render: function() {
var self = this;
$(this.el).append("<button id='add'>Add List Item</button>");
$(this.el).append("<ul></ul>");
},
addItem : function() {
this.counter++;
item = new Item({id: this.counter});
item.set({
part2: item.get('part2') + this.counter
});
this.collection.add(item);
item.sync("create", item);
},
appendItem: function() {
var itemView = new ItemView({
model: item
});
$('ul', this.el).append(itemView.render().el);
}
});
var listView = new ListView();
})(jQuery);
syncItem.php
<?php
include("includes/openDbConn.php");
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
switch($request_method) {
case 'post': {
$data = json_decode(file_get_contents('php://input'));
if($stmt = $mysqli->prepare("INSERT INTO backbonetest (modelId, part1, part2) VALUES (?, ?, ?)"))
{
$stmt->bind_param("iss", $data->{'id'}, $data->{'part1'}, $data->{'part2'});
$stmt->execute();
}
break;
}
case 'get': {
//NOT FINISHED
break;
}
case 'put': {
$data = json_decode(file_get_contents('php://input'));
if($stmt = $mysqli->prepare("UPDATE backbonetest SET part1 = ?, part2 = ? WHERE modelId = ?"))
{
$stmt->bind_param("ssi", $data->{'part1'}, $data->{'part2'}, $data->{'id'});
$stmt->execute();
}
break;
}
case 'delete': {
$data = json_decode(file_get_contents('php://input')); //gets data from the json that was sent with the request
if($stmt = $mysqli->prepare("DELETE FROM backbonetest WHERE modelId = ?"))
{
$stmt->bind_param("i", $data->{'id'});
$stmt->execute();
}
break;
}
}
?>
I have narrowed down where the error is to two spots: where I call this.model.sync("delete", this.model); or $data = json_decode(file_get_contents('php://input')); in the delete case. So I was wondering if there was a special way to access the data when dealing with the delete request method or am I just calling the delete function in backbone wrong?
You have a problem of unfulfilled expectations :) DELETE requests in Backbone don't send by default the attributes as POST, PUT and PATCH do1 : compare the requests sent by model.save and model.destroy in this Fiddle http://jsfiddle.net/fz68a/
You can override Item.sync to give it the behavior you expect:
var Item = Backbone.Model.extend({
defaults: {
part1: 'hello',
part2: 'world'
},
sync: function (method, model, options) {
if (method === 'delete') {
options = options || {};
options.contentType = 'application/json';
options.data = JSON.stringify(this.toJSON());
}
return Backbone.sync.call(this, method, model, options);
}
});
And a demo http://jsfiddle.net/fz68a/1/
1 See Backbone source code http://documentcloud.github.io/backbone/docs/backbone.html#section-139
from what i see on your php code. should already do this.as $_SERVER['REQUEST_METHOD'] which you already are using already answers your question. you can also do a dump $_SERVER to see if yuo backbone app did indeed make the request.
on another note...
...
remove: function() {
this.model.sync("delete", this.model); //deletes Item from server DB
this.model.destroy(); //deletes Item from collection
}
...
you don't need to call model.sync, as calling destroy already implicitly does this.
http://backbonejs.org/#Model-destroy
...
addItem : function() {
this.counter++;
item = new Item({id: this.counter});
item.set({
part2: item.get('part2') + this.counter
});
this.collection.add(item);
item.sync("create", item);
},
...
also instead of doing an collection.add. you can call collection.create
http://backbonejs.org/#Collection-create

Categories