Getting id from link and using it in javascript - php

I have a x number of links on my website like this:
www.link1.com
www.link2.com
www.link3.com
On the bottom I have a little Javascript that is supposed to do something with the value of the clicked link.
$('#UseLink').click(function(e){
var url = "www.domain.com/uselink";
$.ajax({
type: "POST",
url: url,
data: {'linkid' : this.getAttribute('value')},
success: function(data)
{
console.log("Use link result: " + data);
if (data === 'success') {
}
if (data === 'error') {
}
}
});
e.preventDefault();
});
No matter what link I click, it always uses the id of link1. Anyone knows why this is not working?

Id's have to be unique. So do following changes:
www.link1.com
www.link2.com
www.link3.com
JS:
$('.UseLink').click(function(){
var id = $(this).attr('id');
// id contains the id of clicked anchor
});

ID must be unique, you have assigned same IDs to all the a tags.
That is why jquery script is hitting the first element.

var value = $( this ).val();
use this above the ajax call and pass the value data

There probably are plenty of methods to do this with pure javascript but since it has the PHP tag I will give you an answer involving php.
<?php
$id = isset($_GET['id']) ? $_GET['id'] : false;
?>
<script type="text/javascript">
var id = '<?= false !== $id ? $id : ""; ?>';
$('#UseLink').click(function(e){
var url = "www.domain.com/uselink";
$.ajax({
type: "POST",
url: url,
data: {'linkid' : id},
success: function(data)
{
console.log("Use link result: " + data);
if (data === 'success') {
}
if (data === 'error') {
}
}
});
e.preventDefault();
});
</script>
The links to trigger this code:
Link 1
Link 1
Link 1

First you need to know the difference between id and class. Id must be unique throughout the page. You can visit this link https://css-tricks.com/the-difference-between-id-and-class/ to learn the id and class.
And according to your problem, if you change id to class, I think it will go good.
Thanks.

Related

Insert the hyperlinks source in mysql table by clicking it

click me
I have to send abc.html into a table in my database when I click the link
There are different ways of achieving what you are trying to do.
I think though the "cleanest" would be to use jquery (javascript) to manipulate the event handler.
Something like this would work:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
click me
</div>
<script>
$(function() {
$("a").click(function (e) {
var url = $(this).attr("href"); // Here we retrieve the href of clicked link
var res = $.ajax({
type: "POST",
data: {
url: url // The left side is the request key ( so: $_POST['url'])
},
url: "https://url/to/handler.php",
async: false
}).responseText;
console.log(res);
if(res == "success") return true; // returning true lets the browser follow the link
else return false; /* so if it didn't work, the link will not be
followed. Of course you can do at these two
points whatever you like. */
})
});
</script>
Simply echo in PHP success if the insert was successful.
Note though that async:false for AJAX requests is deprecated.

How to clear the inner results of an auto suggest div when value is erased?

Following is my auto suggest code created using jquery
$(document).ready(function(){
$(".input_search").keyup(function()
{
var finder = $(this).val();
var queryString = 'key_wrd='+ finder;
if(finder==''){//check if search is empty}
else
{
$.ajax({
type: "POST",
url: "searcher.php",
data: queryString,
cache: false,
success: function(html)
{
$(".display_found_query_cont").fadeIn();
$(".display_found_query-window").append(html);
}
});
}return false;
});
});
This code closes the suggest window and clears the enterse text
$(document).mouseup(function (e)
{
var search_res_container = $(".display_found_query_cont");
if (!search_res_container.is(e.target)&& search_res_container.has(e.target).length === 0)
{
search_res_container.fadeOut().html();
$(".search_field").val('');
}
});
what do i want to do ?
I want the results displayed to be cleared when the text entered is erased
So how do i do that?
try this code:
if(finder=='')
{
//check if search is empty
$(".display_found_query-window").html('');
}
As per your comment, you want to replace the old content with new result. So just chnage the below line in your ajax success.
$(".display_found_query-window").html(html);

Show/hide div with jQuery and AJAX not working properly

I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)

Toggle Jquery form Posts

I have a simple toggle button that the user can use to either subscribe or unsubscribe from a group they belong to. I have 2 forms that get the post and depending on which page the form posts to, the user is subscribed or unsubscribed. Here's my code and I'm looking for a better way to do this. Currently, my user can click to subscribe or unsubscribe but he or she will have to reload the page to change their setting. In other words, it works fine but there's no toggle...users can't click back and forth between subscribe and unsubscribe, as they have to refresh the page and resubmit. I also would love to fix the toggle function. Thanks for any help.
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataString,
success: function(){
$("#subscribe").removeClass("notifications_subsc");
$("#subscribe").addClass("not_subscribed_group");
}
});
});
});
</script>
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#notsubscribed").click(function(){
$.ajax({
type: "POST",
url: "groupnotificationsoff.php",
data: dataString,
success: function(){
$("#notsubscribed").removeClass("not_subscribed_group");
$("#notsubscribed").addClass("notifications_subsc");
}
});
});
});
</script>
There's no need to rely on parsing out the query string when server-side scripting is available. Instead, when the page is initially served, arrange for PHP to write the group_id value into (eg.) a hidden input field, which then becomes available client-side to be read into javascript/jQuery. (Other techniques are available)
It's also a good idea to arrange for your "groupnotifications.php" script to receive a $_POST['action'] instruction to either subscribe or unsubscribe. That way the client-side half of the application exercises control.
With those changes in place, the code will be something like this:
$(function() {
$("#subscribe").click(function(){
var $s = $(this).attr('disabled',true);//disable button until ajax response received to prevent user clicking again
var clss = ['not_subscribed_group','notifications_subsc'];//The two classnames that are to be toggled.
var dataOj = {
owner : $s.closest(".groupContainer").find('.group_id').val(),//relating to element <input class="group_id" type="hidden" value="..." />
action : ($s.hasClass(clss[0])) ? 1 : 0;//Instruction to 1:subscribe or 0:unsubscribe
};
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataObj,
success: function(status) {//status = 1:subscribed or 0:unsubscribed
switch(Number(status)){
case 1:
$s.removeClass(clss[1]).addClass(clss[0]);
break;
case 0:
$s.removeClass(clss[0]).addClass(clss[1]);
break;
default:
//display error message to user
}
}
error: function(){
//display error message to user
}
complete: function(){
$s.attr('disabled',false);
}
});
});
});
untested
Note: The statement $s.closest(".groupContainer").find('.group_id').val() relies on the hidden input element having class="group_id" and allows for multiple groups, each with its own toggle action, on the same page. Just make sure each group is wrapped in an element (eg div or td) with class="groupContainer".

there is something wrong with this Jquery post?

im trying to pass on the id attribute to the file.php, but its giving me 0 every time, when i try to insert it into the database, the javascript and the html is provided!
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "file.php",
data: info,
success: function(){}
});
$("#follow"+I).hide();
$("#remove"+I).show();
return false;
});
});
html file:
<div id="follow1"><span class="follow_b"> Follow </span></div>
p.s. it deos insert the value in the database
file.php:
<?php
$id =$_POST['id'];
msql_insert.........
?>
It may not matter in this case, but the ID of an element is not supposed to start with a number.

Categories