I'm using jqGrid PHP and adding an actions column.
The editing works fine but once the row is saved, the grid is not reloaded.
When I manually refresh the grid, the updated information appears.
I have tried adding edit options to the addCol (see below) but I read somewhere that editOptions only applies to form editing. Looking at the documentation, it seems like I could use the onSuccess or afterSave parameters but I am not sure how I would add the reloadAfterSubmit method to either of those parameters in PHP.
$grid->addCol(array(
"name"=>"Click to Edit",
"formatter"=>"actions",
"editable"=>false,
"sortable"=>false,
"resizable"=>false,
"fixed"=>true,
"width"=>45,
"loadonce"=>false,
"formatoptions"=>array("keys"=>true, "editbutton"=>true, "delbutton"=>false,"editOptions"=>array("reloadAfterSubmit"=>true))
), "first");
I'm using jQuery and jqGrid's cell editing feature which submits the new cell value to the server when leaving each cell. In my particualr app, when a cell changes it can affect other (calculated) columns in the same row AND possibly in other rows therefore I needed to update values which could be all over the grid.
In my case, the calculation itself is performed on the server when the cell is submitted and the database is updated so I needed to fetch the updated data to update the grid. I wanted to make the cell editing as fast as possible but also keep the rows updated. I also wanted to only update the rows that have been modified as determined by the server. I also wanted something that was generic and reusable.
I don't know how this translates to PHP but here's what I did in JavaScript.
var xhrUpdate = null;
// Handle jqGrid's afterSubmitCell.
$("#someGridId").jqGrid(
"setGridParam",
"afterSubmitCell",
function (response, rowid, name, val, iRow, iCol) {
// If an ajax request is already in progress from the last cell edit,
// abort it since the data is now moot with the new cell update.
// Sorry server, nobody's listening!
if (xhrUpdate != null) {
xhrUpdate.abort();
xhrUpdate = null;
}
// Call the generic grid update function (see below) asynchronously.
xhrUpdate = updateGrid(
"someGridId",
"someUpdateUrl",
{ someParam: someParamValue, ... },
"someIDFieldThatIdentifiesTheGridRow",
true);
// Return success.
return [true, ""];
});
// This function updates a jgGrid which already contains data.
// It will only update the rows and columns that are returned
// from the server.
function updateGrid(grid_id, url, data, idField, async) {
var grid = $("#" + grid_id)
return $.ajax({
async: async,
type: "GET",
datatype: "json",
url: url,
data: data,
success: function (result) {
// Loop over the returned rows.
$.each(result, function (index, row) {
// Loop over the returned fields in each row.
$.each(row, function (key, value) {
// Set the corresponding cell value.
// This won't touch any cell's that aren't
// represented in the JSON data.
grid.jqGrid("setCell", row[idField], key, value);
});
});
}
});
}
Things to note:
1) This definitely puts a load on the server.
2) Being asynchronous, this doesn't deal with bad cell data or other abnormal server responses from the cell submit. It very optimistic but those issues can be dealt with if need be.
3) The server needs to have the smarts to return the appropriate data or you can just return everything.
Sorry it's not PHP but I hope this helps.
Related
Based on the user input's, i calculate some values on my submit action of my form. I have to persist these values in my backend DB. I use PHP for my server side scripting. Please let me know the best practice for doing this. It is a single page application and i use .load("Report.html"); to show the summary page.
Just thinking aloud, can i fetch the row(to be updated) from DB, json_encode, update the json object in jQuery, decode it, then update in DB?
Please help...
My submit button code...
$('form').on('submit', function(event)
{
event.preventDefault();
//CALCULATE SCORE
var noOfCorrectAnswers = 0;
var noOfQuestionsViewed = 0;
$.each(questionsArray, function(i, item)
{
if(item.correctOption == item.selectedAnswer)
{
noOfCorrectAnswers++;
}
if(item.isQuestionViewed == 'YES')
{
noOfQuestionsViewed++;
}
});
alert(noOfQuestionsViewed);
$('#sampleDiv').load("UserReport.html");
});
Run some AJAX passing all of the information you need (which may even be none depending on your use case) from the client-side to your server-side PHP. Your PHP script can fetch things from the database if necessary, make any calculations and/or manipulations and then store the information back in the DB.
If you need to return information to your client-side after updating the database then try returning a JSON object (by just printing the code out in the proper format) from your PHP script before exiting with whatever your JS needs.
Do note that this should be all done asynchronously, so you need to setup your AJAX callback function to handle any information that's returned from your PHP script. If you want to do it synchronously, go for it - but you asked for best practices :P
Looks like you're using jQuery - here's the documentation on AJAX
Raunak Kathuria's answer provides some same code
On form submit make ajax call to set database in the db and access the json
$('form').on('submit', function(event)
{ ...
alert(noOfQuestionsViewed);
$.ajax({
url: "yourphp.php", // php to set the data
type: 'POST',
data: 'yourparams', // all the input selected by users
dataType: json
success: function(json){
//here inside json variable you've the json returned by your PHP
// access json you can loop or just access the property json['sample']
$('#sampleDiv').load("UserReport.html", function () {
// its callback function after html is loaded
$('#someid').html(json['sample'));
});
}
})
You can also use the done callback of ajax
PHP
yourphp.php
Set the values here in db running the desired query and return values using
<?php
// your db ooperations will come here
// fetch the db record
// return the db records in json
$responseVar = array(
'message'=>$message,
'calculatedValue'=>$calculated
);
echo (json_encode($responseVar));
?>
On this page...
http://lab.2toria.com/reflex/index2.php
When the user has dragged and dropped blocks onto the grid, I want to be able to send the positions in some form to a php script that will save them into a table that simply records the coordinates (eg "x1y2", "x1y3", etc) into rows. The fields in my table so far are VERY simple (blockID, blockCoords)
What would be the best way to do this? I'm after your opinion on two things:-
1) Using jQuery ajax, how could I send a string containing the coordinates as a list? Would it be best to create an xml string, or is there another way I've not thought of...and how would I do this
and..
2) Based on the method used to send the data (xml, or whatever), how would I then process the data in the receiving php script to save the data into a table. I know how to save records etc, just wanting to know how best to deal with this situation.
$('element').droppable({
drop:function(event, ui){
$.ajax({
url: '/path/to/my/file.php',
type: 'POST',
data: {'left' : ui.helper.position().left,
'top': ui.helper.position().top},
success: function(data){
//do something with the response from the server
}
});
}
});
And in /path/to/my/file.php
if(isset($_POST['left'])):
$db = new mysqli('connection info here');
$q = $db->prepare('INSERT INTO some_table (left, top) VALUES (?,?)'); //prepare the statement
$q->bind_param('ss', $_POST['left'], $_POST['top']); //safe binding
if(FALSE !== $q->execute()):
return 'Query Executed!';
endif; //execute the statement
return false;
endif;
So in the php file we're simply checking for the existence of the $_POST variable left. We assume top will be available also. We make a mysqli connection, prepare a safe statement, bind the parameters as strings, using the $_POST left/topvalues. Then we check if the execution didn't return false (returns true/false), and if it didn't, we pass a value and exit out of the conditionals all together. If not, the return false will fire by default.
Edit
From your comment, you want to save the actions that the user performs until ready to actually perform the insert, that's easily doable as well.
var dc = 0,
drops = {};
dc will be the dropcount, and drops will be an object.
$('element').droppable({
drop: function(event, ui){
drops[dc] = {'left' : ui.helper.position().left, 'top' : ui.helper.position().top};
dc++;
}
});
In the above, we simply increment through the drops object, storing the information for the left/top values on each drop.
$('.save').click(function(e){
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: {'drops': drops},
success: function(data){
console.log(data);
}
});
});
Here, we have a save button with a class of save, we prevent the default action, then we sent the drops object to the server.
if(isset($_POST['drops'])):
//same process as outlined above, use a helper function to insert the rows
endif;
Now we check for the existence of the $_POST variable 'drops', we'll employ the same tactics as above. I would simply recommend a helper function saveDrops($obj), iterating the returned drops and performing a save for each obj passed in.
1) Yep, use jQuery ajax posting the coords and block id.
2) They will be available to php in the $_POST variable.
See:jQuery Post
I have a PHP page that processes some information when a button is pressed. One of this information is to process a query. I then want the results of the query to be put into a table in another page. I know how to put query results into a table, but I don't know how to pass them row by row to a table on another page. Can anyone help or point me in the right direction?
If I understood this correctly, you'll need AJAX (and, by requirement, JavaScript) for this. What you want to do is call your generation function and have it return a format that you can parse (JSON, XML, you name it).
From there, you'll append it to your table using JavaScript's DOM manipulation functions.
The generation part
Assume that you're getting your data in an array format as follows:
$row = array('column 1','column2');
You'll be getting tons of rows like these, or just one - we'll write the script to handle both cases without requiring a rewrite. Every time you get a row, add it to a non-associative array , call it $RowArray. So, on every row, you'll be calling $RowArray[] = $row;.
You now have the PHP side almost done - all you need to do now is to echo it back to the client. Make sure you echo nothing else but this: echo json_encode($RowArray);. This will format and serialize your array to be a perfect JSON object.
The JavaScript side
We'll assume jQuery for simplicity. Your aim will be to read the JSON object and add rows to a table. We'll assume that the table has ID #MyTable.
The AJAX call is done as follows:
$.ajax({
url: "your_url.php",
dataType: "json",
type: "post",
success: function(d) {
// Your code here
}
});
The success handler will be triggered when the object has been successfully parsed, and the variable d will be the object. This object will be a JavaScript array where each element is an object. All you need to do now is to loop through d and create a row per entry!
success: function(d) {
for(var i=0; i < d.length; i++) {
var newRow = $("<tr></tr");
for (var k in d[i]) {
newRow.append($("<td></td>").text(d[i][k]));
}
newRow.appendTo($("#MyTable"));
}
}
Voila, dynamic AJAXified table in six lines!
My page loads super slow right now. Basically, i want to pre-populate the combo boxes that i have. Right now, it pre-populates each one individually and then selects the default value. This is so slow. The user will have to wait about a minute before the page is fully loaded.
I'm grabbing the values to populate the combo boxes from a server. The values to pre-select the combo box value are received in an array through the response variable. How do i speed this whole process up?
Code is below:
EXTJS
xtype: "combo",
width: 250,
id: "nameId",
name: "comboName",
labelStyle: 'width:100px',
fieldLabel:"Name",
allowBlank: true,
displayField: "nameDisplay",
valueField: "nameValue",
url: "/thelink/toGetAllComboboxValues/fromPHPFile/",
return {
init: function (args) {
formPanel.on({
beforerender: function () {
Ext.Ajax.request({
url: 'url/to/another/PHP/file/',
scope: this,
method: 'GET',
params: {
code_id: 'myUser',
number: '12345'
},
success: function (response, opts) {
var result = Ext.decode(response.responseText);
Ext.getCmp('nameId').setValue(result.Name);
},
});
},
scope: this
});
//add form panel here
},
getFormPanel: function () {
return formPanel;
},
// load parameter values into the form
loadParams: function () {
},
goHome: function () {
},
};
}();
PHP TO GET COMBO BOX VALUES
//makes call to server for each individual combo box values
PHP TO GET PRE-SELECTED VALUES
//grabs all pre-selected values based on an ID and puts them in an array
If your stores each has less than about 300 records, and there aren't really 'that' many stores on your page, what you should do is return everything from the php at once (or more preferably load all the stores with the page load itself, but it sounds like you can't do that). So, instead of your one ajax call getting the values of the selected item in the combobox, think of it more like this:
Defined your models for each of the stores:
Ext.define("MyModel1", {
extend: "Ext.data.Model",
fields: [
{name:"field_code", type:"string"},
{name:"field_value", type:"string"}
]
});
Then define each of your stores in a very simple manner, notice that I left out the reader and proxy that you are probably currently including, for improved performance, use Ext.data.ArrayStore because it removes the necessity for each item in a record to have a named attribute (this reduces the text returned from the server and also the parsing time on the frontend):
var myStore = Ext.create("Ext.data.ArrayStore", {
model: "MyModel1",
data: []
});
Now in the ajax request that you already defined, add in the response from php all the data for the stores as attributes in the json object returned, and do them as array arrays making sure the element order matches how you defined the Ext.data.Model. The return object for my example would look something like this (the data is the array array):
{
my_combobox_value1: "CAD",
my_combobox_data1: [
["CAD","Somthing for display of this record"],
["AN","Another Entry]
]
}
Then change the ajax request to look something like this:
Ext.Ajax.request({
url: 'url/to/another/PHP/file/',
scope: this,
method: 'GET',
params: {
code_id: 'myUser',
number: '12345'
},
success: function (response, opts) {
var result = Ext.decode(response.responseText);
myStore.loadData(result.my_combobox_data1);
Ext.getCmp('nameId').setValue(result.my_combobox_value1);
... and rinse and repeat for all stores, make sure you set the value for each combobox after the store has been loaded :)
},
});
This will give you the best possible performance for you situation. If this does not work, you will have to use stores with proxies that handle everything on the server side and load data as needed.
First, I'd recommend not retrieving the full value list for each combo until the user needs it (either when changing the value or clicking the trigger). You can do this by giving your combo a store that is set up with a Proxy to your URL.
In order to save on the initial single-values displaying, one option would be to store the string value as well as the id in your record (or maybe not store it, per say, but send it down to the client anyway). However, this isn't that nice, and the load time may be fast enough after getting rid of the full list requests. If it isn't, try seeing if you can request ALL the single value displays in one request.
I have a jquery/php voting system I'm working on. Once a user clicks a vote button a jquery modal pops open and they must confirm their vote by clicking "Confirm". This will send an ajax request to update the database and what not. After clicking confirm the modal will close. I would like to be able to update the number of votes dynamically on the page. I can easily grab that data from the mySQL table. My question is how does this get sent back for me to then update the html page dynamically?
Currently the page does nothing, so to the user it doesn't look like they've voted. Ideally I'd want to update the total number of votes and also inject an image that shows what they voted for.
function vote(el, id) {
$.ajax({
type: 'POST',
url: '/path/morepath/',
dataType: 'json',
data: {
'action': 'castVote',
'vote': id
},
success: function (data) {}
});
$.modal.close();
}
On the server side, respond to the POST request with a JSON object containing the number of votes and possibly the image path.
Then inside the AJAX callback, data will be that object. Then you can use jQuery to select an element in the DOM and call .text() or .html() on it to update the content.
If you're passing poorly formed data back from PHP, you can make it a bit better by giving it some structure and then making it json for javascript's ease-of-use:
$sqlResult = ...;
$responseArray = array();
$responseArray['result'] = true; //or false if it failed
$responseArray['data'] = $sqlResult;
print json_encode($responseArray);
Before you can really expect the page to respond properly to an ajax response, you must be sure your response data is being parsed correctly.
Inside of your success function, try console.log'ing your response to see what it looks like
console.log(data);
if there is something you can reference in the return data that is reliable, do a check for it:
success: function(data) {
if(data.result == 'true') {
$('someElement.someClass').someFunction();
}
}
You can change the value or html content of the voting number using a few different options such as:
...
success: function(data)
{
var $newTotal = ...//get total from data
$('voteCountContainer').html($newTotal); // or you can also use .val() if it's an input
}
...
Hope that helped,
Dan