I have a code which is helping for determining which key is pressed. But I confused, I do not know how can I save this key -(button) is pressed-. Is this possible? Can I use php codes in javascript to create a new line in my mysql database?
<script type="text/javascript">
function textsizer(e) {
var evtobj = window.event ? event : e;
var unicode = evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey = String.fromCharCode(unicode);
if (actualkey == "a") {
//database code needed
}
}
document.onkeypress = textsizer;
</script>
Your main problem is that JavaScript is a client-side language (it runs in the browser running on the user's computer) and PHP is a server-side language (it runs on your web server). You can't mix the two together because they run at different times.
What you could do is use is AJAX to send requests from your JavaScript code to your web server, without navigating away from the page, whenever a key is pressed. You'd simply send a key code (or the character that key code represents) as a parameter of the request, then your web server would handle saving that information to your database.
Here is some code that might help you get the ball rolling. I'm opting to use jquery, it will make this much more straight forward.
window.bind('keydown', function(event){
$.ajax(
{
url: 'http://asite.com/script_to_save_codes_to_db.php',
data: event.keyCode,
type: 'POST',
success: function (data){
//have the server respond with a boolean indicating that the keycode was saved to the db or not and decide what to do next
}
}
);
});
How this works on the server side is a whole 'nother can of worms as it will depend on your server-side language and database choices.
For an entirely client-side solution you could save the keyCodes as a json string to localStorage or a cookie and do what you want with it later... But those can be wiped at any time and I would not call them databases.
Related
the log file will be in notepad format the values will be like this 11.23445646,56.3456578954
10.23445646,26.3456578954
16.23445646,-46.3456578954
I'm planning to get the data from server to website textbox, of first value which I marked as italic the values will change after few seconds the updated value will come first. I tried some PHP example but not getting it in the below text box the values I need to get.. for example: x=11.23445646, y=56.3456578954, pls guide me
Longtitude <input id="x" type="number" value = "" onkeyup="updateMarker('x')">
Latitude <input id="y" type="number"value = "" onkeyup="updateMarker('y')">
Updated Answer
You can do this now using Web Socketing. Here is a guide and hello-wrold example of a php websocket server:
http://socketo.me/docs/hello-world
And to see how to implement client side javascript of websocket, you can see the bottom of the link put above, which shows you this snippet:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
Old
PHP does not support live connections generally in the way you expect, you have to simulate it via repeated AJAX request. How? For instance on each second, or each two seconds.
You first have to write an ajax in your HTML with jQuery library:
Sending a request each second:
var url = "url_to_you_file";
var textarea_id = "#textarea";
setInterval(function(){
$.ajax({
url : "site.com/get-file-logs.php",
type : "POST",
success : function(data){
$(".textarea").html(data);
}
});
}, 1000);
Then in PHP file you would write this:
$file_path = "path_to_your_file";
$file_content = file_get_contents($file_path);
echo $file_content;
The above example gets the file content and sends it back to your browser. You may want to process it in a certain way; that then changes your approach a little bit. Because you must always stick to JSON format when you try to get data back from server to be manipulated by Javascript.
PHP doesn't really do "live" page updates since normally when a web browser (or other user agent) loads a web page once it's done downloading the page then PHP is already finished and can't touch what's already on the client.
Best way to do this would probably be to use a JavaScript AJAX call to periodically load the updated values from a PHP script and then update the values on the page.
Or if it's a really small page (in byte size) you could just make it automatically reload the whole page (with updated values) if that is not a problem for you.
In any case every time the PHP script is called it would just open the file in read mode and only read the latest values from the beginning of the file and return those. See fread(). Or maybe file_get_contents() or file() would be easier and just read the first line.
AJAX is a bit larger topic and I don't currently have the time to explain the whole process of updating the page using JavaScript. Google is your friend.
I am trying to send the results of the current drag drop state back to mysql using ajax/php.
The console .log works fine..
With some help the drag and drop jquery feature is all working perfectly however sadly jquery/ajax is really not in my bag of tricks ..
http://jsfiddle.net/ambiguous/FMKmj/ (Credit mu)
Tearing my hair out , any ideas ?
If you just want to submit the groups hash, do it like:
$('#submit').click(function() {
var groups = { };
$('.sort').each(function() {
var a = [ ];
$(this).find('li').each(function() {
a.push(this.id);
});
groups[this.id] = a;
});
console.log(groups);
$.ajax({
url: "yourscript.php",
data: groups,
success: function(){
alert('sent!');
}
});
});
Step 1: Catch the event
Notice that in the JQuery UI doc for sortable there is an event tab: here.
So you have to bind an event to an Ajax call inside the event handling function called when a block is dropped in a new box.
Step 2: The Ajax call
It means you have to write your Ajax call: see here.
Typically, you will do a post request since moving a block from a place to another place will change something on the server side.
What do you send to the server ?
Basically you want to send to the server which block has moved where. But it is up to you, you can send whatever you want, it depends on you server side application.
Step 3: The server side
The server based on this information can execute MySQL requests.
I'm making a fairly simple rating system, and I've got a small problem. When you +1 rate something, I'm trying to run a PHP script which will connect to the database, download the value from it, +1 to that value, and UPDATE the value in the database again.
I don't think reloading the page for a continious rating system would be a very good idea :S
I'm wondering how I can toggle a PHP script with Ajax, so that when you Click an image of a + sign, it runs the PHP add 1 script, and the + button turns in to a tick. I'm crap at ajax, and I'd go for trying jQuery + $.ajax({}); but I've failed 73 attempts. haha.
Anyone willing to give me a hand writing an Ajax script? :DDD
Thanks! :)
If you want someone to click a link which will access your page, let's assume you have this marup:
<a class = 'plusOne' id = 'someIDForYourSQLTable'>+1</a>
The ID is what you are going to pass to your server script so you can update the appropriate row, generally speaking this should be a primary identifier (i.e. Key) for the record that you want to +1.
Here is the jQuery that will send the ajax request to the file: plusOne.php in the same directory as the current page:
$(function() {
$(".plusOne").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "plusOne.php",
success: function(data) {
// Whatever you want to do after the PHP Script returns.
}
});
});
});
The request will send the a URL parameter 'v' which you can access in your PHP script from the $_GET super global array.
html
<img src="plusone.png" rel="some_unique_id" class="rate" />
javscript
$(".rate").click(function() {
var elem = $(this);
$.get('/rate.php?id=' + elem.attr('rel'), function() {
elem.attr('src', 'checked.png').unbind('click');
});
});
and in php
mysql_connect('localhost','db_user','pssword');
mysql_query('UPDATE database_name.table_name SET rating=rating+1 where id=' . mysql_real_escape_string($_GET['id']));
Have a look at xAjax, a library to expose PHP functions/method to client-side JavaScript. xAjax makes things very simple.
For example, you are able to perform several changes in the browser in parallel:
$objResponse = new xajaxResponse();
$objResponse->assign("myInput1","value",$DataFromDatabase);
$objResponse->assign("myInput1","style.color","red");
$objResponse->append("myDiv1","innerHTML",$DataFromDatabase2);
$objResponse->prepend("myDiv2","innerHTML",$DataFromDatabase3);
$objResponse->replace("myDiv3","innerHTML","xajax","<strong>xajax</strong>");
$objResponse->script("var x = prompt("Enter Your Name");");
return $objResponse;
I'm building a multiplayer game which uses a mysql database to store coordinate positions of players, which are then used to display opponent models.
The game uses a javascript file (milktruck.js) on the client side, and then a php file (xml_http_request.php) on the server side.
My problem occurs when trying to get the javascript variables (which store the coordinate information of an opponent) updated as the database information is updated.
The javascript variables are declared within the php file with the following code:
echo "<script> var lla0php = $lla0; </script>";
echo "<script> var lla1php = $lla1; </script>";
echo "<script> var lla2php = $lla2; </script>";
Then used in the javascript file, ticking function: prototype.tick, with:
window['lla0_2']= lla0php;
window['lla1_2']= lla1php;
window['lla2_2']= lla2php;
How do I continuously update these variables with new database information?
The web model is stateless, and to do this you're going to have to think of a way to overcome this and may possibly consider writing an abstraction layer that takes care of this for you.
You'll either need to poll continuously or look into other web-based solutions that allow the server to "push" data back to the client and maintain an "open channel" of communication. An example of this would be Google Talk in your browser or FaceBook chat.
What you need to do is use ajax.
function requestCoord(){
$.ajax({
url: "your url",
dataType : "json",
type: "GET",
success(val){
//get your php script to echo out a json string
//and it will be in val
window['lla0_2']= val.lla0php;
window['lla1_2']= val.lla1php;
window['lla2_2']= val.lla2php;
}
});
}
setInterval(requestCoord, 1000);
UPDATE
You can use html5 sockets.
im trying to adapt this little snippet:
$("#checkbox_id").change(function(){
/* CODE HERE */
});
I have a series of checkboxes that are dynamically generated and their id's are always like "hug3443" were "hug" is the column in the DB and "3443" is the unique id for each row.
My objective would be that every time the checkbox changes state to update it own state in the DB.
Can it be accomplished with jQuery?
Thank you.
I just found a script for this stuff and thought to post it here as I was checking this page a while ago until I finally came across to this script. Tested it and worked like a charm and I have inserted it in my coding library. Enjoy, folks.
http://www.jooria.com/Tutorials/ajax-20/jquery-live-checkbox-inputs-with-animation-effects-158/
Yes. Use live events to attach the change event handler to your checkboxes (so that dynamically added checkboxes will be handled also). Then simply do a AJAX request inside the event handler passing your script the new state and the name/id of the checkbox (you can then "parse" the id and column name in the script).
Not without a server side script that would deal with the data changes.
jQuery is a client side javascript framework and doesn't have direct access to mysql, which is a server side daemon.
Have a look into pairing jQuery with php and mysql.
Code in javascript you write with the use of jQuery is executed on the client-side in a browser. A solution is from your script to make a call to a server page that will execute a MySQL update . For example like this.
$("#checkbox_id").change(function(){
$.ajax({
type: "POST",
url: "/page-that/makes/update.php",
data: {param1:value1}
});
});
You should write some server-side code for managing database (php, ruby, whatever).
You should create something like API, which means, that server-side script needs to get some variables, which sended to it from clients (id's of rows, name and value of columns for example).
And after that you should write your jQuery frontend script, which will request server-side script for managing database tables. For requests you can use AJAX technology, something like this:
$.ajax({
url: 'http://somesite.com/path/to/server/side/script',
type : 'POST',
success: function (data, textStatus) {
alert('yahoo! we get some data from server!' + data);
}
});
You can get the value of the id of the checkbox using javascript you can then split the name into the field name and id value. For this example I've added a - into id to give a seperator
(I think you may need to use the click event rather than change, think change may only work for drop down menus)
$("#checkbox_id").click(function(){
var checkbox_id = $(this).attr("id");
var id_bits = checkbox_id.split("-");
// this would split hug-3443 into hug and 3443 setting id_bits[0] = hug and id_bits[1] = 3443
$.post("update,php",
{
row: id_bits[0],
id: id_bits[1]
}
);
});