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]
}
);
});
Related
I am looking to display the total number of files in a database. To clarify, say I had a website where people could upload pictures of their cars, and I wanted to display a live number of how many pictures there are, what would be the best way to do this? Javascript, php? A mix? I envision a div with a number saying "Total Pictures: x" and where x would be whatever the live total is. I plan on using MySQL to store all the data on the website. Is this even recommended to have something communicate with the server this much? Is there a name for displaying a live number? Thanks!
If you are thinking to use the AngularJS way, you could create a Poller service which polls every second (assuming your /counter.php returns json):
app.factory('Poller', function($http, $timeout) {
var data = { response: {}};
var poller = function() {
$http.get('/counter.php').then(function(r) {
data.response = r.data;
$timeout(poller, 1000);
});
};
poller();
return {
data: data
};
});
Then your controller:
app.controller('CounterCtrl', function(Poller, $scope){
$scope.counter = Poller.data;
});
And finally in your view:
{{counter.response}}
You can read more about $http
Set up a PHP script that queries the database and returns the total file upload count. After that, you can use JavaScript on the page to periodically call the server in a specified interval of time and fetch the count data from your PHP script. Using jQuery and GET, you can do something like this:
jQuery(function($){
setInterval(function(){
$.get( '/counter.php', function(fileUploadCount){
$('#counter').html( fileUploadCount );
});
},20000); // 20 seconds
});
In your HTML:
<p><span id='counter'>xx</span> files have been uploaded so far!</p>
Hope this helps!
How live do you want it to be? Just whenever someone updates the site it's going to have the new value or do you actually want it to update in near real-time?
If it's the latter you have to use Javascript against some kind of API that returns the amount of files in the database. I can't help you with that bit since you are using PHP, but it shouldn't be too hard. Just return some JSON looking something like
{ fileCount: 45020 }
Client-side you have a few options. You have the different javascript frameworks like AngularJS and EmberJS (and many more), as well as just 'plain old' javascript and frameworks like jQuery
The keyword is really AJAX, even if that is just a sort of buzzword for using javascript to make websites dynamic.
I am a fan of using AngularJS because it's easy, but I'll try to give you some pointers for using jQuery first. Note that I have not used jQuery in years now.
The jQuery way
jQuery has a function called jQuery.getJSON(), and according to the documentation you can use that function something like this:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "http://example.com/api/fileCount.json")
.done(function(data) { console.log(data) })
.fail(function() { console.log( "error" ); })
.always(function() { console.log( "complete" ); });
So this means we can call an endpoint and fetch some data using jQuery.
Here is a link to a tutorial about the basics of jQuery by the way.
jQuery makes us able to do things like this:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
When that is executed the div with id "divTest1" will contain the text 'Hello, world!'.
That sounds like something we could use here!
Javascript also has this really nice function called setTimeout(), which allows us to make it call a function later.
This describes how to use jQuery with setTimeout()
As you can see it also shows us jQuery.documentReady(), which is an event that fires when the website is finished loading, so it is a good place to put code we want executed.
The example below shows how to use jQuery to hide a div with id=div after 3 seconds.
jQuery(document).ready(function () {
setTimeout( "jQuery('#div').hide();",3000 ); //hide a div after 3 seconds
});
Combining these things you should be able to make a repeating call that fetches data from your server and then updates a div or another element with the data you have fetched.
Just create a function which uses jQuery.getJSON() to fetch data, and then at the bottom of that add a setTimeout call to run itself in X seconds (however often you want it to update).
In jQuery.documentReady() you call that function the first time the document loads.
And in the .done() bit of the getJSON() call you add the data you got from the server to your div with whatever html you want. I showed you how to use $("#divTest1").text(), but there is also a .html() which acts the same but you should use it to add html to a element.
The angular way would be to use AngularJS's $http to do the same thing, but I wouldn't recommend learning AngularJS until you have a bit of a better grasp on Javascript.
When you do though, I highly recommend it. It's a much better approach than using jQuery.
You can read about AngularJS here
I hope this helps!
I am trying to execute a specific query where I search for the name that i get using javascript. I have this HTML:
<a onmouseover="showDef(textContent)" href="aLinkHere.com">myWord</a>
The function showDef gets the myWord and I'm trying to execute my query after that.
<script type="text/javascript>
function showDef(txt) {
var myWord = txt;
//Some code here to execute the query?
}
</script>
The query I want to have is as follows:
mysql_query("SELECT * FROM defs WHERE name='myWord'");
Now I have to replace the 'myWord' with the word stored in the javascript variable. Is there any way to this? I already tried the following, but that didn't work..
document.write('<?php $data = mysql_query("SELECT * FROM defs WHERE name=\''+ myWord + '\'"); ');
I am relatively new in javascript and php, so any help is very much appreciated!
Javascript is client side language and you need php (server side) lang to execute query.
Create ajax request with that variable and use that variable in your query.
return that response from your remote php file and catch response in javascript. And enjoy with response.
IF you are searching name only(exact) then use = else use LIKE or REGEXP for better performance
This is an example that uses the jQuery library.
var dataString = 'searchVar='+ myWord;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data){
alert(data)
}
});
IN php code you jst get variable with $_POST['searchVar'] and execute your query
$qry = "SELECT * FROM defs WHERE name LIKE '%".'$myWord."%'";
and in while loop jst echo you response.
You're relatively new indeed, this is basic strings 101.
1) do NOT use document.write, it's not meant for you to be used, it's an API from a decade ago and doesn't do what you think it does. Find the element you want to set the content of (using document.getElementById or the like) and then use .innerHTML = ... to set its content.
2) To get your value in your query on the PHP side, just put it in there, it's one of the basic features of PHP:
$myword = sanitize_the_hell_out_of_this($_POST['myword'];
mysql_query("SELECT * FROM defs WHERE name='$myword'");
You can pick whatever method you like for sanitization, there are a few baked into PHP but do NOT, under ANY circumstance, pass the posted value straight to your database, unless you like people deleting your database because they can. Someone can just edit the html, change the single word to "'; drop table words; 'lo" and now your table will get dropped. fun times =)
In order for it to actually work, remember your page runs on the client's computer, and PHP is a server technology. So the javascript will have to ask the server for the data by literally asking the server: you'll need an AJAX get or post operation, and then work with the data that get back. You can't inject PHP code and then have it run on the user's computer.
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.
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;