call php function on clicking link in php - php

I had created basic custom module. in that i just filled information form and that information will stored into the database. and that data i am showing into table format. now i want to edit and delete records from clicking links.
I want to call php function on clicking following links
links are:
while($data = $result->fetchObject()){
$rows[] = array(
$data->id,
$data->name,
$data->address,
$data->mob,
$data->gen,
$data->email,
$data->hob,
l('Edit' .$data->id,'/table', array('query' => array('edi'=>$data- >id))),
l('Delete' .$data->id, '/table', array('query' => array('del'=>$data->id))),
);
}
and the functions are as follows:
function form_values_edit($id){
$id_val = $id;
$my_object = db_select('demo_forms','n')
->fields('n')
->condition('id', $id_val )
->execute()
->fetchAssoc();
return drupal_get_form('demo_form', $my_object);
}
function delete_confirm($form, &$form_state, $id){
$form['delete'] = array(
'#type' => 'value',
'#value' => $id,
);
return confirm_form(
$form,
t('Are you sure you want to delete this?',
'/table',
t('This action cannot be undone'),
t('Delete'),
t('Cancel')
));
}
function delete_confirm_submit($form, &$form_state) {
$record = $form_state['values']['delete'];
if ($record ) {
$num_deleted = db_delete('demo_forms')
->condition('id', $record )
->execute();
drupal_set_message('The record has been deleted!');
}
$form_state['redirect'] = "/table";
}
Thanks

You cannot call a PHP function dynamically by clicking a link, as PHP is a server side language. HOWEVER if you load another page, before loading the page you can execute PHP code.
EDIT
if you need a PHP function dynamically, what I usually do (and this may be wrong according to some people) is call that function in an AJAX call. Note: I would generally use POST for this.
$.ajax(
url: 'url/to/php/function',
type: 'POST/GET',
data: {'data' : data},
success: function(res) {
// use the result stored in res
},
error: function(res) {
// use res to get the error result
}
);

Just add check for id field or another unique value in your php code and update or delete rows where id = ... With out unique value you can't do that. Describe your usability and post your html for more...

Related

Returning an array from DB query as JSON and then putting the contents into list elements with jQuery

I have a commenting system I am working on thats is aiming to be like instagrams system.
Currently, I show the last 3 items in a PHP foreach and also have a 'show all button'.
My aim is then that button gets clicked and calls a function which then returns all the comments as an array. I then would need to .prepend() this array as list elements.
Normally an AJAX call to fetch data is fine. But in the past I have only retuned one line values.
I am using Laravel so my function to fetch would be something like:
public function fetch() {
DB:: // SELECT ALL COMMENTS
$commentsArray = array();
foreach ($comments as $comment) {
$commentsArray = (array('commentusername', 'comment'));
}
return Response::json(array(
'success' => true,
'comments' => $commentsArray,
200)
);
}
And then in my jQuery call:
if (data.success) {
$(".comments_"+id).prepend("<li><b>USERNAME:</b> Comment</li>");
}
That prepend woulds as I want, but I need to learn how I should be correctly creating the array, and then how I can loop through them and create the list elements in jQuery.
Note, that PHP function is written here and untested etc.
Thanks.
First, use array_map to get an array of the format you want:
public function fetch() {
DB:: // SELECT ALL COMMENTS
$commentsArray = array_map(function($comment){
return array(
'username' => $comment->commentusername,
'comment' => $comment->comment
);
}, $comments);
return Response::json(array(
'success' => true,
'comments' => $commentsArray
));
}
(I changed commentusername to username for the output array. Also you don't need the 200 in your response)
Now this is what your response will look like:
{
success: true,
comments: [
{username: 'foo', comment: 'comment of foo'},
{username: 'foo', comment: 'comment of foo'}
]
}
Then in your javascript code, do this:
if (data.success) {
for(var i=0; i<data.comments.length; i++){
var comment = data.comments[i];
$(".comments_"+id).prepend("<li><b>"+comment.username+":</b> "+comment.comment+"</li>");
}
}
Also note that if you use HTTP status codes for errors, you can remove success: true and assume that if the response is 200 (ajax success callback) the request has been made successfully.
I could not understand your question, but i m gonna to show you, how you can get json response from script and then can parse that,
// script.php
<?php
$data = array(
array('User' : 'Tiger', 'Comment' : 'Any comment,, '),
array('User' : 'John', 'Comment' : 'Tiger is nice guy !!')
); // In reality data will fetch from Db
header('Content-Type: application/json'); // must be set, and no space between ...pe and ':'
echo json_encode($data);
?>
client_side.js
$.get('script.php', function(data) {
for(i = 0; i < data.length; i++){
$(".comments_"+id).prepend("<li><b>USERNAME :</b> " + data[i].User + " <b> Comment :</b> " + data[i].Comment + "</li>"); // You should use templete here
} // __prepending comments
}, 'json');
Thanks :)
First of all, you need to add your arrays to an array. As you do, you are always just overwrite your variable:
$commentsArray[] = (array('commentusername', 'comment'));
add a [] after your name of variable.
And then in the jQuery:
$.each(data, function(idx, obj) {
$(".comments_"+id).prepend("<li><b>USERNAME:" + obj.commentusername + ", </b> Comment</li>" + obj.comment);
});
NOTE: Don't forget to check and change your id in the loop.

How to load model data to Select2 dropdown which uses Ajax filtering in Yii

I use the following select2 Yii widget in my view to populate a drop-down list. Since the data necessary for the preparation of the select list consists of more than 2K records I use select2 with minimumInputLength parameter and an ajax query to generate partial result of the list based on user input. If I create a new record I have no problem at all. It populates everything fine and I can save data to my database. However I don't know how to load saved data back to this drop-down during my update action. I read somewhere that initselection intended for this purpose but I couldn't figure out how to use it.
Can someone help me out on this?
My view:
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
'allowClear'=>true,
'placeholder'=>'Kérem válasszon összetevőt!',
'minimumInputLength' => 3,
'ajax' => array(
'url' => Yii::app()->createUrl('etelOsszerendeles/filterOsszetevo'),
'dataType' => 'json',
'quietMillis'=> 100,
'data' => 'js: function(text,page) {
return {
q: text,
page_limit: 10,
page: page,
};
}',
'results'=>'js:function(data,page) { var more = (page * 10) < data.total; return {results: data, more:more }; }',
),
),
));?>
My controller's action filter:
public function actionFilterOsszetevo()
{
$list = EtelOsszetevo::model()->findAll('nev like :osszetevo_neve',array(':osszetevo_neve'=>"%".$_GET['q']."%"));
$result = array();
foreach ($list as $item){
$result[] = array(
'id'=>$item->id,
'text'=>$item->nev,
);
}
echo CJSON::encode($result);
}
I use initSelection to load existing record for update in this way (I replaced some of your view code with ... to focus in main changes). Tested with Yii 1.1.14. Essentially, I use two different ajax calls:
View:
<?php
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
...
...
'ajax' => array(
'url' => Yii::app()->createUrl('client/searchByQuery'),
...
...
'data' => 'js: function(text,page) {
return {
q: text,
...
};
}',
...
),
'initSelection'=>'js:function(element,callback) {
var id=$(element).val(); // read #selector value
if ( id !== "" ) {
$.ajax("'.Yii::app()->createUrl('client/searchById').'", {
data: { id: id },
dataType: "json"
}).done(function(data,textStatus, jqXHR) { callback(data[0]); });
}
}',
),
));
?>
Now in your controller you should receive parameters for ajax processing: query (q), as string, when inserting; id (id) as int when updating. Parameter names must be same as ajax data parameters (in this sample insert q; in update id) when read in $_GET. Code is not refactored/optimized:
Controller:
public function actionSearchByQuery(){
$data = Client::model()->searchByQuery( (string)$_GET['q'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
public function actionSearchById(){
$data = Client::model()->findByPk( (int) $_GET['id'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
Model - custom query and a little of order / security / clean :)
public function searchByQuery( $query='' ) {
$criteria = new CDbCriteria;
$criteria->select = 'id, ssn, full_name';
$criteria->condition = "ssn LIKE :ssn OR full_name LIKE :full_name";
$criteria->params = array (
':ssn' => '%'. $query .'%',
':full_name' => '%'. $query .'%',
);
$criteria->limit = 10;
return $this->findAll( $criteria );
}
EDIT:
It works out of box when update is preloaded with traditional HTTP Post (synchronous, for example with Yii generated forms). For async/Ajax updates, for example with JQuery:
Event / Trigger:
$('#button').on("click", function(e) {
...
... your update logic, ajax request, read values, etc
...
$('#select2_element').select2('val', id_to_load );
});
With this, initSelection will run again in async way with new id_to_load value, reloading record by id.
In your case and for your needs, initSelection could be complete different to avoid load record from db or you can use formatResult and formatSelection custom functions (are described in Load Remote Data sample source code). Reading documentation, I understand that initSelection's callback need JSON data with id and text elements to load properly or you could try to combine both concepts (this initSelection with your custom JS event/trigger call) (not tested):
'initSelection'=>'js:function(element,callback) {
// here your code to load and build your values,
// this is very basic sample
var id='myId';
var text='myValue';
data = {
"id": id,
"text": text
}
callback(data);
}',
Or directly on Trigger call:
$('#button').on("click", function(e) {
...
... ...
$("#select2_element").select2("data", {id: "myId", text: "MyVal"});
});
Hope that helps.
I tried doing that way, but couldn't do it
the solution I came up to get my record filled and selected was:
In case of the attribute having some data(in update mode or default value), I wrote some javascript that after document ready event, would fill the select with my data (just selected it ind pushed html in it), and made it selected, and then I rest( or update) the select to show my work.

My ajax JSON object is recognized as "Undefined"

I am having troubles with my ajax call. When I try to alert the result it keeps resulting as Undefined.
Both alerts are resulting to undefined.
I am not too sure if I am coding this correctly, please help me if I am.
Q: If I am accessing it incorrectly, how exactly would I access the skill property/index.
JQUERY/JSCRIPT
$(document).ready(function(){
// Skill sort on change
$('#order_by').on('change', function() {
$.ajax({
type: "POST",
url: "sort_skill_be.php",
dataType: "json",
data: {skill:this.value}
}).done(function(result){
alert(result[0].skill);
})
});
});
PHP FILE: This method receives a statement and places an "object" array to an overall array.
function helpFetchPostInfo($stmt){
$results = $stmt->fetchAll();
$recent_posts = array();
foreach ($results as $row){
$post = array(
'username' => $row['username'],
'steam' => $row['steam'],
'skill' => $row['skill'],
'description' => $row['description'],
'date' => $row['date'],
);
array_push($recent_posts, $post);
}
return json_encode($recent_posts);
}
Thank you for the assistance it is much appreciated
function sortSkill($skill){
// If All skill is selected display posts normally
if ($skill == 'All'){
displayPosts();
exit;
}
$db = connect();
$sql = "SELECT * FROM users LEFT JOIN posts
ON users.idUsers = posts.fkuser
WHERE posts.fkuser IS NOT NULL and users.skill=:skill
ORDER BY date DESC";
$stmt = $db->prepare($sql);
$stmt->execute(array(':skill' => $skill));
if ($stmt->rowCount() == 0){
// Nothing has returned
unset($_SESSION['recent_posts']); // Reset session of posts if no posts appear.
}
else
{
$recent_posts = helpFetchPostInfo($stmt);
return $recent_posts;
}
}
Sort skill is being called in a seperate php file called sort_skill_be.php, which is called from the jquery when a selection is changed.
<?php
session_start();
include 'database.php';
$skill_sort = $_POST['skill'];
sortSkill($skill_sort);
header('Location:index.php');
?>
EDIT: added JSON datatype to jquery
Now my problem is the alert is not being called at all anymore.
Looks like you are not providing the dataType attribute in your ajax method.
dataType: "json",
Either do that or parse your result to JSON before accessing it.
I don't see any issue the way you are trying to access the object.

Cakephp Js helper

I am working with Js helper to help me replace the contents of a "div" in my index.ctp with contents of another file changeto.ctp .
This application has a few check boxes with corresponding images. When I select a checkbox, the setting is stored in the database and the corresponding image is to be displayed. Similarly when unchecked, it is to be removed from the database and the image should disappear.
I am using the Js helper for this :
my changeto.ctp is subset of my index.ctp and has access to same variables and loads without any problems (except that any click/change events are just not responded to. The names of the Ids of the checkboxes are exactly same).
My index file contains the following Js code at the bottom of all Html:
$this->Js->get($change_checkbox1 )->event('click',
$this->Js->request(array(
'controller'=>'testing',
'action'=>'changeto'
), array(
'update'=>'#changeDiv',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => false,
'inline' => true
))
))
);
This is generating the following Jquery/javascript
$(document).ready(function () {$("#ck0_1_8").bind("click", function (event) {$.ajax({async:true, data:$("#ck0_1_8").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#changeDiv").html(data);}, type:"post", url:"\/mytest-site\/options\/testing"});
return false;});
}
My controller has a function called
changeto()
{
$this->layout = 'ajax';
}
the first time I click on this the checkbox this works without any problem. However any subsequent clicks don't work. The javascript is not even being called.
My questions are :
Any ideas ?
Will it help if I somehow ask cakephp to use on() / live() insead of bind() .If yes how ?
Thanks!!
Solved this by editing a cakephp core file:
lib/Cake/View/Helper/JqueryEngineHelper.php
line 184:
change
return sprintf('%s.bind("%s", %s);', $this->selection, $type, $callback);
to
return sprintf('%s.live("%s", %s);', $this->selection, $type, $callback);
cake version 2.2.2
You have to use on instead of bind as they suggest in this question .live() vs .bind()
That's what I did was create my own Helper on View/Helper add the following method:
public function onEvent($selector, $type, $callback, $options = array()) {
$defaults = array('wrap' => true, 'stop' => true);
$options = array_merge($defaults, $options);
$function = 'function (event) {%s}';
if ($options['wrap'] && $options['stop']) {
$callback .= "\nreturn false;";
}
if ($options['wrap']) {
$callback = sprintf($function, $callback);
}
return sprintf('$(document).on("%s", "%s", %s);', $type, $selector, $callback);
}
And use that method from my views:
echo $this->MyJs->onEvent('#creditcards', 'change', $eventCode, array('stop' => false));

My Codeigniter autocomplete with ajax

I’m adding private messaging to my site. In the Recipient text field in my form, I want to suggest valid usernames when someone starts typing. After reading tutorials and studying some scripts I made the following code for suggesting usernames from my database table named users. It works but I’m not certain how correct and secure it is.
Jquery (using the Jquery UI autocomplete plugin):
$(function() {
$( "#username" ).autocomplete({ //the recipient text field with id #username
source: function( request, response ) {
$.ajax({
url: "http://localhost/mysite/index.php/my_controller/search_username",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
});
Controller (for simplicity I did not use a model although I plan to)
function search_username()
{
$username = trim($this->input->get('term')); //get term parameter sent via text field. Not sure how secure get() is
$this->db->select('id, username');
$this->db->from('users');
$this->db->like('username', $username);
$this->db->limit('5');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['response'] = 'true'; //If username exists set true
$data['message'] = array();
foreach ($query->result() as $row)
{
$data['message'][] = array(
'label' => $row->username,
'value' => $row->username,
'user_id' => $row->id
);
}
}
else
{
$data['response'] = 'false'; //Set false if user not valid
}
echo json_encode($data);
}
There is one edit that I would recommend making...
I would enable XSS protection by passing a second argument TRUE to get()
$username = trim($this->input->get('term', TRUE));
You can also add more exception, if you wish that function will works only for ajax calls :
if($this->input->is_ajax_request())
{
//... process the input
}
else
{
show_404();
}
Codeigniter active record database should make your code clean of any SQL injections. And if you're not posting anything you don't need to worry about XSS.
Using this someone could get a list of all possible usernames.. but other than that I would say it's "secure" (it looks very similar to what i'm using for my site =p)
EDIT:
And if you're not posting anything you don't need to worry about XSS.
I should clarify, IF you are posting anything (displaying anything that the user enters) then you should XSS filter (which johndavidjohn's answer below me explains [just pass TRUE as 2nd param]).. I didn't quite understand what u meant in your explanation of what "term" is... If all you are doing is searching, then you do not need to XSS filter, but if a user can send/write a message (generate content that your site stores [to be displayed]) then you should XSS filter on iput.

Categories