Save data by MySQL after click a link to an external web - javascript

I want to put a clicks counter on banners on my page so advertisers get an idea of how many visitors arrive via my website.
I've seen that could be done by directing the link to an intermediate page that access MySQL (to save the data in a record BD) using PHP, and then redirected to the advertiser's website, but I wonder if there otherwise somewhat more "elegant" to do so.
Could anyone tell me if it is possible?
I've found an similar example, but this one donwload a file and count the visit (I only want to go to another web)
EXAMPLE HTML
<span style="font-family: Verdana, Arial, Helvetica, sans-serif;"><a href='files/my_file.zip' id='25' onClick='dc(this.id)' target='_blank'>Download this file</a> </span>
EXAMPLE Javascript
function dc(id){$.post("process.php",{file_id:id})}
EXAMPLE Process.php
$file_id = $_POST['file_id'];
mysql_query("UPDATE file SET downloads = downloads + 1 WHERE id = " .$file_id);
I tried to adapt this example to my code, like this:
HTML
echo '<br><a onClick="sumar(this.id);" href="http://'.$result['WEB'].'" id="'.$result['ID_PAG'].'" target="_blank">'.$result['WEB'].'</a><br />';
Javascript (In head section)
function sumar(id){($.post("suma.php",{pag:id})}
Suma.php
$pag=$_POST['pag'];
$mysqli->query("UPDATE lapag SET visitas=visitas+1 WHERE id_pag=".$pag);
Thank You!

Are you sure you have the apostrophs right? I c/p html part into eclipse and it did not particularly like it.
echo "<br><a onClick='sumar(this.id)'";
echo "href='http://".$result['WEB'] . "'";
echo "id=". $result['ID_PAG'] . 'target="_blank">';
echo $result['WEB']. "</a><br />";
I have broken it up into several echoes in order to make it clearer and easier to handle.

HTML
<?php echo $result['WEB']; ?>
Sumar.php
$pag=$_GET['ID_PAG'];
$mysqli->query("UPDATE lapag SET visitas=visitas+1 WHERE id_pag=".$pag);
header("Location: http://".$_GET['WEB']); // redirect
exit();

Think best practice should look like this:
<a href="http://random.org" onclick='called(event, this, "clicked")'>Visit site</a>
function called(event, link, id){
event.preventDefault();
event.stopImmediatePropagation();
var theUrl = "counter.php";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange=function(){
if (this.readyState != 4) //4 means call is finished - we just want to switch side after the counter-call finished
return;
window.location.href = link.href.value;
};
xmlHttp.open("GET", theUrl, true);
xmlHttp.send("id="+id);
return false;
}
Example: http://jsbin.com/porotobuna/1/edit?html,js,output
In the counter.php just get the get variable "id" (which represents the clicked link) and handle the counter (I recommend some kind of database)

Related

How can I run a php script when a user clicks a link without redirecting to that particular php page, and download an mp3 file at the same time?

I have an mp3 file whose downloads value am counting and updating well in a MySQL database when I run my php script by going to the scripts address in the address bar like this https://groupkse.net/music_files/countDownloads.php?id=3. My issue is I want to run this php script without redirecting my browser to this location, when a link is clicked to download that mp3. NB: The mp3 is in the same directory with the countDownloads.php and the page containing the link is in a different directory, but on the same server, i.e. https://groupkse.net/songReleaseHtml/megaMuQuarantine.php
Code from countDownloads.php is below:
<?php
//Make connection with database
$conn = mysqli_connect("localhost", "groupkse_music_admin", "my_Password", "groupkse_music_downloads");
//Check connection
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exiit();
}
//Passing which song needs download increment
$incomingData = $_SERVER['QUERY_STRING'];
$data = substr($incomingData, strpos($incomingData, 'id=') + 3);
$id = mysqli_real_escape_string($conn, $data);
//echo "$id";
$query = "UPDATE `music_downloads` SET `downloads_number` = `downloads_number` + 1 WHERE `Id` = '$id'";
mysqli_query($conn, $query);
?>
And code from my link in the megaMuQuarantine.php:
Download MP3
Download MP3
Add this input to point to the php file that counts downloads.
<input type="hidden" id="downloadCounter" value="LINK TO COUNTER" />
Put this at the bottom of your web page:
<script>
document.getElementById("dButton").addEventListener("click", function(event){
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
location.relod;
}
};
xhttp.open("GET", document.getElementById("downloadCounter").value(), true);
xhttp.send();
});
</script>
To execute a PHP code without actual page action requires AJAX as pointed out by #nikistag; security issues being secondary as per now. For file downloads, this can be tricky and I would advice that you go with the 'download' attribute for html5. If such links with download attribute is clicked, it will download the file - major file types already covered. Now figure out a way to create this dynamic link; you can easily do this with jQuery or pure JS and perform auto-click on it when your button is clicked.
//hide this somewhere in your current page
<a id="choiceMusic" href="../music_files/default_music.mp3" download>
//to change href according to choice, use something like this in that master function
var currentMusic = "../music_files/"+ chosenOne.mp3;
$("#choiceMusic").attr("href", currentMusic);
//when ready to call this; //if fails, try: $('#choiceMusic')[0].click(function(){});
$('#choiceMusic').trigger('click');
Ensure that all these happen after the document if fully ready
$(document).ready(function(){
//safe to do your staff now,
});
Now call your master function and don't forget to include your Ajax function for updates
I put together the information from the above answers and came up with a solution that works for me. I hope it's a practice that is allowed!
Made two interdependent links with one of them invisible:
Download MP3
<a href="../music_files/mu_quarantine.mp3" download id="downloadSong" hidden></a>
Some AJAX and another JavaScript function to run my PHP file in the background and auto click the invisible link:
var dButton = document.getElementById("dButton"),
hidden_dLink = document.getElementById("downloadSong");
// Act on clicks to a elements
function downloadMP3() {
// Clicks the hidden anchor tag
hidden_dLink.click();
}
$(document).ready(function () {
$('#dButton').on('click', function () {
$.ajax({
url: 'https://groupkse.net/music_files/countDownloads.php?id=3',
method: 'GET',
xhrFields: {
responseType: 'blob'
},
success: function (data) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'file.mp3';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
});
});
If there is a way in which this code can be properly written, I would appreciate the guidance! Like I have earlier said somewhere, am new to programming. I further need to refresh a certain element where am echoing the id value from my database after the ajax has run successfully so that the number of downloads is updated on link click.

PHP/AJAX application label won't load

I have an ajax/php application which you can download from dropbox.
it's here:
https://www.dropbox.com/sh/zkca8peed97ieiu/AABwKVf_vP6s0BnQpxCcAeWZa?dl=0
the HTML code is rendered but the div tag isn't as I think the page is not interactive because the javascript file foodstore.js won't render.
Does anyone know any fixes?
The app should when typed in tell you whether the current product is in stock or not with the div tag underInput.
Here's the javascript then HTML,
//Create object that's responsible for communicating with server behind the scenes.
var xmlHttp = createXmlHttpRequestObject(); //a function name which is to be built now.
//awesome object which allows you to communicate with server without having to
//refresh the page.
function createXMLHttpRequestObjecct() {
var xmlHttp;
//work for IE!
if(window.ActiveXobject){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
xmlHttp = false;
}
} else { //work for other browsers
try {
xmlHttp = new XMLHttpRequest(); //built-in function doesn't need to be coded itself.
}catch(e) {
xmlHttp= false;
}
}
if(!xmlHttp)
alert("Unfortunately we cannot create the object");
else
return xmlHttp; //function needs return statement otherwise variable won't equal anything
}
/*----------------------------------------SAMPLE CODE FOR EVERY AJAX PROGRAMME ABOVE -------------------------------*/
//Heart of being able to communicate to the server with ajax.
function process() {
//this process function is responsible for taking the object created above
//and sending the request to the server
//xmlhttp is the object we are testing for.
//if 0 and 4 it means the object is free and ready to communicate with server
if(xmlHttp.readyState==0 || xmlHttp.readyState==4) {
food = encodeURIComponent(document.getElementbyId("userInput").value);//document is webpage .value
//is the value that the user types into the input box.
//build-in function to communicate with the server
xmlHttp.open("GET", "foodstore.php?food="+food,true);//creates request to send to the server.
//As php accepts info one of two ways ie GET and POST
//false/true if ajax request should be done asynchronously as in without refreshing the page.
//.open function creates the type of reqeust that we want.
//Communicate with the webserver
xmlHttp.onreadystatechange = handleServerResponse;
//Send to the server
xmlHttp.send(null); //the parameter used is only used with post. we are using get, that's why it's null.
}else {
setTimeout('process()',1000); //is object ready to communicate or busy.
//if busy wait and try again.
}
}
function handleServerResponse() {
//Server will send an XML file in between the <response> tags.
//first we check object for errors.
if (xmlHttp.readyState==4) {//state no.4 when object is done communicating with the server
if (xmlHttp.status==200) { //200 means that communication went okay with the server.
xmlResponse=xmlHttp.responseXML; //extracting xml from foodstore.php so the
//xml response is basically the new xml.
xmlDocumentElement = xmlResponse.documentElement;//documentelement is the root
//element of the xml file. the document element is where we pull everythin else
//from.
message = xmlDocumentElement.firstChild.data; //.data gets data from xml file
//gets the message from the server, in between the response tags.
//Set the inner html, part that shows to the user equals to a blue color messag.e
document.getElementbyId("underInput").innerHTMl = '<span style="color:blue">' + message + '</span>'; //innerHTML is html inbetween the div
///the stuff that shows on the webpage.
setTimeOut('process()',1000);
} else {
alert("Something went wrong!");
}
}
}
//STEPS:
//1. Creates the object for communication
//2. Communicatse with the server
//3. Update your webpage, create an element or do something cool
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()"> <!--Function will be inside javascript and will kickstart ajax programme. -->
<h3>The Chuff Bucket</h3>
<p>Enter the food you would like to order:</p>
<input type="text" id="userInput"/>
<div id="underInput">
</div>
</body>
</html>
and here's the PHP file from the project file , it's foodstore.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
header('Content-Type: text/xml'); //we're going to be generating xml content.
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food']; //store user data in this variable.
//can send things to PHP in one of two ways using either get or post.
//we use get because it's more simple.
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food,$foodArray))//takes two params. name of variable and the array itself.
echo 'We do have '.$food.'!';
elseif($food=='')
echo'Enter a food you idiot';
else
echo'Sorry we have none of '.$food.'in stock!';
echo '</response>';
?>
And basically when you type something in it should tell you whether that item is in stock or not. It won't do that and I can't quite understand why.
I have double checked that the code is typed in correctly. Have I made any syntax errors?
Kind regards,

jQuery load PHP that display flash content

What my php side does is load data use 'id' from database, and then show the raw data of swf files.
The code of php like this:
<?php
if(isset($_GET['id']))
{
include ('database.php');
$record = mysql_query("SELECT `Flash`, `FlashBlob` FROM `information` WHERE `id` = '". $_GET['id'] ."'; ", $link);
$swf = mysql_fetch_array($record);
mysql_close($link);
header("Content-type: " . $swf['Flash']);
echo $swf['FlashBlob'];
exit;
}
So if I just load the php in the web link, it goes well( the whole php page will show the flash I stored in database).
In my main page, I want to load the page into my div($("#gameArea")), I have tried:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", 'api/swfInfo.php?id=' + id,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('gameArea').innerHTML=xmlhttp.responseText;
}
}
but the result is it load only raw data( binary data) not the flash(swf file to be shown), what should I do?
I even not sure whether I should find a flash plugin for my flash or not
because I put my flash(swf file) in the database for some reason......
Please help me for the direction, thanks in advance!
Your overcomplicating the problem. If in-fact your swfInfo.php is outputting the swf file's bytes with a content type of application/x-shockwave-flash all you need to do is set the data attribute of your <object> tag to that URL.
<object type="application/x-shockwave-flash" data="api/swfInfo.php?id=7">
<param /> <!-- parameters -->
</object>
I would also recommend a content-length declaration to ensure your connection closes properly when loading files this way.
header('Content-length: ' . mb_strlen($swf['FlashBlob']));
header('Connection: close');
Try the following:
header('Content-Type: application/x-shockwave-flash');
header("Content-Disposition:attachment; filename="test.swf");
My questions are:
What is $swf['Flash'] ? Maybe there is the error?
Have you tried your script with a file_read_content() just for debugging reasons?

Php & code injection

The website for a client of mine continues to be "hacked" (I didn't do the website).The hacked pages contain a js script that loads an image and audio from youtube (Lol). Every page was modified and every page has a "news banner" .I'm pretty sure the problem is this part
<?php
$ul = new NewsList;
$ul->Load(3);
if($ul->Current() == null){ ?>
<?php }
else{
for(; $ul->Current() != null; $ul->Next()){
$new = $ul->Current();
the complete implementation of this NewsList : http://pastebin.com/WuWjcJ4p
I'm not a php programmer so I don't get where the problem is....I'm not asking that someone going to explain every line, maybe only an advice , thank you
Sounds like an SQL injection.
I believe the loadById() method is injectable (depending on how you call it).
Here is a way to strengthen it :
function LoadById($id){
$this->news = array();
$this->current = 0;
$this->total = 0;
$ndb = new NewsDB('news');
$result = $ndb->_query("SELECT * FROM ".$ndb->table." WHERE id = " . intval($id));
$new = mysql_fetch_assoc($result);
$n = new News($new['id'], $new['titolo'], $new['data'], $new['contenuto'], $new['img']);
array_push($this->news, $n);
unset($n);
$this->total = 1;
}
Someone might have stolen the passwords from administration using this security flaw and edited the articles from the back-office.
So I suggest you change this code, then change the passwords, delete all php sessions, and finally edit your articles to remove this "news banner".
Note that it might as well be a stored XSS.
Do you have a system which allows to comment the news?

Get webpage and read throug it using javascript

Hi i have a quick question, say that you would like to connect to a website and search it for what links it contains, how do you do this with javascript?
I would like to do something like this
Var everythingAdiffrentPageContains = //Go to some link ex www.msn.se and store it in this variable
var pageLinks = []; var anchors = everythingAdiffrentPageContains.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
We can assume here that we have acces rights to the site so this is not of a concern.
In other words I would like to go to some site and store all that sites Hyperlinks in an array, how would you do this in javascript?
Thanks
EDIT since pointed out Im not trying to connect to another domain. Im trying to connect to another apache webserver inside my lan that hosts a website that I would like to scan for links.
Unfornuatley I do not have PHP on my webserver :/ But a simple javascript would do it
for example go to X:/folder/example.html
Read it, and store the links
Unfortunately - You can't do this. "We can assume here that we have acces rights to the site"...that's a false assumption from a JavaScript point of view, if the page is on another domain. You simply can't access content on another domain (not HTML content anyway) via JavaScript. It's prevented by the same-origin policy, in place for several security reasons.
I suggest you to use a JS framework that helps you to retrieve elements and do stuff with DOM easily.
For example using mootools you could achieve this writing some code like this:
var req = new Request.HTML({
url:'./retrieve.php?url=YOURURL', //create a server script to "retrieve" the html of another domain page
onSuccess: function(tree,DOMelements) {
var links = [];
DOMelements.getElements('a').each(function(element){
links.push(element.get('href'));
});
}
});
req.send();
The retrieve.php page should be written for example in this way:
<?php
$url = $_GET['url'];
header('Content-type: application/xml');
echo file_get_contents($url);
?>

Categories

Resources