ajax and php updating mysql - php

i am having problem updating the database.
Basically what i am trying to do is everytime a download link is clicked the download count in the database goes up.
Can someone point me in the right direction as i have been trying to get this right for hours :(
Here is the html.
<div class="button_border_dark"> <a id="linkcounter" href="http://www.derby-web-design-agency.co.uk/freeby-download/<?php echo $freebies_download ; ?>" target="_blank" title="Download">Click To Download File</a></div>
Here is the jquery
<script>
$('#linkcounter').bind('click',function(){
$.post("downloadcount.php",{ linkid: <?php echo $id ; ?>});
});
</script>
Here is the downloadcount.php which i am trying to post data too, so it updates the content.
<?php
require_once("applications/constants/connection.php");
require_once("applications/controllers/basic.php");
if(isset($_REQUEST["linkid"])){
$linkid = sanitise($_POST["linkid"]);
$updatedownload = mysql_query("UPDATE freebies SET download_count=`download_count` +1 WHERE id ='".$linkid."'") OR die(mysql_error());
}

You don't say what is the problem!
Is not incrementing? is incrementing too much? is one process blocking the other? the problem is that people can cheat and make so a file has ben downloaded a million times?
Anyway, I think you code can be simpler.
$('#linkcounter').click(function(){
$("#invisibleiframe").attr("src",$(this).attr("src");
$.post("downloadcount.php",{ linkid: <?php echo $id ; ?>});
return false;
});
this need to create a invisible iframe, that will be the one downloaded the file. after starting this download, the ajax request is made. a single event do the two things. made this way the stuff still works if js is disabled.

I think should be
$updatedownload = mysql_query("UPDATE freebies SET download_count= download_count +1 WHERE id ='".$linkid."'") OR die(mysql_error());
Note the single quote:
SET download_count = download_count +1

Well first off I would not mix the jQuery and PHP personally, this may be the source of your problem, I would try something like this
<div class="button_border_dark" theLinkId="<?php echo $id ; ?>">
<a id="linkcounter" href="http://yourURL/" target="_blank" title="Download">
Click To Download File
</a>
</div>
With the jQuery like this
<script>
$('#linkcounter').bind('click',function(){
var theLinkId = $(this).parent().attr('theLinkId');
$.post("downloadcount.php",{ linkid : theLinkId});
});
</script>

It is possible that your event is not actually being bound to the anchor, because you are running .bind() before the anchor exists. Try this:
<script>
$(document).ready(function(){
$('#linkcounter').bind('click',function(){
$.post("downloadcount.php",{ linkid: <?php echo $id ; ?>});
});
})
</script>

how many anchors you have with id = 'linkcounter' ?
If you have more than one, i recommend you to change 'id' for 'class'
Greatings.
EDIT:
Try something like this:
Link
<script type="text/javascript">
function goToLink(o, id) {
$.post("downloadcounter.php",
{linkid : id},
function () {
window.open($(this).attr("href"));
}
);
return false;
}
</script>

Related

How do I reload a input after 3 seconds with javascript

How do I reload this input once after 3 seconds has passed after the webpage has loaded. using javascript
<input type="text" name="steamID" id="steamID" value="<?php echo $steamid; ?>">
Try looking at this answer on SO:
Reload random div content every x seconds
If that doesn't work for you, you will have to use ajax to get new content. Look at jQuery's API here:
http://api.jquery.com/jQuery.ajax/
Or if you're not using jQuery, look at this for a tutorial on AJAX:
http://www.w3schools.com/ajax/default.asp
Otherwise, for more help, please post more of your code -- but ajax will have to be used
If you want the PHP in your code to be run again, you need to make you code a little more complicated.
You will need the following components
a php file that will lookup and print $steamid only.
a javascript function that uses AJAX to get the information from the php file, sets the value of your input
call the javascript on page load, then set an interval for 3 seconds and call it again.
But based on this...
The problem i have that the PHP var $steamid are set after the input has been created so all i need todo is reload the input so the $steamid will show.
... I think you just need to re-order your PHP code.
By reset, I am assuming you mean set the value to null.
$(window).load(function(){
setTimeout( function() {
document.getElementById("steamID").value = "";
},3000);
});
EDIT: Based on your further description, wait until steamID is set, then put this on the page:
<script type="text/javascript">
document.getElementById("steamID").value = "<?php echo $steamid; ?>";
</script>
<?php
echo "<script type='text/javascript'>";
$steamid = "testing 1,2,3";
echo " var sID = '".$steamid."';";
?>
function setupRefresh() {
setInterval("refreshVal()", 3000);
}
function refreshVal() {
var e = document.getElementById('steamID');
e.value = sID;
}
</script>

Change php array when user checks a checkbox

I have a column that has a button that when pressed, links to a URL set in PHP. I want to add a checkbox next to that button so that if it's checked when a user presses the button, it will take them to an alternate url. The PHP code setting the url:
<?php
$link = 'http://www.example.com';
?>
I realize that the code needs to be in javascript, which I don't know. I know only a tiny bit of php, so any help would be apprciated.
To clarify: (and of course I know this code will never work)
What I want to do is this:
<?php
If (checkbox is checked) {
$link = 'http://www.google.com';
} else {
$link = 'http://www.example.com';
}
?>
There is probably another way to do what you want to achieve. The value of the checkbox should be sent to a single php script on the server with the rest of the form's fields' values. Then you can use the checkbox's value (boolean) in php and do what you need to do accordingly, possibly requiring external scripts.
Checkbox value is not sent to server with form submit if it is not checked.
So, you can use something like this:
<?php
if (isset($_POST['checkbox_name'])) {
$link = 'http://www.google.com';
}else{
$link = 'http://www.example.com';
}
?>
Include the jQuery from Google:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
Then write the redirect function which you call after clicking the button;
<script>
function foo() {
if ($('#checkbox').is(':checked')) {
//redirect to google.com
window.location = "http://www.google.com/";
} else {
window.location = "http://www.example.com/"
}
}
</script>
And finaly your button should look like this:
<button onclick="foo();" >Your button</button>
This code assumes your checkbox has an id "checkbox".
Also, I don't think that what you're trying to do should be done with PHP - so you should learn Javascript/jQuery straight away instead of writing code the way it shouldn't be written.
Example: http://jsfiddle.net/5bdae/
Using jQuery this is fairly simple. You bind a function to the link, this function works out whether the checkbox is checked, if it is it links to one place, otherwise it links to another.
For an HTML structure like this:
<input id='myCheckbox' type="checkbox" name="box" value="box" />
<a href='#' id='myLink'>My Link</a>
The jQuery would be:
$('#myLink').click(function(event){
event.preventDefault();
if ($('#myCheckbox').is(':checked')){
window.location.href='http://www.example.com';
} else {
window.location.href='http://www.ask.com';
}
});
This could would go outside of the PHP tags, and you would need to include jQuery in your code.

Printing a javascript variable in php echo

To clarify:
I have an echo statement as follows:
$striptitle .= ' - <a onclick="getnewurl();" href="'.SGLink::album($aid). '">'. $namek .'</a></h1>
<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-via="jb_thehot" data-text="Pictures of '. $hashfinal .'" teens>Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';
echo $striptitle ;
The onclick does this:
<script type="text/javascript">
function getnewurl()
{
var url = document.URL;
alert( url );
}
</script>
What I need is essentially to add the my anchor tag a data-url="INSERT_VAR_URL_HERE"
Is that possible?
Let me know if this isn't clear enough
Thanks!
Edit: to clarify, the alert in the function is only for testing. What I need is to be able to use the variable obtained in the function, in the same $striptitle variable.
My problem is that the url changes with AJAX, and the twitter button's data-url does not get updated. I was hoping to be able to get the new url by getting it everytime it is clicked. If there are other ways to do that, I'm open to suggestions!
Why not pass it as an argument?
$striptitle .= " - <a onclick=\"getnewurl('URL-HERE');\"...>";
Then in your script:
<script>
function getnewurl(url) {
alert(url);
}
</script>
Building on #Kolink's answer one way to not repeat the url in two places you could generate the link as:
<a onclick="getnewurl(this);" href="...">
then your JS could look like:
function getnewurl(link) {
link.setAttribute('data-url', location.href);
}
EDIT apparently jQuery.data doesn't update the dom properly, but setAttribute does

PHP: Delete from a Database with some prompts from javascript

My code is below, I am trying to delete records from mysql database but before deleting the browser has to prompt the user whether the deletion should continue. My problem is my logic is not working its deleting the record no matter what. Any help will be appreciated.
if (isset($_POST['outofqcellchat'])){
?>
<script type ="text/javascript">
var question = confirm("Are you sure you want to unsubscribe\nThis will delete all your facebook information in QCell Facebook");
if(question){
<?php
$delusr = mysql_query("delete from `chat_config` where `phone` = '$phonenumb'");
$row = mysql_num_rows($delusr);
if($row>=1){
header("Location:http://apps.facebook.com/qcellchat");
}
?>
alert("Unsubscribed, You can register again any time you wish\nThank You");
}else {
alert("Thanks for choosing not to unregister \nQCell Expand your world");
}
</script>
<?php
}
?>
Thats my code. Please help
you want to prompt the user upon click of a anchor tag or button. For eg using anchor tag
<a href="delete.php" onclick="return javascript:confirm("Are you sure you want to delete?");" />Delete</a>
This will prompt user.
Or you might use a javascript function such as
<a href="delete.php" onclick="return check();" />Delete</a>
<script type="text/javascript">
function check(){
var question = confirm("Are you sure?");
if(question){
return true;
}else{
alert("Thanks for not choosing to delete");
return false;
}
}
</script>
Hope this helps.
You have a fundamental misunderstanding between PHP and Javascript here. The PHP code will be executed regardless of any JavaScript conditions (which will be processed long after PHP is done, in the browser).
You will need to change the logic so that confirming the deletion redirects the user to a PHP page that deletes the record, or starts an Ajax request with the same effect.
The PHP runs on the server before the client even sees the JavaScript. Use AJAX or a form submission instead.
Try to separate your PHP from javascript and do not forget to delete using the exact link u are targeting ,if you want to delete one by one record , in href that is where u put that Id first .
Delete
<script type="text/javascript">
function check(){
var question = confirm("Are you sure?");
if(question){
return true;
}else{
alert("Thanks for not choosing to delete");
return false;
}
}

How do I show next result in MySQL on "onclick" in JavaScript?

I want to show a certain amount of results (say, 5) and make a:
<a href="" onclick="<?php ShowNextResult(); ?>">
And use onlick to show the next 5 results.
EDIT ::
HTML
<div id="results">
<div class="result"></div>
<div class="result"></div>
<div class="result"></div>
</div>
<a href="#" id="showMore" />Show more</a>
JAVASCRIPT
Use Jquery as below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#showMore').click(function(event) {
event.preventDefault();
$number = $('.result').size();
$.ajax({
type: "POST",
url: "getNext.php",
data: "count=$number",
success: function(results){
$('#results').append(results);
}
});
});
});
</script>
PHP
you should make a new php page (getNext.php ) that will get query results
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons LIMIT {$_POST['count']},5");
while($row = mysql_fetch_array($result))
{
echo "<div class='result'>".$row['FirstName'] . " " . $row['LastName']."</div>";
}
mysql_close($con);
?>
HELP
you can use SQL something like
SELECT x,xx,xxx FROM XxXxXs Limit $_POST['count'],5
Since you specifically mention JavaScript I assume you don't want to reload the page or anything like that. Your onClick will have to trigger an AJAX call to a php page on your server that will handle the request and give you back the next five records (or the last 5, or random ones, etc...).
JQuery is really popular for doing this and have built in functionality to make this process easier.
http://api.jquery.com/jQuery.ajax/
Here are some tutorials: http://docs.jquery.com/Tutorials
Your best bet is to write this functionality w/o using JavaScript. Make the page accept arguments to show specific records. Once you have that code done, then put the AJAX on top of it, but that way you'll have the older stuff to fall back on if you need to for compatibility or things don't work the way you need them to.
These are pretty general answers, do you need specific help making the query to only show the next 5 records? Or the specific PHP code to tie it together? Or just the JS to do the AJAX stuff? Could you be more descriptive if you need more info.
change
data: "count=$number",
to
data: "count=" + $number,
because then it isn't work!
Here's my solution that showing quiz questions partially with next button means on each click at Next Button 5 more question will display.
<?php
$strSQL="SELECT * FROM `quizes` WHERE Q1 IS NOT NULL ORDER BY RAND()";
$result=mysql_query($strSQL);
while($row=mysql_fetch_array($result)){
$c=0;
$q[]= $row['Q1']; // This is database record that has all question stored as array
?>
<?php
for($inc=0; $inc < $ret; $inc++){ ?>
<table>
<tr id="<?php echo "i".$inc ?>">
<td id="qs"> <?php print_r($q[$inc]); ?></td>
</tr></table>
<!-- here in i am display all question with loop in this variable $q[$inc] -->
<?php } ?>
// Now we are going to display partial
instead of all so data will display partially with next button
Next/Show More
//this is anchor/button on which more questions will load and display when clicked
//CSS question are placing in tr (table row) so first hide all question
<style>
tr{
display:none
}
</style>
//jquery now we will show partial question 5-questions at each click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("[id=i0],[id=i1],[id=i2],[id=i3],[id=i4],[id=i5]").show();
//Display first 5-question on page load other question will
//show when use will click on next button
var i=0;
$("#more").click(function(){ // Next button click function
//questions tr id we set in above code is looping like this i1,i2,i3,i4,i5,i6...
i=i+5; //at each click increment of 5 question
var e=i+5;
//start after the last displayed question like if previous result was 1-5 question then next result should be 5-10 questions...
for(var c=i; c < e; c++ ){
$("[id=i"+c+"]").show();
}
});
});
</script>

Categories