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
Related
What I know is how to download and upload data from the database.
But how do I control, whether a data has been uploaded on the database? And if a data has been uploaded, I want to know how to get this data to put this to the listview without reloading the whole database again?
In other words I want to have the new written text in the listview in real time, like a messenger.
Piggybacking off of #CptMisery's answer here, I agree that ajax would be useful for this.
I use this quite often when I'm writing to a database - as a form of callback to ensure data was actually written. First, here's the code you'd execute in JavaScript:
$.ajax({
type: 'POST',
url: 'some_php_page.php',
data: { data:data },
success:function(data){
if ( data == 0 ) {
console.log("item has been updated");
} else {
console.log("item has NOT been updated");
}
}
}); //close ajax
What this does is the ajax call sends the variable data as a POST to your some_php_page.php. You can send multiple items like this: data: { data:data, variable1:variable1, age:age, date:date }. The PHP page does something, (e.g. - writes to the database), and if it's successful, you have PHP echo "0", otherwise you have it echo "1". The ajax success call happens once the some_php_page.php returns a value. The success call reads that value and then does something. This is a relatively simple way to accomplish (I think) what you're looking to do.
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));
?>
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.
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!
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