Changing url from JavaScript code and adding another value - php

I have following mysql query:
$colname_profile = "-1";
if (isset($_GET['user'])) {
$colname_profile = $_GET['user'];
}
mysql_select_db($database_conn, $conn);
$query_profile = sprintf("SELECT * FROM users WHERE user_id = %s", GetSQLValueString($colname_profile, "int"));
$profile = mysql_query($query_profile, $conn) or die(mysql_error());
$row_profile = mysql_fetch_assoc($profile);
$totalRows_profile = mysql_num_rows($profile);
and following JS part of code I need to change:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"),
now, how do I add another value inside JS code from above query which should be in format of
user='.$row_profile['user_id'].'
so I need to keep whats already inside that JS url and at the end add that user ID. In case you need complete JS here it is
<script type="text/javascript">
$(document).ready(function(){
$("#loadmorebutton").click(function (){
$('#loadmorebutton').html('<img src="../images/body/icons/ajax-loader.gif" />');
$.ajax({
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"),
success: function(html){
if(html){
$("#historywrapper").append(html);
$('#loadmorebutton').html('Load More');
}else{
$('#loadmorebutton').replaceWith('<center>No more posts to show.</center>');
}
}
});
});
});
</script>
Thanks for help.

maybe change url line to something like this:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "&user=<?php echo urlencode($row_profile['user_id']); ?>",

Given the way the question is asked, this will work:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "user=<?php echo $row_profile['user_id']; ?>",
However I don't know if that is what you are looking for. Is $row_profile['user_id'] only a single value on a page or is this like a list of users and for each row in the table is there a different $row_profile['user_id'] that might exist? If this is a single value, for example the user_id of the user visiting the page and you want to pass that along with every ajax request, you might be better off storing that value is sessions elsewhere as it is unlikely to change unless the user logs out and back in under another account.

Related

Increment MySQL value on click with +1

What I have
An url like this: http://localhost:8888/website/?key=ABC
A MySQL table with many rows, one with a key called ABC. I have a button that I want users to click (upvote) the MySQL row corresponding to key=ABC.
In my scripts.js I have this (incomplete?) Ajax code:
function increment() {
$.ajax({
type: 'POST',
url: '../js/ajax.php',
success: function(data) {
alert("function saved: " + data);
}
});
}
And my ajax.php looks like this:
<?php
if (isset($_GET['key']) {
$rowKEYtest = $_GET['key'];
$sql2 = "UPDATE database SET Score = Score + 1 WHERE UniqueKey = '$rowKEYtest'";
$conn->query($sql2);
} else {
echo "lol";
}
?>
It's not updating. I have no idea what to do.
Please have a look in your code, There is 2 mistakes.
1. In your ajax call you are using type: 'POST', you should use GET.
2. You are nor parsing your 'key' param in ajax call.
Actually you are using POST method in ajax but in ajax.php trying to get the value with GET method. second thing you are not passing any param in ajax call.
Hope this will help.

tooltipster dynamic content does not work

i'm very frustrated, because i can't find the answer how can i show tooltip with ajax dinamic content. If i use static contet it works, but it doesn7t work with dinamic contect. Can you please help me?
Here is my tooltipster script:
<script type="text/javascript">
$(document).ready(function () {
$('.pomoctools').tooltipster({
multiple: true,
content: 'Loading...',
functionBefore: function (origin, continueTooltip) {
continueTooltip();
// next, we want to check if our data has already been cached
//if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'POST',
url: 'person/index_person_test.php',
success: function (data) {
// update our tooltip content with our returned data and cache it
origin.tooltipster('content', $(data)).data('ajax', 'cached');
}
});
}
});
});
Then I have this php page (here is just the code for displaying the data of person: person/index_person_test.php) :
$person_id = $_GET['person_id'];//person id
//find person's data
$sql = mysql_query("SELECT * FROM person WHERE person_id='$person_id'");
$row = mysql_fetch_array($sql);
$titleText = stripslashes($row[person_name]);
$sql = mysql_query("SELECT user FROM `users` WHERE id='$row[user_id_updt]'");
$user_name_updt = mysql_fetch_array($sql);
echo $person_id;
I want to show the tooltipster on my other php page, let's call it cast.php, here is just the part for tooltipster:
echo '</td>
<td width="100%" valign="top">'.$row[person_name].'</div>';
So my problem is that the toltipster does not show data when hovering on the link in cast.php.
If i change in person_index_test.php to:
$person_id = $_POST['person_id']; //person id
it does not help.
If i go to "person/index_person_test&person_id=56774"
the data is displayed correctly and if i echo the person id, i get the correct value:
echo $person_id;
I know i need to change things in javacript to fetch my mysql data correctly, but i can't find the answer. I have tried also adding to my jaascript after
url: 'person/index_person_test.php',
data: person_id,
or
data: 'person_id'
or
data: { 'person_id': person_id},
I have tried everything but it doesn't work.
If i cange in my javascript to static person_id then the tooltipster shows the content, but of course on hover the data is always the same. So for static i have changed this:
$.ajax({
type: 'POST',
url: '**?main=person/index_person_test&person_id=56774**',
success: function(data) {
would you please help me? I have read all the tooltipster questions here on ostackoverflow, but i can't find the answer...
Thanks! Misko

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.

Multiple one-time PHP database updates using jquery's .error()

I have a webpage with some broken images, these images are being show by a database. I am using the following jQuery to hide the images that are broken.
//images are wrapped in an anchor
$("img").error(function() {
$(this).parent().hide();
});
I would like to utilize the "status" column in the database to set all of the broken images to "hidden". Every anchor that wraps an image on the page has a "id" attribute that matches the primary database key "id".
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: "status=hidden&id=".error.""
});
});
// changestatus.php
<?php
mysql_connect("localhost", "stackoverflowexampleuser", "stackoverflowexamplepass") or die(mysql_error());
mysql_select_db("stackoverflowexampledatabase") or die(mysql_error());
$id = $_POST['id'];
$status = $_POST['status'];
$query="UPDATE stackoverflowexampletable SET status = '".$status."' WHERE id ='".$id."'";
mysql_query($query) or die ('error');
mysql_close();
header( 'Location: MYSOURCE' ) ;
?>
This is my first stab at ajax, and I know I got some stuff seriously wrong. I saw a couple of examples using KEY VALUE pairs but I don't know what the $_POST['var'] should be.
Can you even request something like this "when the page loads"? I tried wrapping it in an arbitrary button and it didn't work.
Since this just needs to be used once I'm not really focused on using AJAX.
Try this:
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: {
status: "hidden",
id: error
}
});
});
If you're wanting to initiate it on page load, be sure to include it in the $(document).ready() function.

ajax POST not working, can't figure why

I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.

Categories