jqgrid php SELECT query problems - jqgrid
I am attempting to use a variable in my SELECT statement but I'm running into some very strange problems .code below.
do not work,none data!
Code:
$fid= $_GET['f'];
echo $fid;//prints 3
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid = '$fid' ";
work fine!
**Code:**
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid ='3' ";
thank you!
grid.php
<?php include ("add/add_config.php");?>
<?php include ("php/jqAutocomplete.php");?>
<?php include ("php/jqCalendar.php");?>
<?php include ("php/jqGrid.php");?>
<?php
ini_set("display_errors","1");
$fid= $_GET['f'];
include ("php/jqGridPdo.php");
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
echo $fid;
$grid->SelectCommand ="SELECT threadid, thumb, title, stage, status, startdate ,duedate FROM thread WHERE forumid='3'";
//$g="SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid='$fid'";
//echo $g;
// set the ouput format to json
$grid->dataType = 'json';
$grid->table ="thread";
$grid->setPrimaryKeyId("threadid");
$grid->setUrl('grid.php');
$grid->cacheCount = true;
$grid->addCol(array(
"name"=>"actions",
"formatter"=>"actions",
"editable"=>false,
"sortable"=>false,
"resizable"=>false,
"fixed"=>true,
"width"=>60,
"formatoptions"=>array("keys"=>true)
), "first");
$grid->setGridOptions(array(
"caption"=>"cdbdev",
"rownumbers"=>true,
"toppager"=>true,
"rowNum"=>10,
"sortname"=>"threadid",
"hoverrows"=>true,
"rowList"=>array(10,20,50),
"postData"=>array("grid_recs"=>776),
"height"=>"auto",
"width"=>"auto"
));
$grid->addCol(array("name"=>"fileToUpload", "editable"=>true, "edittype"=>"file", "editrules"=>array("edithidden"=>true)));
$upload = <<<UPLOAD
function(formid) {
//These are needed for fileupload plugin
$(formid).attr("method","POST");
$(formid).attr("action","");
$(formid).attr("enctype","multipart/form-data");
$("<br/><button id='buttonUpload'>Upload</button>").insertAfter("#fileToUpload",formid);
// bind a event
$("#buttonUpload",formid).click(function(){
$.ajaxFileUpload({
url:'doajaxfileupload.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status) {
console.log(data);
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else{
$("#fileToUpload").val("");
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(e);
}
});
return false;
});
}
UPLOAD;
$grid->setJSCode($upload);
$image = <<<CUSTOM
function formatImage(cellValue, options, rowObject) {
var imageHtml = "<img src='images/" + cellValue + "' originalValue='" + cellValue + "' />";
return imageHtml;
}
function unformatImage(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
function formatRating(cellValue, options, rowObject) {
var color = (parseInt(cellValue) > 0) ? "green" : "red";
var cellHtml = "<span style='color:" + color + "' originalValue='" +
cellValue + "'>" + cellValue + "</span>";
return cellHtml;
}
function unformatRating(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
CUSTOM;
$grid->setJSCode($image);
$grid->setSelect('stage', "SELECT id, name FROM selection where statid=1");
$grid->setSelect('status', "SELECT id,name FROM selection where statid=2 ");
$grid->setColProperty("threadid", array( "width"=>80 , "align"=>center));
$grid->setColProperty("stage", array( "width"=>120 , "align"=>center));
$grid->setColProperty("forumid", array( "width"=>0 ,));
$grid->setColProperty("status", array( "width"=>120 , "align"=>center ));
$grid->setColProperty("title", array( "width"=>280, "align"=>center ,"formatter"=>"showlink","formatoptions"=>array("baseLinkUrl"=>"showthread.php", "target"=>"_blank", "idName"=>"t")));
$grid->setColProperty("startdate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("duedate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("CustomerID", array("editrules"=>array("required"=>true)));
$grid->setAutocomplete("CustomerID",false,"SELECT CustomerID, CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName",null,true,true);
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("startdate",array("buttonOnly"=>false));
$grid->datearray = array('startdate');
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("duedate",array("buttonOnly"=>false));
$grid->datearray = array('duedate');
$grid->navigator = true;
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"excel"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->exportfile = 'Report.xls';
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"pdf"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->inlineNav = true;
$grid->setNavEvent('edit', 'onInitializeForm', $upload);
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
What SQL engine are you using? If it's MySQL you can use:
echo mysql_error();
after running the select to see what error you're having
also try echoing the SELECT statement after generating it to make sure no additional whitespace etc is added to $fid
Related
Unable to change button UI on AJAX getJSON .done
After creating add post to favorite and posted at codereview i had to improve my code as bellow, And after changing code the button UI doesn't change when clicked post_page.php <?php $email = 'user#mail.com'; // Query to get the user_id $stmt = $conn->prepare('SELECT memberID FROM members WHERE email = :email AND active="Yes" '); $stmt->execute(array(':email' => $email)); $row = $stmt->fetch(); $mbid = $row['memberID']; $pid = '4'; // Query to Get the Director ID $stmt = $conn->prepare('SELECT * FROM allpostdata WHERE id =:id'); $stmt->execute(array(':id' => $pid)); $result = $stmt->fetchAll(); foreach ($result as $row) { echo "<p>Director: " . $row['tit'] . "</p> "; $fav_image = checkFavorite($mbid, $pid, $conn); echo "Favorite? : " . $fav_image . ""; } function checkFavorite($mbid, $pid, $conn) { $stmt = $conn->prepare("SELECT * FROM favorite WHERE memberID=:mid AND id=:id"); $stmt->execute(array(':mid' => $mbid, ':id' => $pid)); $count = $stmt->rowCount(); if ($count == 0) { echo "<div class='button btn btn-block btn-outline-danger' method='Like' data-user=" . $mbid . " data-post=" . $pid . "> Add<i class='mi mi_sml ml-2' id=" . $pid . ">favorite_border</i></div>"; } else { echo "<div class='button btn btn-block btn-outline-danger' method='Unlike' data-user=" . $mbid . " data-post=" . $pid . ">Remove<i class='mi mi_sml ml-2' id=" . $pid . ">favorite</i></div>"; } } ?> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <script> $(document).ready(function () { $('.button').click(function (e) { e.preventDefault(); $.getJSON('favs.php', {user_id: $(this).attr('data-user'), director_id: $(this).attr('data-post'), method: $(this).attr('method')}) .done(function (json) { switch (json.feedback) { case 'Like' : $(this).attr('method', 'Unlike'); $(this).html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button break; case 'Unlike' : $(this).html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button'); $(this).attr('method', 'Like'); break; case 'Fail' : alert('The Favorite setting could not be changed.'); break; } }) .fail(function (jqXHR, textStatus, error) { alert("Error Changing Favorite: " + error); }); }); }); </script> favs.php <?php include("$_SERVER[DOCUMENT_ROOT]/include/config.php"); include("$_SERVER[DOCUMENT_ROOT]/classes/function.php"); $method = clean_input($_GET['method']); $user_id = clean_input($_GET['user_id']); $director_id = clean_input($_GET['director_id']); switch ($method) { case "Like" : $query = 'INSERT INTO favorite (memberID, id) VALUES (:mID, :pID)'; break; case "Unlike" : $query = 'DELETE FROM favorite WHERE memberID=:mID and id=:pID'; break; } $feedback = 'Fail'; // start with pessimistic feedback if (isset($query)) { $stmt = $conn->prepare($query); $stmt->bindParam(':mID', $user_id, PDO::PARAM_INT, 12); $stmt->bindParam(':pID', $director_id, PDO::PARAM_INT, 12); if ($stmt->execute()) { $feedback = $method; } // feedback becomes method on success } echo json_encode(['id' => $director_id, 'feedback' => $feedback]); ?> My problem is when button is clicked and when ajax return success the button should change its UI. where else in my case its not changing when on page load it show Add even after clicking on button and ajax return success still it is same.
The problem with your code is $(this) i.e: In ajax success function jquery is not able to find which element is clicked and where to apply required changes. To solve this you can store $(this) in some variable and use the same. Like below : $('.button').click(function(e) { //getting current element which is clicked var button = $(this); e.preventDefault(); $.getJSON('favs.php', { user_id: $(this).attr('data-user'), director_id: $(this).attr('data-post'), method: $(this).attr('method') }) .done(function(json) { switch (json.feedback) { case 'Like': button.attr('method', 'Unlike'); button.html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button break; case 'Unlike': button.html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button'); button.attr('method', 'Like'); break; case 'Fail': alert('The Favorite setting could not be changed.'); break; } }) .fail(function(jqXHR, textStatus, error) { alert("Error Changing Favorite: " + error); }); });
How to change 'active/inactive status of user' through ajax?
I am display list of users in datatable based on 2 parameters through AJAX in codeigniter. I want to change the status of user in database and display in table. I have 3 status 0-> inactive, 1->active, -1->left. I want to change the status and display in datatable without reloading the page. I have tried changing the status but the status is changing only once. After first AJAX call there is no change when i again change the status. //view <script> $(document).ready(function() { $('#academicTable_wrapper').hide(); $('#studentTable').DataTable(); showStudents(); function showStudents() { $('#submitBtn').on('click',function(){ var courseId = $('#courseId').val(); var classId = $('#classId').val(); $.ajax({ type : 'POST', url : "<?php echo base_url();?>Student/getStudentsList", // async : true, data : {courseId:courseId,classId:classId}, dataType : 'json', success : function(data){ //alert(data); var html = ''; var i; for(i=0; i<data.length; i++){ var studentId = data[i].studentId; if(data[i].status == 1) var status = "Approved"; else if(data[i].status == 0) var status = "Pending"; else var status = "Left"; html += '<tr>'+ '<td>'+data[i].studentId+'</td>'+ '<td>'+data[i].studentName+'</td>'+ '<td>'+data[i].studentPhoneNum+'</td>'+ '<td>'+data[i].created_on+'</td>'+ '<td id="changeStatus">'+status+'</td>'+ '<td>'+ 'View'+ ' '+ '<a id="activateBtn" data-id="'+data[i].id+'" data-status="'+data[i].status+'" class="btn btn-primary btn-sm text-white">Activate/Deactivate</a>'+ ' '+ 'Delete'+ '</td>'+ '</tr>'; } $('#studentTable').DataTable().destroy(); $('#showData').html(html); $('#studentTable').DataTable(); $('#academicTable_wrapper').show(); } }); }); } $(document).on('click','#activateBtn',function() { var id = $(this).data('id'); var status = $(this).data('status'); $.ajax({ method: 'POST', url: "<?php echo base_url();?>Student/approveStudent", data:{id:id,status:status}, success : function(data) { alert(data); $('#changeStatus').text(''); if(data == 0) { showStudents(); $('#changeStatus').html('Inactive'); } else{ showStudents(); $('#changeStatus').html('Approv'); } }, error:function(data) { console.log(data); } },1000); }); }); </script> //controller function approveStudent() { $id = $this->input->post('id'); $status = $this->input->post('status'); $col = 'id'; $query = $this->Admin_model->activate($col,$id,$status,$this->studentDetail); if($query){ $result = $this->Admin_model->getData($col,$id,$this->studentDetail); } $status = 1; if ($result[0]->status == 0) { $status = 0; } echo $status; } I expect whenever I click activateBtn the status should change in database and also in datatable.
codeigniter foreach not displaying all records in table
Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything. It's simply a chat system I implemented allowing users to send messages to one another. Everytime a new record is inserted, the latest record does not show up but the previous ones do. Please see my code attached with this. Thank you. Controller - Chats.php public function ajax_get_chat_messages() { echo $this->_get_chat_messages(); } public function _get_chat_messages() { $recipient = $this->input->post('recipient'); $chat = $this->Chats_model->get_chat_messages($recipient); if($chat->num_rows() > 0) { $c_html = '<ul>'; foreach($chat->result() as $cht) { $c_html .= '<li>'.$cht->username.'</li>'; $c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>'; } $c_html .= '</ul>'; $result = array('status' => 'ok', 'content' => $c_html); return json_encode($result); } } JS - Chat2.js $(document).ready(function () { setInterval(function () { get_chat_messages();}, 2500) function get_chat_messages() { $.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) { if (data.status == 'ok') { $("div#view").html(data.content); } else { //there was an error do something } }, "json"); } /*function get_chat_messages() { $.ajax({ type: "POST", dataType: 'json', url: base_url +"user/chats/ajax_get_chat_messages", data: {recipient: recipient}, // pass it as POST parameter success: function(data){ $("div#view").html(data); console.log(data); } }); } */ get_chat_messages(); }); model - Chats_model.php public function get_chat_messages($recipient) { $session = $this->session->userdata('user_id'); $query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC "; $result = $this->db->query($query, array($recipient)); return $result; } Image also attached
Flask-Admin: How to filter selectable data of a field based on values entered in the previous field, with search conditions in another table
in flask-admin model view I want to filter a dropdown menu in the edit/create view of field that is a relationship, based on values entered in the previous field. In the specific case, I would like to see only the ones in the "posto" that are displayed in another table belonging to the selected 'categoria' class Tag(db.Model): __tablename__ = 'tags' nr_TAG = db.Column(db.Integer, primary_key=True) categoria_id = db.Column(db.Integer, db.ForeignKey('categorie.id'), nullable=False) categoria = db.relationship('Categoria', backref='tags') posto_id = db.Column(db.Integer, db.ForeignKey('stalli.id'), nullable=False) posto = db.relationship('Stallo', backref='tags') cognome = db.Column(db.String(30), nullable=False) nome = db.Column(db.String(30)) auto = db.Column(db.String(20)) targa = db.Column(db.String(10)) recapito = db.Column(db.String(80)) stato = db.Column(db.Integer) posto_occ = db.Column(db.Integer) orario = db.Column(db.Integer) fuoriposto = db.Column(db.String(10)) parcheggio = db.Column(db.String(40)) class TagsAdmin(sqla.ModelView): can_edit = True can_create = True column_list = ['nr_TAG', 'categoria', 'posto', 'cognome', 'targa', 'stato', 'orario', 'fuoriposto', 'parcheggio'] can_view_details = True details_modal = True form_columns = ['nr_TAG', 'categoria', 'posto', 'cognome', 'nome', 'auto', 'targa', 'recapito'] Any idea? Thanks
I came up with following solution, maybe it's not perfect but it does the job: master.html function populateSelectField(to_populate, options, select) { $('#s2id_' + to_populate + ' > a > span').text(''); var el = $('select[name$="' + to_populate + '"]'); el.children().remove(); option = '<option value=""></option>'; el.append($(option)); options.forEach(function(row) { var option_id = row.id, option_title = row.title; if (select && option_id == select) { option = '<option value="' + option_id + '" selected>' + option_title + '</option>'; $('#s2id_' + to_populate + ' > a > span').text(option_title); } else { option = '<option value="' + option_id + '">' + option_title + '</option>'; } el.append($(option)); }); } function getOptions(el, to_populate, url, select) { var item_id = el.val(), url = window.location.origin + url + item_id + '/'; $.get(url).done(function(options) { populateSelectField(to_populate, options, select); }).fail(function(err) { console.error(err.message); return false; }); } function selectFieldManipulation(from_populate, to_populate, url) { var main_select = $('select[name$="' + from_populate + '"]'), to_populate_el = $('select[name$="' + to_populate + '"]'); getOptions(main_select, to_populate, url, to_populate_el.val()); main_select.change(function(e) { getOptions(main_select, to_populate, url, null); }); } create.html / edit.html $(document).ready(function() { selectFieldManipulation('from_populate', 'to_populate', '/api/route_to_view/'); });
laravel ajax post doesn't return values
I am trying to perform ajax post in laravel. I have a controller "show_freeCars" awich gets some values from ajax post and performs the query to return the results. I have this: public function show_freeCars() { $starttime = Input::get('starttime'); $endtime = Input::get('endtime'); $enddate = Input::get('enddate'); $startdate = Input::get('startdate'); $classes = Input::get('classes'); $free_cars = DB::select('SELECT * FROM cars WHERE id NOT IN (select distinct c.id from cars as c ' . 'left join rentals as r on c.id = r.vehicle ' . 'where STARTTIME="' . $startdate . ' ' . $starttime . '" ' . 'AND ENDTIME="' . $enddate . ' ' . $endtime . '" ' . 'AND (r.status="REZERVATION" OR r.status="CHECK_OUT") ' . 'order by c.id) AND class= "' . $classes . '" '); if (Request::ajax()) { $response_values = array( 'success' => 1, 'values' => $free_cars, ); return Response::json($response_values); } else { dd('error'); } } and javascript jQuery('#form-reservation').submit(function() { var startdate = $('input[name$="startdate"]').val(); var starttime = $('input[name$="starttime"]').val(); var enddate = $('input[name$="enddate"]').val(); var endtime = $('input[name$="endtime"]').val(); var classes = $('input[name$="classes"]').val(); var url = $(this).attr("action"); jQuery.ajax({ url: url, type: "post", data: { startdate: startdate, starttime: starttime, enddate: enddate, endtime: endtime, classes: classes }, datatype: "json", beforeSend: function() { jQuery('#ajax-loading').show(); } }) .done(function(data) { $('#cars_table').empty() if (data.success === 1) { var arr = data.values; alert(arr); } else { window.location = data.redirect_to; } }) .fail(function(jqXHR, ajaxOptions, thrownError) { alert('Invalid Data'); }); return false; }); It alerts an empty. But if i remove the lines $classes = Input::get('classes'); and AND class= "' . $classes . '" ' from controller it shows the results. The query is ok because I tested it with dd($free_cars) and it displays the list of cars. Just something is messed with ajax return values. Why it returns null?