i have some problem that using jqgrid as jquery framework.
In my case, i have some table which is CRUD function that connect to a table let say departments
in this table there are two id: idms_department, department (name). The idms_department is auto increment column.
here's my jqgrid syntax
$(document).ready(function() {
//alert("start");
jQuery("#departments").jqGrid({
mtype:'GET',
url:'functions/get_dept.php',
editurl:'functions/edit_dept.php',
datatype: "JSON",
colNames:['Department ID','Department'],
colModel:[
{name:'idms_department',index:'idms_department', width:150, editable:false, key:true},
{name:'department',index:'department', width:800,editable:true}
],
loadComplete: function () {
alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
rowNum:10,
rowList:[5,10,15],
pager: '#pager-departments',
sortname: 'idms_department',
viewrecords: true,
jsonReader: {repeatitems: true, idms_department: "idms_department" },
sortorder: "asc",
caption:"MSC Departments"
});
jQuery("#departments").jqGrid('navGrid','#pager-departments',{edit:true,add:true,del:true},{closeAfterEdit:true},{closeAfterAdd:true},{},{closeAfterSearch:true},{});
jQuery("#departments").jqGrid('gridResize',{minWidth:350,maxWidth:850,minHeight:80, maxHeight:350});
//alert("end");
//start navigation system
$('#navigation-bar').collapsible({
effect: 'none',
initialCollapse: true
});
//end navigation system
});
i can add new data using add dialog in jqgrid, but when i want to edit the form, it doesn't editable.
The problem is the id i think. Before, the editable for idms_department is set to editable:true, the working fine, but when i make it editable:false, because, the user can't add new id himself, so i make it editable:false, and the row is gone from dialog.
I have get response from my firebug, it shows that the function is sending the right data, but, the data is unchanged.
The function of edit php goes here:
if($oper == 'edit'){
$deptid = $_POST['idms_department'];
echo $deptid;
$deptnm = $_POST['department'];
$upt = "UPDATE ms_department SET idms_department = '$deptid', department = '$deptnm' WHERE idms_department = '$deptid'";
if(mysql_query($upt)){
"Edited Successfully";
} else {
die("Error Edit : " .mysql_error());
}
mysql_close();
}
is there anything wrong?
jaGrid send rowid as id, but you use
$deptid = $_POST['idms_department'];
and later WHERE idms_department = '$deptid'" in the UPDATE. You have to change the above statement to
$deptid = $_POST['id'];
or to use prmNames: {id: "idms_department"} option of jqGrid to rename "id" variable which will be sent during editing to "idms_department".
Related
I have a calendar.php file which looks up "php/get-events" to display calendar events from the database (This currently works as expected). I am trying to use "php/calendarupdate" to then update the database with the new start/end times that have been dragged, but the data posting to this page always comes back as undefined, so it's not finding it for some reason.
"Calendar.php"
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
initialDate: '2021-03-18',
editable: true,
eventDrop: function(event, delta) {
start=moment(event.start).format('Y-MM-DD HH:mm:ss');
end=moment(event.end).format('Y-MM-DD HH:mm:ss');
$.ajax({
url: 'php/calendarupdate.php',
data: 'title=' + event.title + '&start='+ event.start +'&end=' + event.end + '&id=' + event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
},
navLinks: true, // can click day/week names to navigate views
dayMaxEvents: true, // allow "more" link when too many events
events: {
url: '/php/get-events.php',
failure: function() {
document.getElementById('script-warning').style.display = 'block'
}
},
loading: function(bool) {
document.getElementById('loading').style.display =
bool ? 'block' : 'none';
}
});
calendar.render();
});
</script>
The following is where I get the data which successfully displays events on the calendar.
"php/get-events.php"
$stmt = $pdo->prepare("Select id,task_name,start,end,notes,task_type,status from tasks where attendees like ".$attendees);
$stmt->execute();
//$stmt->debugDumpParams();
foreach ($stmt as $row){
$rawdata[] = array('id' => $row['id'], 'title'=> $row['task_name'], 'start'=> $row['start'], 'end'=> $row['end']);
}
$rawdata = json_encode($rawdata);
echo $rawdata;
The following is the update file, which it is getting into ok, but the echo's I try to display are all undefined.
/* Values received via ajax */
echo "id -".$_POST['id'];
echo "start -".$_POST['start'];
echo "end -".$_POST['end'];
// update the records
$stmt = $pdo->prepare('UPDATE tasks SET start=?, end=? WHERE id=?');
$stmt->execute($_POST['start'], $_POST['end'], $_POST['id']);
$stmt->debugDumpParams();
It may be something simple, but from the documentation I've read, I can't seem to figure out why my variables are not posting successfully. Thanks.
You have the wrong syntax for your eventDrop signature. See https://fullcalendar.io/docs/eventDrop
It should be
eventDrop: function(info) {
And then replace
event.start
and
event.end
with
info.event.start
and
info.event.end
This will get the information you need correctly from the data which fullCalendar supplies.
I am using this rateyo plugin in my application. There is a page where user can give rating to an entity. But before giving rating I am making a check, if that user already assigned a rating to that particular entity and if the user does, then I fetch rating value from database and set it as the plugin says. But if it is a new user, he can submit his new rating.
here is the code what I am implementing:
$(document).ready(function(){
$("#rateYo").rateYo().on('rateyo.set',function(e, data){
$.ajax({
type : "post",
url : "PostRatingValue.php",
data : {
"rating" : data.rating,
"peopleid" : celeb_id,
"userid" : user_id
},
dataType : "json",
success : function(response){
if(response.toString() == "true"){
$.growl.notice({ title: "Growl", message: "Rating<b> "+ data.rating +" </b>assigned successfully" });
}
else{
$.growl.error({ message: "<b>Unable to assign rating.</b>" });
}
},
error : function(response){
$.growl.error({ message: "<b>Something went terribly wrong! :'(.</b>" });
}
});
});
below is the code to set the rating value if it exist.
<?php
if(isset($fetchRatingIdAndValue['ratingpoints'])){
?>
$("#rateYo").rateYo("option", "rating", <?php echo $fetchRatingIdAndValue['ratingpoints'];?>);
<?php
}
?>
});
Problem is that, when old rating is set, an ajax call is made which inserts same data again in table. I want my ajax call to work only when I need to set new rating or edit previous rating. I am not able to find the way out for this. Please help.
When you set the rating after Initialization of rateyo, rateyo.set event will be fired on the element.
Please do not do that, instead If already old rating exists, pass it during initialization itself like
$(document).ready(function(){
$("#rateYo").rateYo({
rating: <?php echo $fetchRatingIdAndValue['ratingpoints'];?>
}).on('rateyo.set',function(e, data){
$.ajax({
type : "post",
url : "PostRatingValue.php",
data : {
"rating" : data.rating,
"peopleid" : celeb_id,
"userid" : user_id
},
dataType : "json",
success : function(response){
if(response.toString() == "true"){
$.growl.notice({ title: "Growl", message: "Rating<b> "+ data.rating +" </b>assigned successfully" });
}
else{
$.growl.error({ message: "<b>Unable to assign rating.</b>" });
}
},
error : function(response){
$.growl.error({ message: "<b>Something went terribly wrong! :'(.</b>" });
}
});
});
});
$fetchRatingIdAndValue['ratingpoints'] should contain 0 if user has not given any rating previously.
I am trying to create a simple AJAX/PHP chat application to enable communication between registered users on a website. The problem with it is storing the chat history. I thought of storing all the chat messages in a single database (with columns like user1, user2, message, time), and then at every AJAX request, search the database for a matching message between the users, but I think this might be extremely inefficient. Is it a good idea to implement it this way, and what are some good ways of handling this?
Since a chat room has to constantly get updates, I wanted to minimize the requests to a minimum, so I just labeled each message with the database id. Since every user can see all the messages for that room, the request is just sending the id to the server to see if there were any new posts. If there were, it returns the new posts and updates the page.
Here's the JavaScript that I use:
var csrf = $("input[name='csrf_test_name']").val();
load_messages();
load_users();
$("#submitbutton").click(function(){
var message = $("#content").val();
$.post(base_url + "index.php/chat/ajax_post", {
text: message,
csrf_test_name: csrf
});
$("#content").attr("value", "");
return false;
});
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "index.php/chat/ajax_retrieve",
type: "POST",
data: {
last: last,
csrf_test_name: csrf
},
cache: false,
success: function(html){
if(html.substr(1, 1) == 'p'){
var oldscrollHeight = $("#messagewindow").prop("scrollHeight") - 20;
var id;
var tag;
var user;
var uid;
//remove messages that exceed the max - determined on the server side
$('#messagewindow p:lt(' + $(html).siblings().size() + ')').remove();
//add messages, emoticons and classes based on whether its the user or someone else
$(html).find('b').each(function(){
if ($(this).html() == user_name + ':'){
$('#messagewindow').append($(this).parent().emoticons(base_url + 'images/emoticons').attr('class', 'self'));
} else {
$('#messagewindow').append($(this).parent().emoticons(base_url + 'images/emoticons').attr('class', 'others'));
}
});
//scroll screen
var newscrollHeight = $("#messagewindow").prop("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#messagewindow").animate({ scrollTop: newscrollHeight }, 'normal');
}
$(html).find('span').each(function(){
id = $(this).attr('id');
uid = 'u' + id.substr(1);
if (id.substr(0, 1) == 'e' && $('#userwindow p[id="' + uid + '"]').size() < 1){
user = $(this).prev().html();
tag = "<p id='" + uid + "'>" + user.substr(0, user.length - 1) + "</p>";
$('#userwindow').append(tag);
} else if(id.substr(0, 1) == 'x') {
$('#userwindow p[id="u' + id.substr(1) + '"]').remove();
}
});
}
}
});
}
function load_users(){
$.ajax({
url: base_url + "index.php/chat/ajax_users",
cache: false,
success: function(html){
if(html.substr(1, 1) == 'p'){
$("#userwindow").html(html);
}
}
});
}
setInterval(load_messages, 2000);
setInterval(load_users, 240000);
What would be wrong with your method?
Use the proper MySQL indexes on your table (I would say on the two columns user1, user2 and on timestamp or unique ID for the order) and the performance will be good enough.
You can add the curent timestamp to the AJAX request to retreive only message that you didn't loaded the call before.
So I have yet another problem,
I am trying to get an AJAX script to work, but upon click the page will reload but fail to UPDATE the database field.
The code im using I have working for other similar scripts on the site but for some reason this one, using the same code doesnt work, the code used follows below;
HTML code to send the call to AJAX:
<input onClick="read('<? echo $id; ?>')" id="read" name="read" type="checkbox" value="1" style="position:relative; top:2px; width: auto">
The code to confirm user selection and send onto a form handling file:
function read(ID) {
if(confirm('Are you sure you have read this carefully, you will not be alerted again "' + ID + '" ?')) {
$.get('http://<? echo ROOT . ADMIN . INCLUDES; ?>formHandling.php', { read: ID }, function(data) {
window.location.href = 'http://<? echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].""; ?>';
});
}
return false;
}
Lastly the code to handle the SQL query:
if (isset($_GET['read'])) {
// Pass the GET data and associate them to variables
$read = trim($_GET['read']);
$query = "UPDATE cms_motd SET read='$read' WHERE id='1'";
$result = mysql_query($query)or die("Database query died: " . mysql_error());
unset($_GET['readConfirm']);
}
Thanks in advance for all that help.
Regards,
Dan.
Don't you mean:
$query = "UPDATE cms_motd SET read='1' WHERE id='$read'";
Instead of:
$query = "UPDATE cms_motd SET read='$read' WHERE id='1'";
Edit:
I don't know if it is a copy&past error:
$result = mysql_query($query);or die("Database query died: " . mysql_error());
Needs to be:
$result = mysql_query($query) or die("Database query died: " . mysql_error());
I have some challenges with the fact that you do the query but don't give your code any feedback to continue. For example, what if the query fails? Do you just press on?
Here's how I handle these sort of Ajax transactions (yes, longhand!)
$('#read').click(function() {
$("#div").dialog({ //Shows dialog
height: 250,
width: 450,
modal: true,
buttons: {
"Cancel": function() {
$( this ).dialog( "close" );
},
"Save": function() {
$.ajax({
url: "url.php", //
timeout: 30000,
type: "POST",
data: $('#form').serialize(),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(data){
$('#updatediv).html(data.stuff);
src="web/imgs/icons/24deleteB.png"></td>';
}
$( this ).dialog( "close" );
}
}
});
});
Now, the URL.php will do the query and return a json_encoded string back to the AJAX that will then be able to know if the transaction was succesful via the success/error functions. You could do additional conditioning on the success case to ensure that something was saved a particular way or that a result matched a case that you wanted it to before doing something. On success, I show just a simple .html inner html type action, but you could do any quantity or variety of things such as show/hide, inner html, etc. The choice is yours. Also, note that I use Jquery UI dialogs instead of system dialogs, so you'd need Jquery UI to make it look pretty if you used this verbatim. Finally, rather than onclick note that I'm using the .click functionality that Jquery provides, which is just a hair cleaner.
I have a problem with following script. It generates a list of places which are editable, deletable or you can even create a new one.
I want to send a $.post request when creating a new place to a php file which makes an entry into a database (MySQL) and then lists this entryes in html. Now why doesn't even the $.post send an alert message to notifi me that the data is been send?
The script isn't finished yet how you can see, but it would be great if you could give me a hand!
JS-Script
$(function() {
$(".edit").click(function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").click(function() {
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none");
});
$(".save").click(function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
alert("save name: "+myvariable1+" save id: "+myvariable2);
});
$(".delete").click(function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").click(function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place_list.php", {action: "create", name: myvariable4}, function(data){
alert("Data Loaded: " + data);
},"html");
alert(myvariable4);
});
});
PHP-File
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>New</button>";
?>
Have you got firefox and firebug installed?
If so you can view the net tab and see if the post request gets made to place_list.php and also what the response is. I suspect it is 404'ing as the path maybe incorrect. You can always use the .ajax method rather than .post. This allows you to specify an error method that gets called upon a failed ajax request.
e.g
$.ajax({
url : "place_list.php",
data : {action: "create", name: myvariable4},
cache : false,
error : function(XMLHttpRequest, textStatus, errorThrown){
//console.log or alert error
alert(errorThrown);
},
success: function(html){
alert("Data Loaded: " + data);
}
});