Ajax visit link without actually visiting link - php

I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.

use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>

Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly

Related

jQuery AJAX request not firing when posting to a php script.

I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".

php check if link clicked

The question is that how do i check if a link has been clicked?
+
+
(another document)
<?php
session_start();
$_SESSION['car'] = $_SESSION['car'] + 1;
$_SESSION['boat'] = $_SESSION['boat'] + 1;
header("Location: betalning.php");
?>
The first a tag add a car to the cart and the second a tag add a boat to the cart. How do i detect which one of the a tag that has been clicked, and if i now click on any of the a tags both a car and a boat will be added to the cart.
You can add GET parameters to the links:
Add car
And then in your PHP document:
if($_GET['add'] == 'car'){
$_SESSION['car'] += 1;
}
// etc...
This is basically the easiest way to pass data from one page to another using a link.
The concept that you should use. is Ajax.
Every click and others things with the browser only happens on the client ( browser ).
Then when you do click. The browser has send request to server.
The server, get values that you send from browser and it proccess.
Some simple may be:
// Html
<a id="linkone" href="laggtill.php">+</a>
<a id="linktwo" href="laggtill.php">+</a>
//Javascript
// Use jquery
$("#linkone").on("click", function(){
//function that send request to server
$.post('someurl.php', {})
.success(function(res){
console.log(res);
// If you stay here, the procces should be ended
})
// if you return false, the click dont redirect other window
// if you return true, the click redirect other window
return false;
});
// php file for first link
<?php
//capture values
// But only is a clic, then there is not values
session_start();
$_SESSION['car'] = $_SESSION['car'] + 1;
// If you want some simple, one file only works for one link
// For the other link, you should create other file same to this.
header("Location: betalning.php"); // With ajax dont use this line,
?>

How can i use jQuery/AJAX to load a page and send data?

I will try to word this as clearly as possible.
So I have a link which upon a click will submit some data to my database.
<a href='' id='likePost' ><i class='fa fa-thumbs-up'></i></a>
So when this link is clicked, I would want some data that is relevant to the "post" sent to the PHP file which will then process to the MySQL database.
The current jQuery I have is as follows:
<script type="text/javascript">// <![CDATA[
$(function(){
$("#likePost").click(function(event){
$.ajax({
type:"POST",
url:"functions/likePost.php",
data:"post=<?= $post['unique_post_id'] ?>",
success:function(html){
alert("Liked post = success")
}
});
});
// ]]></script>
One thing at this stage that i'd like to point out is each post has a unique ID which can be called upon with $post['unique_post_id'].
My PHP file code is:
<?php
session_start();
require_once("../global.php");
$unique = $_POST['post'];
/* FIND USER ID OF TARGET (OWNER OF POST) */
$findID = $connection->query("SELECT userid FROM posts WHERE unique_post_id='{$unique}'");
$id = $findID->fetch_assoc();
/* INSERT LIKE INTO DB */
$time = time();
$qry = $connection->query("INSERT INTO posts_likes (id, from_user_id, target_user_id, unique_post_id, time) VALUES (NULL, '{$_SESSION['SESS_MEMBER_ID']}','{$id}','{$unique}', '{$time}')");
?>
However none of this works. I'm pretty sure that there's something wrong with the AJAX code. Any idea's how I can achieve this?
Just as a quick summary, what I need is:
CLICK --> TRIGGER AJAX CODE? --> LOAD PHP FILE WITH ADDITIONAL DATA ATTACHED (unique post id) --> PHP FILE INSERTS QUERY.
Hope I've been as clear as possible, thanks in advance :)
(If I seem nooby, my age might be a reason: 15)
You should open up your browser console and see what errors are being thrown.
Base off of what script I've read your data definition looks wrong, I believe it wants an object like
$.ajax({
data: { post : '23', id: '32' }
});
And you should prevent the default click from reloading your page by using no href attribute or href="#" or by using
$('element').click(function(e){
e.preventDefault();
}

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

Combine JQuery/PHP to log clicks into database?

The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston"
success: function(data){
alert('done');
});

Categories