load revelant data when clicking on link using jQuery - php

Hey, I'm trying to make an Address book for my site and I was thinking of having two panes. The one on the left to have Contact names, and the one on the right to have the contact details.
I can get the Contact pane loaded up using a while loop to cycle through my query, but then I was thinking that I really had no Idea how to load the details of that contact when the user clicks on a specific contact name.
How would I be able to approach this problem?

If you have something like:
<div id="contactNamesPane">
<ul>
<li>Doe, John</li>
</ul>
</div>
<div id="contactDetailsPane">
</div>
$('contactNamesPane a.names').click(
var thisContactId = $(this).attr('id');
$('contactDetailsPane')
.load('http://path/to/script.php?contactId=' + thisContactId + ' #' + thisContactId);
);
This has the assumptions that you have a php script to generate the contact details (located at http://path/to/script.php and this script can take a GET variable in order to show the particular individual.
It also assumes that this data will be placed inside an element of an id equal to the contact's name.
A vaguely coherent demo's posted on my server at: http://davidrhysthomas.co.uk/so/loadDemo.html

When you create the list on the left add the id of the contact to the rel
<ul id="contacts">
<li>Name Here</li>
...
</ul>
Then with jquery you can use the rel attribute and peform a ajax request to a php page that returns the info of the contact with that id
$("#contact a").click(function() {
var id = $(this).attr("rel");
$.get("url_of_php_page", { id: id },
function(data){
// do something with the data
}
);
});
use jquery.data instead

Related

How to fix cant retrieve data with jquery

i should tell you my code is actually work, but a litle bit of annoying problem i cant solve by my self.
The problem is i only can retrieve the first record(id) from my data grid but i cant retrieve the second or other record id
example :
when i click my edit button of my first record of my data then i want to send the id to my jquery and show it in console and use it for selecting data form database (this is work)
but when i click edit of my second record of my data it wont send data to my Jquery and show it in console
This is my Grid code
<?php foreach($data['gakubu_data'] as $gakubu):?>
<li class="list-group-item d-flex justify-content-between align-items-center"><?= $gakubu['code_gakubu'];?> | <?= $gakubu['gakubu'];?>
編集
</li>
<?php endforeach;?>
</div>
</div>
this is my Jquery Script
$(function(){
$('#showUpdateModal').on('click',function(){
$('#formModalLabel').html('データ編集');
$('.modal-footer button[type=submit]').html('データ編集');
const id = $(this).data('code');
console.log(id);
});
});
Your loop creates multiple elements with the same id (id="showUpdateModal"). Id's must be unique within a document, so when you select it with: $('#showUpdateModal'), it will always return the first element with that id (since there shouldn't be any more elements with the same id).
You can solve it by using a class instead:
編集
(I removed the id and added showUpdateModal as a class instead)
Now you can register the event on the class instead:
$('.showUpdateModal').on('click', function() {
// Your current code
});

Pass the information of tags to the php and display in another page( and can also update in another page)?

I am working on a tag system:
1.you can select some tags from a list and display them in a tag container (the tag can be selected only once and the sum is limited to 10), and different tag has different colors.
2.you can delete some selected tags in the tag container
3.pass the information to the php and store in the database.
4. display the tags in another page and you can update the selected tag list in this page.
For now the first two steps has finished by javascript but I am quite confused how I can pass the selected information to the php and the database (the content and colors) so they can be displayed and updated in another page.Anyone can give me some suggestions? Thanks.
The link to the jsfiddle is http://jsfiddle.net/V9Euk/1015/
Here is the html:
<ul>
<li data-val="300"><span class="label label-morning">Morning</span></li>
<li data-val="301"><span class="label label-afternoon">Afternoon</span></li>
<li data-val="302"><span class="label label-evening">Evening</span></li>
</ul>
<div class="tagHandler">
<ul class="tagHandlerContainer" id="tag_handler">
</ul>
</div>
here is the javascript:
$(function(){
var tags = [];
function add_tag(that){
var tag = $(that).text();
if($.inArray(tag, tags)>=0|| tags.length >= 10) return;
tags.push(tag);
var singleValues = $(that).find('span').clone();
singleValues[0].innerHTML += "&times";
$("#tag_handler").append(singleValues);/*display the selected tags in the tag_handler with &times style*/
}
$("li").click(function(){
add_tag(this);
});/*add tags to the tag_container when click the li*/
$('#tag_handler').on('click', 'span', function(){
var tag = $(this).text();
var index = $.inArray(tag, tags);
tags.splice(index,1);
$(this).remove();
});/*remove the tag when click this tag in the tag_container*/
});
First of all the jsfiddle link doesn't work for me.
Now, the only way is to use http methods like POST/GET to pass the data from client to server. The implementation depends of what you like the most or better a friendly and easy to use interface, so my suggestions are:
You can create (dynamically or not) a form (with hidden fields for example) and update their values with JS and pass the data through a submit button which is an easy implementation.
An another implementation is to use Ajax if you take care of user selection and create the data structure dynamically.
In both cases, you should validate the correctness of the submitted data with php. Never trust the user or the "supposed" JavaScript restrictions.

PHP database display in same fields with different anchor tags

I've searched high and low to see if this is possible and came up empty handed. Firstly, here's my code:
<div id="information" style="display:none">
</div>
<?php $seat = mysql_query("SELECT * FROM people WHERE seat='C3-24'"); $row = mysql_fetch_array($seat); ?>
<ul>
<li> <?= $row['first_name']; ?></li>
<li> <?= $row['last_name']?> </li>
<li> <?= $row['seat']?></li>
</ul>
</div><!-- information -->
<div id="c3-24" class="seat">
<a class="trigger" onClick="document.getElementById('information').style.display='block';"></a></div>
</div>
Basically I want to update the li list when I select a div id "c3-25". Now I know that having the WHERE seat="C3-25" will only output the database row of with that but I want to reuse this structure with other locations. From what I read this isn't possible. Ideally I want to have a list of divs (c3-24 to c3-50) and display the corresponding information when the anchor tag is clicked in the li fields.
I've tried putting multiple "information" divs but the information just end up stacking on top of one another.
Any help would be appreciated.
The problem is timing. There are two very separate execution contexts worth considering to understand your problem:
page construction (PHP) - the web server creates HTML to send to the browser;
user interaction (JavaScript) - the user's browser has rendered the page and the user is interacting with it.
Since page construction time happens way before the browser gets the information, it can't possibly implement user decisions (which happen later).
The typical solution to this kind of solution is to break up the application into multiple requests. As a best practice, it's also better to split out your JavaScript into a separate file and use a technique called delegation to reduce the amount of code.
Here's how I'd do it. First, send down the page structure (PHP/HTML):
<div id="information">
<!-- leave empty -->
</div>
<div class="seats">
<div class="seat">
<a class="trigger">c3-24</a></div>
</div>
<div class="seat">
<a class="trigger">c3-25</a></div>
</div>
...
</div>
Then set up the user interaction in a separate JavaScript file:
// setup a click handler on the parent 'seats' div
document.querySelector('.seats').addEventListener('click', function(e){
// check if the target of the click was actually an anchor tag with class=target
if (e.target.classList.contains('target')) {
var
// use the text of the anchor tag to get the seat
seat = e.target.textContent,
// create an XMLHttpRequest to asynchronously get the seat details
req = new XMLHttpRequest();
// handle server result by inserting details
req.onreadystatechange = function() {
if(req.readyState === 4){
document.getElementById('information').innerHTML = req.responseText;
}
};
req.open("GET", "seatdata.php?seat=" + encodeURIComponent(seat), true);
req.send(null);
}
});
Finally, implement a separate PHP script which gets the data for a specific seat (e.g. seatdata.php). Your script should get the seat URL parameter via $_GET['seat'] and use that in your query.
Per Madara's comment, don't use the mysql_query function directly since it has been deprecated, use something better instead.

How to get the post id for the javascript Ajax call?

I have a similar to SO clone i am working on for practice. I am in the middle of coding the vote system. I would like that when the upvote/downvote button is clicked, an Ajax call gets sent with the parameters for the processing page holding the post id and the value.
The post is needed to be able to know which post to record on the processing page that the javascript calls
I have a table of posts each with a post id and a votes table with votes with a vote id, so in my votes mapping table I record the topic id along side the post id.
However I cannot work out how to dynamically give a different post id for the Ajax call to each different post? Should I create perhaps a hidden field?
How is this generally done? Thanks a lot!
Actually, you don't need to use hidden fields either. ) It may be more simple just to use the post's ID itself - or the rel attribute of upvote/downvote buttons. Like that:
HTML
<div id='post-XXX'>
<a href='#' class='upvote_post' rel='XXX'></a>
{ ... some immensely great post content goes here ... }
</div>
JS
$('.upvote_post').click(function() {
var post_id = this.getAttribute('rel');
// or var post_id = $(this).parents('div').getAttr('id').match(/\d+$/);
$.post(some_url, /* data including post_id */)
}
On Stack Overflow, every post contains <input type="hidden" value="POSTID">. When a vote button is clicked, the code seeks for this input element, and sends an AJAX request, together with this post ID.
You can have a look at the relevant code, here: http://userscripts.org/scripts/review/125051
This user script allows all (including non-registered) users to view vote counts on posts. To do so, the post ID and vote buttons have to be located.
Stripped down to the bare bones (excluding CSS), the code looks like:
<input type="hidden" value="--post id--">
<div class="vote upvote"></div>
<div class="vote downvote"></div>
// Example using jQuery:
$('.upvote').click(function() {
var $this = $(this);
$.get('/vote', {
postId: $this.siblings('input[type="hidden"]').val(),
type: $this.hasClass('upvote') ? '+1' : '-1'
}, function(data) {
// do something with server's response.
});
});
You can iterate over all buttons and raise the id of each post or they already have ids server side but then you have to tell your script these upon creation.

Ajax and PHP help

Im currently calling a php code that displays results from a mysql db by using AJAX so that the page doesnt reload!
Inside the php code, I am creating a menu where the users can chose to display only "private ads" or "all ads".
Currently, "all ads" are displayed in a div container using ajax as mentioned because I havent implemented the "show private only", which is where I need your help...
Is it possible to use AJAX to check if the user clicks on the "show private only" tab in the php code displayed, and then setting a variable to something and sending it to the SAME php code which then uses the variable to display"private ads" only, WITHOUT making a new query to mysql?
If you need more input just tell me...
SOME MORE INPUT:
This is what I want:
AJAX is used to check search criteria... AJAX sends criteria to PHP... PHP Checks mysql db for criteria and displays in tables, also creates two links, one for "all ads" and one for "private only"... PHP echoes the display tables... AJAX DISPLAYS the tables in a DIV container in the HTML page (innerhtml=blabla)
UPDATE
HERE COMES THE ADDITION I WANT: the users click on one of the links provided by the PHP code, lets say "private only", AJAX reacts and calls PHP code again ... PHP code this time displays the tables differently, filtering out all non-private ads... AJAX displays in the div container...
Is this possible, if so could you point me in the right direction please!
Thanks
If I understood correctly you want do filtering on your ads by a criteria. This could easily be done without a second query in php code. Just change your html code to add a class in advertisement entry that describes the category. Then add the buttons that will filter out the unwanted.
HTML:
Display all ads
Display normal ads
Display private ads
<div id="ads">
<ul>
<li class="normal">Advertisment 1</li>
<li class="normal">Advertisment 2</li>
<li class="private">PRIVATE Advertisment 1</li>
<li class="normal">Advertisment 3</li>
</ul>
</div>
<!-- Then add the following code to capture click events -->
<script type="text/javascript">
$(document).ready(function()
{
$('#normal_ads').click(function()
{
$('#ads li:not(.normal)').hide();
$('#ads li.normal').show();
return false;
});
$('#private_ads').click(function()
{
$('#ads li:not(.private)').hide();
$('#ads li.private').show();
return false;
});
$('#all_ads').click(function()
{
$('#ads li').show();
return false;
});
});
</script>
This was written from mind, I will cross-check it right away. OK it works.
The advantage of this is that you want have to re-query for every click of the user as all advertisements will sent the first time and JavaScript will filter out the unwanted. You can also add some effects in the show/hide through jquery's effects.
The php should just be outputting the form, so the javascript can definitely check what the form value is before sending and/or displaying the ads and do filtering based on the form value (or letting the server side of the AJAX request do the filtering).
If I understood your question correctly, you could implement it with JQuery with ease.
HTML:
Display normal ads
Display private ads
<div id="ads"></div>
JQuery:
$(document).ready(function()
{
$('#normal_ads').click(function()
{
$('#ads').html("").load("ajax_ads.php?normal=1");
return false;
});
$('#private_ads').click(function()
{
$('#ads').html("").load("ajax_ads.php?private=1");
return false;
});
});
Just add a token to the URL string which the XmlHTTP request goes to?
In other words "my.server.script.php?ads=all" or "my.server.script.php?ads=private" and examine your request variables in the PHP script to determine what to return.

Categories