InlineButton should change value (date) in database - php

Im trying to implement an Inline button inside a table, that immediately changes / writes the Date of today in the database.
The click on the Button "change" should write the actual Date in the Database.
I already found a way to create an inline button to change a boolean value inside the Database. To activate / deactivate a Product for example.
Now I nearly need the same only with the fact, that when I press the Button it should write todays date inside the Database.
Creating the Button
function doCustomRenderColumn($fieldName, $fieldData, $rowData, &$customText, &$handled)
{
if ($fieldName == 'active') {
$dataAttributes = sprintf('data-id="%s" data-active="%s"', $rowData['id'], $fieldData);
$customText = '<span class="product-info" style="display: none;" ' . $dataAttributes. '></span>' . $customText;
$customText .= '<button class="btn btn-default inline-button" style="margin-left: 25px;">Change</button>';
$handled = true;
}
}
Handling parameters and executing the query
function DoPrepare() {
if (GetApplication()->IsGETValueSet('id') && GetApplication()->IsGETValueSet('active')) {
$id = GetApplication()->GetGETValue('id');
$active = GetApplication()->GetGETValue('active');
$sql = "UPDATE product SET active=$active WHERE id=$id";
$this->GetConnection()->ExecSQL($sql);
echo json_encode(array("active" => $active));
exit;
}
Handling the button click and calling AJAX
// OnAfterPageLoad event body
function prepareInlineButtons() {
$('button.inline-button').click(function() {
var self = $(this);
var checkboxControl = self.siblings('.pg-row-checkbox');
var productId = self.siblings('.product-info').data('id');
var activity = self.siblings('.product-info').data('active');
$.getJSON(location.href, {id: productId, active: activity == 1 ? 0 : 1}, function (data) {
self.siblings('.product-info').data('active', data.active);
if (data.active == 1) {
checkboxControl.addClass('checked')
}
else {
checkboxControl.removeClass('checked')
}
})
})
}
prepareInlineButtons();

You use click(function(), but this don't gonna work.
This just work for objects already on screen at loading time.
Try use .on() jquery function, like $('button.inline-button').on('click', function()

Related

Calling a php function with a button by using jquery

I'm trying to figure out how to call a PHP function with a html button as i understand so far i can't use javascript since it client side but would it work with jquery and how so?
Here my button
<button type="button" class="btn btn-default" data-dismiss="modal">Yes</button>
And here is my function in php
function confirmCloseTicket($conn) {
if (isset($_GET['deleteticketid'])) {
$id = $_GET['deleteticketid'];
$statuschange = "Closed Ticket";
$sql = "INSERT INTO closedtickets SELECT * FROM ticket WHERE ticketID = $id;";
$sql .= "DELETE FROM ticket WHERE ticketID = $id;";
$sql .= "UPDATE closedtickets SET status = '$statuschange' WHERE closedtickets.ticketID = $id;";
$result = mysqli_multi_query($conn, $sql);
if($result) {
header("location: http://localhost/ticketSystem/viewticket.php");
exit();
}else {
echo "failed";
}
}
}
I figure it out with this method:
Starting of to create a button using <a> tag and give it AN ID "Verify-Email" you can call it what ever you want just remember it!
HTML:
Verify Now!
In jquery or inside a <script></script> tag i call ID "#verify-email". also using # it tells is a ID and not a class, if you were using a class it would look like this.
".verify-email"
Then i'm using a .click(function(e){ a bassic click do function.
then i'm using e.preventDefault(); to prevent the page to refresh while we doing this click function by pressing the button from the page.
then i'm using a $.ajax({ }); reuqest to call it to POST Method.
as you can see inside my Ajax i have URL, method and DATA, what i have done i have called an action : 'verify-email' see step 6. how i GET that POST inside php.
jquery:
$("#verify-email").click(function(e) {
e.preventDefault();
$(this).text('Please Wait...');
$.ajax({
url: 'assets/php/process.php',
method: 'POST',
data: { action: 'verify-email' },
success:function(response){
$("#verifyEmailAlert").html(response);
$("#verify-email").text('Verify Now');
}
});
});
inside here i have a isset function by verify super global variable $_POST['action] and also checking it again with 'verify-email' both of those values need to be same as $.ajax method
process.php:
if (isset($_POST['action']) && $_POST['action'] == 'verify-email') {
// need to create a varible for "verify-email"
$Getemail = $_POST['verify-email'];
then call the function
}

PHP/JQUERY label to input in while loop on edit button click

I'm using php/jquery and html my requirement is when I click on edit button, label should be replaced with input text and I would be able to update in my mysql db and if I click on cancel button input to label..
Following is my code:
<?php
$sql = 'select * from demo';
while($row = mysql_fetch_object($sql)) {
?>
<label style="display:block;">abc</label>
<input type="text" style="display:none;"/>
<button id="edit">edit</button>
<button id="cancel">cancel</button>
<?php
}
?>
suppose If I display 10 records from mysql db, for each record I should be able to edit on particularly clicked row.
Any help is appreciated thanks!
I would wrap each label in a parent (for example a p).
On a click, you hide the label and add a input and two buttons to the parent.
By clicking the cancel button, the label gets visible again and the other elements will be removed.
The "tricky" part is the submit button. You'll need a PHP page that processes the data you post to it. Then when it succeeds you should echo an ok . The $.post function knows a success argument. This function will check if the returned value will be ok, and if so, changes the text from the label, shows it, and removes the other items.
$(function() {
$('.edit').on('click', function(e) {
e.preventDefault();
var elem = $(this) ,
label = elem.prev('label') ,
parent = elem.parent() ,
value = label.text() ,
input = '<input type="text" value="'+value+'" />' ,
save = '<button class="save">Save</button>' ,
cancel = '<button class="cancel">Cancel</button>';
parent.children().hide();
parent.append(input+save+cancel);
});
$(document).on('click', '.cancel', function(e) {
e.preventDefault();
var elem = $(this) ,
parent = elem.parent() ,
label = parent.find('label');
parent.children(':not(label,.edit)').remove();
parent.children().show();
});
$(document).on('click', '.save', function(e) {
e.preventDefault();
var elem = $(this) ,
parent = elem.parent() ,
label = parent.find('label') ,
value = parent.find('input').val();
parent.addClass('active');
var data = '&name='+value;
$.post("processingPage.php", data)
.success( function(returnedData) {
if( returnedData == 'ok' ) { /* change this to check if the data was processed right */
var active = $('.active');
active.find('label').text( active.find('input').val() );
active.children(':not(label,.edit)').remove();
active.children.show();
}
});
$('.active').removeClass('active');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label>Some text</label><button class="edit">Edit</button></p>
<p><label>Some text</label><button class="edit">Edit</button></p>
<p><label>Some text</label><button class="edit">Edit</button></p>
<p><label>Some text</label><button class="edit">Edit</button></p>
You're PHP would look like this:
<?php
$return = false;
if( isset( $_POST['name'] ) ) {
if( mysqli_query( ... ) ) {
$return = true;
}
}
if( $return )
echo 'ok';
else
echo 'not ok';
?>

Follow button with AJAX

I have created a button with which you can follow/unfollow a user, with AJAx and PHP.
If you click on the button, you follow, else, you unfollow.
There's a function that checks if the user you try to follow is already followed...
HTML
<div class="heart"><i class="fa fa-heart awesome"></i></div>
PHP
public static function Follow($user, $seguidor){
$sql = "INSERT INTO seguidores (id_canal, id_seguidor) VALUES ('$user', '$seguidor')";
$resultado = self::Conexion($sql);
return $resultado;
}
public static function CheckFollow($user, $seguidor){
$heart = "";
$sql = "SELECT * FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
$resultado = self::Conexion($sql);
$verificacion = false;
if(isset($resultado)) {
$fila = $resultado->fetch();
if($fila !== false){
$verificacion = true;
}
}
if($verificacion == false){
$heart = "<div data-id='".$user."' class='heart'><i class='fa fa-heart awesome'></i></div>";
} else {
$heart = "<div data-id='".$user."' class='heart like'><i class='fa fa-heart awesome'></i></div>";
}
return $heart;
}
public static function Unfollow($user, $seguidor){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
$resultado = self::Conexion($sql);
return $resultado;
}
AJAX
$(document).ready(function () {
$function() {
var element = $(this);
var data_id = element.attr("data-id");
$.ajax({
type: "POST",
url: "database.php",
data: data_id,
success: function(){ }
});
return false;
}
});
The problem is, how can I load those php funcionts everytime I click the button...
Click > follow
Another click > unfollow
Here's a few suggestions:
I notice you are creating HTML strings in PHP. If at all possible, you want to avoid doing that.
Keep all your HTML, CSS and JavaScript client-side. As you progress as a developer, you will start to see why. Think of them as templates.
In this case, you just need to return either "followed" or 'unfollowed" to the client callback. Could boil it down to a boolean!
So, in your template, define both the followed state and the unfollowed state. Use CSS to hide the appropriate one. This can be incredibly lightweight!
In these examples, you just set the follow attribute on your button.
So your javascript would look like:
// I would do something like:
find=document;
id="getElementById";
/* ... */
success: function (request, status)
{
if (!status)
return
;
find[id]("follow-1").setAttribute("follow", request.responseText)
}
(check the ajax api of the lib)
1.)
<button id="follow-1" follow="true">
<img src="transparent.png" />
</button>
+
button[follow="false"] > img
{ background: transparent url("unfollow.png");
}
button[follow="true"] > img
{ background: transparent url("follow.png");
}
2.)
<button id="follow-1" follow="true">
<img src="follow.png" />
<img src="unfollow.png" />
</button>
+
button[follow] > img
{ display: none;
}
button[follow="false"] > img:last-child
{ display: block;
}
button[follow="true"] > img:first-child
{ display: block;
}
I would suggest using framework such as CodeIgniter to handle the back-end as you can post data directly to public controller methods directly from ajax, but for rough idea on how it could work (you may need to fix up bugs / tweak as I wrote from memory):
Add to PHP to handle incoming requests:
//Minimal vulnerability protection while getting inputs.
$update_types = array("Follow", "CheckFollow", "Unfollow");
$update_method = in_array($_POST["update_type"],
$update_types)? $_POST["update_type"], "");
if ($update_method) {
//Call the update function & bounce the response
//in JSON back to the AJAX handler.
echo json_encode(call_user_func($update_method,
(int) $_POST["user_id"], (int) $_POST["seguidor"]));
}
Javascript:
$(document).ready(function () {
//Button click handler.
$("div.heart").on("click", function() {
var my_button = $(this);
var update_type = "";
if (my_button.hasClass('.like'))
update_type = "Unfollow";
else
update_type = "Follow";
$.ajax({
type: "POST",
url: "database.php",
data: {
"update_type": update_type,
user_id: my_button.attr("data-id"),
seguidor: "some value here - not sure based on code"
},
success: function(response) {
//response from server - check for errors...
//Update the UI - add heart if follow updated, remove it if not.
//You will need to modify your php functions to return result code and then either add "like" class or remove it - obviously this is not a complete rewrite of your app.
if ("/* result is followed */")
my_button.addClass("like");
else
my_button.removeClass("like");
}
});
});
});

Force selection with JQuery autocomplete

I know this question has been asked before, but I wasn't able to find any answers that are up to date or functional (at least for my application).
My JQuery autocomplete box is using a mysql database as its source. I want the user to be able to type to get recommendations, but then is forced to select from the dropdown choices before they can submit the form.
My Javascript:
<script type="text/javascript">
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 5
});
});
var inputs = {college: false};
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
alert('incorrect');
return false;
}
}
alert('correct');
$('#college_select_form').submit();
});
</script>
My form:
<form action="choose.php" method="post" id="college_select_form" name="college_select_form">
<input type="text" id="college" name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
</form>
Search.php:
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what would be the best approach to doing this? The only solution I can think of is using PHP to verify that the textbox's value matches a value in the database, but I'm not sure how to implement that with my current code.
You should always check it in "choose.php" (server-side) since the user can disable the JavaScript and post whatever they want in the inputs of your form
$college = mysql_real_escape_string($_GET['college']);
if ($college != "" || $college != null || $college != -1)
{
//DO STUFF
}
NOTE: YOU SHOULD ALWAYS USE "mysql_real_escape_string" to prevent SQL Injection!
more info: http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
So accordingly in search.php change the
$ac_term = "%".$_GET['term']."%";
to
$ac_term = "%". mysql_real_escape_string($_GET['term']) ."%";
You can also check the form before the user submit to just make it more user friendly (users don't want to wait couple of seconds for the page to gets refreshed with errors on it!)
so maybe something like this would help: Submit Event Listener for a form
function evtSubmit(e) {
// code
e.preventDefault();
// CHECK IT HERE!
};
var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');
In my project i handled it by checking on focus-out , if the text entered in the autocomplete field actually matches my dropdown options.If not i will simply remove it.
change: function(event, ui) {
if (!ui.item) {
this.value = '';
}
}
See my full example here-Jquery auto comp example
it has an embeded fiddle,you can check the fiddle directly also
http://jsfiddle.net/9Agqm/3/light/
Add this code to your JavaScript before you instantiate your autocomplete object:
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
This will make it so whenever the menu appears, you have a list of current items the user can choose from stored in $.ui.autocomplete.currentItems. You can then use that to check against when you are submitting your form. Of course the way you implement this part is up to you depending on how dynamic your form is, but here is an example that requires hard-coding a list of input fields and making sure they all have ids.
//create an object that contains every input's id with a starting value of false
var inputs = {college: false};
//for each input, you will have a function that updates your 'inputs' object
//as long as all inputs have id's and they all are using autocomplete,
//the first line could be written as: $('input').change(function(){ and the
//function would only need to be written once. It is easier to maintain
//if you use seperate id's though like so:
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
//when you submit, check that your inputs are all marked as true
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
return false; //one or more input does not have correct value
}
}
//all inputs have a value generated from search.php
$('#myform').submit();
});
UPDATE
The only difference between our two examples (one that works and one that doesn't) is that you are binding other events to your input element, onclick and onblur. So by changing our listener from change to blur as well mostly fixes the problem. But it creates a new problem when the enter/return key is pressed to submit the form. So if we add a listener for that specific event then everything works out ok. Here is what the code looks like now:
var validateInfo = function(elem){
var id = elem.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(elem).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
}
$('#college').on('blur', function(){
validateInfo(this);
}).on('keydown', function(e){
if(e.which == 13){ //Enter key pressed
validateInfo(this);
}
});
Add a hidden input element to your form:
<input type="hidden" name="selectedvalue" id="selectedvalue" />
Add a select event handler to your autocomplete, that copies the selected value to the hidden input:
$("#college").autocomplete({
source: "search.php",
minLength: 5,
select: function (event, ui) {
$('#selectedvalue').val(ui.item.value);
}
});
Then just ignore the auto-complete form input in posted data.
As this is javascript, your only concern should be if an item is selected from the autocomplete list. This can simply be done by setting a variable to true on select and false on change. That is enough to prevent regular users from continuing without selecting a school. To prevent abuse you need to check the value server side after posting. All normal user will pass that check.
If I understand the question correctly, this is something I have encountered before. Here is some code pretty much lifted straight out of another project. I have used a local datasource here but the project this is lifted from uses remote data so there won't be a difference:
var valueSelected = '';
$('#college').autocomplete({
source: ['collegeA', 'collegeB', 'collegeC']
}).on('autocompletechange autocompleteselect', function (event, ui) {
if (!ui.item) {
valueSelected = '';
} else {
$('#submit').prop('disabled', false);
valueSelected = ui.item.label;
}
}).on('propertychange input keyup cut paste', function () {
if ($(this).val() != valueSelected) {
valueSelected = '';
}
$('#submit').prop('disabled', !valueSelected);
});
This will programatically enable and disable the submit button depending on whether a value has been selected by the user.
Fiddle here

Trying to make an AJAX edit in place in Codeigniter .. failing

I'm on my first CI project and I'm trying to do basically an AJAX "edit in place".
I have a user profile page with a number of fields. Basically the user is looking at his own data, and I would like to give him the option to edit his info on a field by field basis. I have about 20 fields like so..
<div id="desc_short">
<div class="old_info"><p><?php echo $the_user->desc_short; ?></p></div>
<div class="edit_buttons">
<button type="button" class="btn_edit">Edit Field</button>
<button type="button" class="btn_submit">Submit Change</button>
<button type="button" class="btn_cancel">Cancel</button>
</div>
The submit and cancel buttons start off with display:none. A click on the 'edit' button appends a form to the div with some hidden field info and "shows it in" along with 'submit' and 'cancel' buttons. SO now the user has a text field under the original info, and two new buttons.
$('.btn_edit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var form_HTML = "<form action='edit_profile' method='post'><input type='text' class='new_info' name='new_info'/><input type='hidden' class='edit_field' name='edit_field' value='"+this_field_id+"'/></form>";
$("#"+this_field_id).append(form_HTML).hide().show(500);
$(this).siblings().fadeIn(1000);
});
So I am dynamically adding the form to the appropriate div, and giving it a hidden field with the name of the datafield that is being edited. I'm also showing the "submit" and "cancel" buttons (although notice that the submit button is not in the form element).
I'll leave out the "cancel button" function, but here is the submit button jquery. As you can see I am trying to submit the form by "remote control", triggering a submit event on the form long distance from the submit button. And then on the submit event, I preventDefault and then try to $.post the info to an AJAX controller..
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data = 'true')
{
alert(data); // <<<< alerts "true"
}
else
{
alert("bad");
}
}
);
});
});
Here is the ajax controller
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
$result = $this->Member_model->edit_profile( $ID, $field, $new_info );
echo $result;
}
And the model..
public function edit_profile($ID, $field, $new_info)
{
$statement = "UPDATE users SET $field=$new_info WHERE UID=$ID"
$query = $this->db->query($statement);
return $query;
}
I am actually getting back "TRUE" back to Jquery to alert out .. but nothing is being edited. No change to the information. Frankly, I am surprised I'm even getting 'true' back (the whole remote submit thing .. I thought "no way this works").. but that makes it tough to see what is going wrong.
Ideas?
Apart from the if(data = 'true) error, i don't see where the other error could be.
When you alert data, what does it show you?
Try this in the model;
public function edit_profile($ID, $field, $new_info)
{
$data = array('field_table' => $field, 'new_info_table' => $new_info);
return ($this->db->where('UID',$ID)->update('tabel_name',$data)) ? TRUE : FALSE;
}
AND in
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
if($this->Member_model->edit_profile( $ID, $field, $new_info )){
echo 'success';
}else{
echo 'error';
}
}
Then
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data == 'success')
{
alert(data); // <<<< alerts "true"
}
else if(data == 'error')
{
alert('Database error');
}
else{
alert('');
}
}
);
});
});
Just wrote it on here, so i haven't tested it. But give it a try, at least you might be able to know where the error is coming from. If you still get the same error, try alert data before the if(data == 'sucess'), to see what the profile edit func is returning.

Categories