Update database after user action - php

Ok, so I am relatively new to php, javascript, and jquery. Here is what I have going.
I have a table that is created when the page opens that is filled up using a for from a database query (just a simple select *). The problem right now is the final <td> is a dropdown menu that the use can change (changing the item from viewed to unviewed and back). So, what i want to do is when the user selects either value in the drop down menu, i want to get the second column value (the ID value in my database) of that row and update the viewed status. My problem is I am not sure how to use JQuery to get the ID value into my update statement for the database. Here is what I have so far:
<script language="Javascript">
//cache the select and span elements
var table = document.getElementById('leads');
var mySelect = document.getElementById("mySelect");
//when it changes
mySelect.onchange = function() {
var row = this.parentNode.parentNode;
//change the tag innerHTML checking the selected value of the select
if (mySelect == "1") {
var id = table.rows[row.rowIndex].cells[1].innerHTML;
//HOW DO I GET THIS ID INTO A SELECT STATEMENT THAT CAN EXECUTED BY A PHP FUNCTION
}
}
</script>
EDIT:
Here is an attempt so far... Inside my if statement I added the following line:
$.get("updateToNew.php", {lid: id});
and here is the php (you can assume the connection to the database and everything is correct inside this file):
$query = mysql_query("UPDATE myTable SET new=1 WHERE ID=".$_GET['lid']) or die(mysql_error());
This does not throw any errors, but does not update the database. Also, I noticed as I was troubleshooting that the script only runs the first time the drop down menu is changed, any time after that it does nothing.

You would have to write an XmlHttpRequest to fulfill this action.
See what suits you best: What is the difference between XMLHttpRequest, jQuery.ajax, jQuery.post, jQuery.get

Related

Change the value of second select on first select

I'm sorry I haven't included "my attempt" as such with this one, I'm useless with jquery so need some advice!!
I would like to change the value of a second selctor based on the results of the first.
I have a database of builders and regions with the headers builder_name and builder_region. The list ends up looking like this ...
builder_1 region_1
builder_1 region_2
builder_2 region_1
builder_3 region_1
builder_3 region_2
builder_3 region_3
(You get the idea)
I'm using the following in the form I've built to get a list of the builders for the first select box ...
echo '<select class= "ml-select" name="gen_builder">';
echo '<option value=" ">Select Builder</option>';
while($row = mysql_fetch_array($rsBUILDER)) {
if($linebreak !== $row['builder_name']) {
echo '<option value="'.$row['builder_name'].'">'.$row['builder_name'].'</option>';
}
else {echo "";}
$linebreak = $row['builder_name'];
}
echo '</select>';
The $linebreak is to get rid of the duplicate builder names from the list, which works a treat.
What I would like to achieve is a second selector that selects the regions available, dependant upon the builder that has been selected in the first option. I hope this makes sense????
The second query needs to look at the builder selected in the first selector and filter out just the regions that are in rows with the builder name form selector one.
Please do say if you need further information, I'm not great at explaining myself.
As you said you don't have experience with jQuery or Ajax, I'll post my answer with as many comments as possible. I will assume that you have two select dropdowns in your page.
The first one contains the builders, so it will have id="builders".
The second one contains the regions, so it will have id="regions".
From what I understand, the first select will be exactly the one you posted in your question, generated server-side (by PHP). I only ask that you please make a slight change on it, making each option value be equal to the builder's database ID, and not its name (unless the builder's primary key is their name, and not an ID). This will make no difference for the final user but will be important for our jQuery solution. The second one will be empty, as the idea is to fill it dynamically with the regions related to the builder selected in the first dropdown.
Now let's get to the jQuery code:
//Everything that goes below this first line will be ready as soon as the page is fully loaded
$(document).ready(function() {
//The following code defines an event. More precisely, we are defining that the code inside it will run every time our select with id "builders" has its value changed
$('#builders').change(function() {
//$(this) is our builders select. $(this).val() contains the selected value, which is the ID of our selected builder
var currentValue = $(this).val();
//Now, this is our Ajax command that will invoke a script called get_regions.php, which will receive the builder's ID in $_GET['builder_id'] and you can use to query your database looking for all regions related to this builder. Make sure to create an array with the returned regions. Your get_regions.php's last line should be echo json_encode($regions);
$.get("get_regions.php", {'builder_id': currentValue}, function(data) {
//Inside this function is the code that will run when we receive the response from our PHP script. It contains a JSON encoded list of regions, so first of all we need to parse this JSON
var regions = $.parseJSON(data);
//Before filling our second select dropdown with the regions, let's remove all options it already contains, if any
$('#regions').empty();
//Now, all there is left is to loop over the regions, adding each as an option of the regions dropdown. I'll do it the universal way
for (var i = 0; i < regions.length; i++) {
var regionOption = '<option value="'+regions[i]['region_name']+'">';
regionOption += regions[i]['region_name'];
regionOption += '</option>';
$('#regions').append(regionOption);
}
});
});
});
Despite any syntax errors (can't test the code from here) this should do the trick. Hope the comments were clear enough for you to understand how things work in jQuery.

jQuery Table AddRow Plugin adding ID numbers to added rows

I have a form and I'm using the jQuery Table AddRow plugin to dynamically add rows to a table, the problem is I'm trying to when you select a Menu Item that the menu item goes into the text box to the left of it. It works on the first row but I can't figure out how to get it to work with rows that are added via the plugin.
You can see my code in action here: http://jsfiddle.net/VXNzd/
Here is the jQuery code:
// This moves the select box text to the input box
$('#mnu_names').change(function() {
var mnuProduct = $("#mnu_names").find(':selected').text();
var mnuCleanProduct = mnuProduct.split(' - ');
$('#topping_name').attr('value', mnuCleanProduct[0]);
});
// This code is needed to add and delete rows with the plugin
$(".toppings_add").btnAddRow({
It may be easier to see what I'm talking about by visiting the jsfiddle link up top. When it loads use the select box to and select something, It will put that info over into the text box without the price info. Add a new row and try it again. Won't work, can't figure out how to make it work.
The problem was as said by tomhallam your ID's are not unique. Also $.change() does not work on blocks added after you ran that. You should instead use $.on('change',...).
I updated your code and posted it on http://jsfiddle.net/PDPbn/5/.
The modified jquery-code goes as follows:
$(document).on('change','.mnu_names',function() {
var mnuProduct = $(this).find(':selected').text();
var mnuCleanProduct = mnuProduct.split(' - ');
$(this).parentsUntil('tbody').find('.topping_name').attr('value', mnuCleanProduct[0]);
});

jQuery, PHP - How to make a 'Get started' popup box

I'm trying to create one of those pop-up boxes you'll get the first time you log in to my website. I wan't this to have some 'Get started' articles, FAQ and so one.
But I can't figure out how I would make this happen? I would like to create it in jQuery and PHP.
But should I have a row['getStarted'] in my database set to 0 or 1, and then display the popup box if it's set to 1? Or is there a better way to do it?
And I've also been looking for how to change a row in the Database, with just a simple click on a button like: "Don't show me this again". I've figured out I need ajax, but how would an action like this look like?
I hope to get some links or a way to get started.
You will need jQuery and PHP.
But should I have a row['getStarted'] in my database set to 0 or 1, and then display the popup box if it's set to 1?
Yes you should do exactly that. Maybe in the 'users' table.
This is an example, I didnt test it but it should work.
Its just to show you in 3-4 steps how its done.
MySQL table -USERS
id UserID FirstName Popup
1 7804 Peter 1
2 5874 Lois 0
3 9875 Joseph 1
Html
*//An element (image/button/what ever) with the class "No_popups_for_me"
//and a pseudo element named UserID*
//Here you can check before displaying the element if the user has popup enabled.
<?php
include ("connection.php"); //Your connection settings to MySQL
$activate = "SELECT id from users WHERE UserID='".$VARIABLE_CONTAINING_THE_USER_INFO."' AND Popup='".1."' ";
$activate_src= mysql_query($activate);
if (mysql_num_rows($activate_src)>0) {
echo '<div class="No_popups_for_me" UserID="'.$VARIABLE_CONTAINING_THE_USER_INFO.'"></div>';
}
?>
JavaScript
//User clicks the button to disable popups.
$('.No_popups_for_me').click(function(){
jQuery.ajax
({
type: "POST", //method used to send data
url: "./update_users.php", // which file to call
data: { UID:$(this).attr('UserID') }, //Grab UserID from the html element, store it in a var named UID
cache: false
}
});
PHP
*// file update_users.php*
<?php
include ("connection.php"); //Your connection settings to MySQL
$current_user = intval(trim($_POST['UID'])); //Get the data ajax send via post
$disable_popup="UPDATE users set Popup=0 WHERE id=$current_user"; //Update SQL
mysql_query($disable_popup) or die ("Error10.25");
?>
What I will do, is to have a "last_login" attribute in the user table.
if row["last_login"] is NULL, then it's first time login.
if it is a timestamp, then it is not the first time.
And obviously you need to update this attribute every time the user login.
The other reason for me to have this attribute, is to keep track of the active users.
for the AJAX, I recommend to use the Bootstrap, A css&js framework build by Twitter.
The Modals plugin fits your needs perfectly.
http://twitter.github.com/bootstrap/javascript.html#modals

Form select button to insert info to db mysql

I need help here.. I want to create some form for submit data to db. I have no problem with the form and inserting data to db. but I stuck when I want to add new value to db table column. I have create 1 select button and on the select button value list from db column (e.g category). picture attached.
Top: select the value from db and input disable
bottom: select create new and input enable to create new value
Sorry stackoverflow does not allow me to attach img. Here is the link
http://dl.dropbox.com/u/121852/form-elements.jpg
Hope you guys are clear and can help me.. thanks in advance!
If I'm getting you correctly - you want an final option on the select's options list with "create new one"?
Than you should give it a unique value like "createcategory" and put onchange event on that select box
<select name="..." onchange="javascript:checkSelect(this.value);">
As you can see - I called the javascript function checkSelect that you should create with somethis like that:
function checkSelect(val)
{
if(val == "createcategory")
document.getElementById('the_input_id').disabled = false;
else
document.getElementById('the_input_id').disabled = true;
}
What I did in this function is to check on every change of the select-box if the value of the selected option is "createcategory", and if so - I'm setting the text input disabled to false, so it would work, otherwise - I'm setting it again to true

php database connection within expression engine and javascript

I am trying to set up a simple hit counter within expression engine using javascript and php. If a user clicks a certain link, I want it to trigger a javascript function which updates a value within my expression engine database. My setup is this:
I have a table called exp_custom_stats. Within that table are several rows of stats. For this example we'll use stat_downloads as the row that needs updating, with stat_name as the column header for stat_downloads, and stat_count as the column header for the value.
All I want to do is connect to the database, retrieve the stat_count for stat_downloads, and store it as a variable. Then on javascript click of a link, I want to increment that variable by one, and submit it back to the database as an update. The rough example would be below, but how do I connect to the DB in expression engine through a template?
DB Connection:
<?php
SELECT * FROM exp_custom_stats WHERE stat_name = 'stat_downloads';
$stat_val = 'stat_count';
$stat_val++;
echo "$stat_val";
?>
DB Update:
<script type="text/javascript">
$(document).ready(function() {
$('.stat_increment').click(function(){
<?php
INSERT INTO exp_custom_stats
VALUES ($stat_value)
WHERE stat_name = 'stat_downloads';
?>
});
});
</script>
I figured out a way to do this using a combination of AJAX, PHP, and the External Entries add-on.

Categories