php database connection within expression engine and javascript - php

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.

Related

Extract text from HTML and pass it to MySQL query in a PHP script

I've been looking around for solutions for this for quite sometime and sadly, haven't found a proper solution for it.
Here's the situation.
I have a Bootstrap modal that displays text ( let's call it 'header' ) depending on which button was clicked. The header value is picked up from the data-attribute of the button and using jQuery, I update the text for the respective modal. I hope I've been clear enough about this.
Now, I want to use the same header text in a PHP Script that queries my MySQL table with this 'header' value in the LIKE clause of my query as '%header%'.
Seems simple enough but I can't get my head around it.
Here are some issues that I face:
The header value is empty in the PHP script when I try to pass it to the script. I tried using script_tags to strip the tags around the HTML of the header and just extract the text and also tried PHP DOM but it did not work.
Here are the basic steps for further clarity:
I have a PHP script that needs to get a text value from the HTML on the same page.
This text value was picked up from a data-attribute of a button and updated via jQuery to the HTML.
This text value must be included in the LIKE clause of MySQL query in the PHP script for any updates to the table.
I can handle everything else except the extraction of text and sending it to the PHP script part.
Thank you.
Adding Code for reference:
This is the HTML code that houses the data-attribute:
The $project_title variable was set previously and appended to the button.
echo "<a class='delete_icon' data-project_title='$project_title'><i class='fa fa-trash'></i></a>";
This is the jQuery code:
$('#project_profile_modal').on('show.bs.modal', function (event) {
var del_icon = $(event.relatedTarget);
var project_title = del_icon.data('project_title');
modal.find('h4').text(project_title);
}
This is the excerpt of the PHP script that is relevant:
<?php
$result = "SELECT content FROM my_table WHERE content LIKE '%$project_title%';
?>
Question is: how do I get the text contained in h4 to $project_title/my LIKE clause.
Assuming button looks something like:
<button class="modal-button" data-text="..." data-row_id="...">
Then in click handler you gather all the data and send to server:
$('.modal-button').click(function(){
var data = $(this).data();
// send to server
$.post(url, data, function(response){
// update modal header and content
$('modal-header-selector').text(data.text);
$('modal-content-selector').html(response);
})
})

Update table with each input character

I've just asked a question on how to refresh an element without refreshing your page. I've been learning ajax for some hours now, but I'm having trouble getting any implemented.
So what I want to do is this:
Refresh a table containing mainly sql executions, for which I need the input value.
To update it I use onkeyup="Search();" which then forwards my value to another php page.
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
I know I can get this value on a php page like this:
<script type="text/javascript">
function Search() {
var inputValue = $('#IDsearch').val();
$.post('testAjaxJquery.php', {postname: inputValue},
function (data) {
$('#IDsearch').val(data)
});
}
</script>
and in PHP (testAjaxJquery.php)
<?php
$searchValue = $_POST['postname'];
echo $searchValue;
?>
The problem here is: I don't know how to use the retrieved value and update my existing table with it, without a page refresh. I tried putting all of the code inside a new php file and using $("#refreshOnSearch").load("refresh.php");, no luck.
The essence is: Once a letter is typed, I need an updated version of my table.
I guess you could say I am trying to replicate https://datatables.net/index.
Start with looking inside your $.post function.
Then inspect data using console.log(data) or debugger and looking at what data is. It's possible data is an object and you are trying to set #IDsearch to an object instead of a string or int.
If that is the case you will want to do something like $('#IDsearch').val(data.response);

Passing PHP variables to jQuery pop-up DIV

I'm quite new to PHP and I'm dealing with a problem I have no idea how to solve. I'm generating a table of users (name, username, e-mail) from a MySQL database. There is an edit link in each row. This links displays a pop-up DIV (made using jQuery) that contains three form fields (name, username, e-mail) that can be used to edit (update) the particular row.
I would like to pre-load the current values from the database into these form fields to make it more convenient to edit them.
The problem is that the DIV is displayed without refreshing the web page, meaning that I'm unable to pass any parameters from the edit link and therefore I cannot tell the server which values to pre-load.
Is there any solution to this?
Thanks!
You can pass them using this way:
Note : when u generate the values(name,username,email) in Server (using PHP)..do it as follows :
<a class='editBtn' data-x="the username info" data-y="the email info" data-z="name">Edit</a>
then at Client side catch them using on click events:
jQuery('.editBtn').each(function(i,v){
jQuery(v).click(function(eve){
eve.preventDefault();
eve.stopPropagation();
var username= jQuery(v).attr('data-x');
var email= jQuery(v).attr('data-y');
var name= jQuery(v).attr('data-z');
/*
display ur Modal Box here
Happy Coding :) ,
*/
});
});
try this:
$(your var in JS) = <?PHP echo $(your rowname in the prepaired statement)['(your ID tablevariable)'];?>
that could work but i hadn't seen the code so, this is the only thing i could give tou to try
if you want to refresh the data in realtime about your html with your new values, you must use AJAX. JQuery give us a simple api about this: https://api.jquery.com/jQuery.ajax/
I like to use a hidden <iframe> at the bottom of all my pages. I can load a php script into that, which than can be used to update the parent frame by using javascript.
<iframe name="hidden" id="hidden" style="display:none"></iframe>
To call the script, just use a link or button to call it.
Click to load script!
Once you get the data from mysql, use javascript to change the variables.
<script language="javascript">
parent.document.getElementById('name').value = '<?PHP= $sqlResults['name']; ?>';
parent.document.getElementById('username').value = '<?PHP= $sqlResults['username']; ?>';
parent.document.getElementById('email').value = '<?PHP= $sqlResults['email']; ?>';
</script>

Update database after user action

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

Fill Single Input Based On Prior Select - MYSQL PHP JS?

I want to grab my customers phone number from a MYSQL database and auto populate it into an input box based on users selection of customers in a prior dropdown box.
I've managed to do this in the past when filling in larger amounts of data but what I've previously used seems like a lot of code to auto fill a single input box.
I know how to fill the customer phone based on the data passed from the prior page (although I've deleted that bit here) but I want that data to change dynamically as users use the dropdown.
There's got to be an easy way to do this but I'm a complete newb at js (and only barely proficient at PHP & MYSQL). Can anyone give me a hand?
My PHP/HTML:
$result = mysql_query("SELECT cust_id, name, phone FROM customers ORDER BY name ASC");
$customers = mysql_fetch_array($result);
<label for="customer">Customer:</label>
<select name="customer">
<option value="0">Add New Customer</option>
<? foreach ($customers as $customer): ?>
<option value="<?=$customer['cust_id']?>" <?=($customer['cust_id'] == $parts['cust']) ? "selected" : ""?>><?=$customer['name']?></option>
<? endforeach; ?>
</select>
<label for="custphone">Customer Phone:</label>
<input type="text" name="custphone" value="">
Let me know if you need anything else from me and thanks in advance for helping me out on this.
For this answer, I will use the jQuery syntax, jQuery is a free javascript library, and you'll certainly use it in the future, read more.
To resume, we'll use an event triggered by your select element, when his value is changed, we'll process an AJAX request with some parameters to a PHP page (ajax.php) which returns the phone number of the customer previously choosen.
First you need to include in your HTML web page, the jQuery script, with the <script> tag.
<script src="path/to/jquery.js"></script>
In a second time, we'll create a new javascript script (assuming you add some id's to your HTML elements):
<script type="text/javascript">
$(document).ready(function(){ // When the document is ready
$("select#customers").on("change",function(){ // We attach the event onchange to the select element
var customer_id = this.value; // We retirve the customer's id
$.ajax({
url : "path/to/ajax.php", // path to you php file which returns the phone number
method : "post", // We want a POST request
data : "customer_id="+customer_id, // You'll retrieve this data in your $_POST variable in ajax.php : $_POST['customer_id']
success: function(response) { // The function to execute if the request is a -success-, response will be the customer phone number
$("input#custphone").value(response); // Fill the phone number input
}
});
});
});
</script>
Now, you've all the gear to continue, you should read about jQuery and AJAX.
You just have to create the "ajax.php", retrieve your customer id with the $_POST variable, process the SQL query to retrieve the phone number, then, return it with an echo.
Sounds like you want to look into AJAX. jQuery.ajax() makes it pretty easy.
Basically, you have a page on the server that queries the database and returns a JSON encoded string that the javascript can convert (using jQuery.parseJSON)back into an array and populate the list!
Use .change() to bind an event to the dropdown's change event. This will fire whenever the selection changes. Inside, you want to get the value (see demo on that page) and send an AJAX request to the server.
The PHP script on the server will query the database and return a JSON string. In the success function of the jQuery AJAX block you can populate the new list with the decoded information. See this page for a tutorial on how to add items to a select.

Categories