getting query string php - jquery - #?id= - php

I am really stuck and was wondering if someone could lend a hand please,
i know how to get a query string, thats not a problem,
however,
I have links that use jquery to fade out the content and load the new content via links,
usage example below - class="link2" is a reference for the jquery to do what it does lol
click here
in the href i have to have the # first to stop the page from loading if you get what i mean,
now when i try and get the query string id=2 it says none as there is a # first, there is probably a simple fix for this but i must just be missing it,
i have searched and searched but still cant find the answer
----------------------edit------------------------------
this is what i am trying to do,
enter page,
sql query runs to display all the reports
click a report and the jquery hides "contmain" and shows "contreports" now a new sql query runs to display the report based on the "id"
now usually i can just get this information from the url and clean it up, hovever as i have jquery running i need to have the "#" for the href so the page does not reload and the jquery can run, but now this is stopping me from being able to retrieve the url query,
Interstellar_Coder
he seems to have the right idea, passing it in the background

Although i don't fully understand what you're doing, i'm guessing it would be better to store your querystring as a data attribute.
click here
Then in your jQuery function.
$('.link2').click(function(e){
var queryString = $(this).data('id');
e.preventDefault(); // prevent the default action
});

because of the code i thought it best to post here
i think i am getting close,
#Interstellar_Coder - this is what i have so far but it only ever retrieves the first id,
$query1 = mysql_query("SELECT * FROM `".TBL_CATCH_REPORTS."` order by id DESC");
$query2 = mysql_num_rows($query1);
if(mysql_num_rows($query1) != 0) {?>
<table width="880" style="margin:0 auto">
<?PHP while ($output = mysql_fetch_assoc($query1)) { ?>
<tr class="row">
<td width="190px"><input type="button" class="c_report"value="<?PHP echo $output['id']; ?>" />
View Report <img src="images/icons/arrow_right.png" width="16" height="16" /></a></td>
<td width="210px">Submited by <?PHP echo $output['submitby']; ?></td>
<td width="160px"><?PHP echo $output['date']; ?></td>
<td><?PHP echo $output['title']; ?></td>
</tr>
<?PHP } ?>
</table>
<?PHP }else{ echo '.Sorry there are no catch reports yet'; }?>
<div id="contreport"> content here </div>
<script type="text/javascript">
$(document).ready(function(){
$(".c_report").click(function () {
$("#contreport").html('Getting Catch Report......');
$.ajax({
type: "POST",
data: "data=" + $(".c_report").val(),
url: "reportdata.php",
success: function(msg){
$("#contreport").html(msg)
}
});
});
});
</script>
my other page "reportdata.php just gets the value and is then used in a sql statement
$getreport = '';
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$getreport = trim($_POST['data']);
}
i am assuming i need some kind of loop going on in the jquery but i am just lost, been stuck on this all day today again lol
this is all i need
id 1 - link
id 2 - link
id 3 - link
id 4 - link
id 5 - link
click on any and the id will be sent to reportdata.php where the id will be used in a sql statement, then the data returned and displayed,
its truly sending me mad lol

Related

Hello i'm trying to do multiple sorting using php mysql where i'm searching and then sorting the data

i'm printing a table in php where data is coming from mysql now i'm creating functionalities like searching and sorting so when i click on sort it sorts the data and when i click on search i get searched data now the problem is i want to perform sorting on searched data like for example i sorted the data and then i searched for words starting with a i.e i got results like adam,azan,anand so i want to perform resorting on these searched data and get data as adam,anand,azan
my approach is:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here Get Sort Content is a function calling Store Procedure SortContent which is working at first sorting
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
and i'm talking in context of large amount of data i hope i have made myself clear and if possible how can i implement ajax using mysqli
You will need to trigger an event in JavaScript, which in turn will use your HTML search input, which is then sent to the server, where a query will be executed and the results returned (as HTML) to the JavaScript code, and finally placed back on the page. At least this is how I solve my ajax searches...
So the flow could be something like:
Input -> JavaScript event -> ajax -> result -> page
Here is some code that might get you started, though I haven't tested i myself:
HTML:
<input type="text" id="my_search_input">
<div id="my_search_result"></div>
JS (jQuery):
var $inputField = $( "#my_search_input" );
var $result = $( "#my_search_result" );
$inputField.on('keyup', function(){ //triggered when a pressed key is lifted
var searchTerm = $inputField.val();
$.ajax({
url:"/mySearch.php",
method:"post",
data:{searchTerm:searchTerm},
success:function(response){ //response contains the data from mySearch.php
var parsedResponse = JSON.parse(response);
var resultHtml = parsedResponse.html; //this is the array key of what the PHP script returns
$result.append(resultHtml);
}
});
});
PHP
$searchTerm = $_POST['searchTerm']; //$_POST['searchTerm'] is what we defined in data:{... in the ajax call
// here is where you need to retrieve data from your database
// the db result needs to be processed into HTML and assigned to a variable
$html = "<div>My result based on data</div>";
return json_encode(['html' => $html]);

I need a script to change a link when clicked on it to another content

i am working on student supervision project. i wanted to create a page that contain the available project topics, when clicked on a topic of interest, to assigns the topic to the user with that 'id' and renders the link unavailable e.g a topic that has a link 'available' to change to 'unavailable'.
i will really apreciate if someone in the house can help?
Thanks
You need to use ajax for it, that way and helping with jquery you make the changes in real time
I made some small changes to perform this action with jquery
<body>
<table cellspacing="2" cellpadding="2" border="2">
<?php $sql = "Select * from prject_topic"; $result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['lecturer_name'];?></td>
<td><?php echo $row['topic'];?></td>
<td><span class="actu" id="<?php echo $row['project_id'];?>">
<?php echo $row['status'];?>
</span>
</td>
</tr> <?php } ?>
</table>
<script type="text/javascript">
$(function(){
//We capture the Click in the user item
$(".actu").on('click', function(){
//We take the ide of this item
var id = $(this).attr('id');
//We check the current status of the user
if($(this).html() == "Deactivate"){
var est = "Activate";
}else{
var est = "Deactivate";
}
//We made a request of type ajax sending by post the id for its update
$.post('#.php',
{
'id':id,
'est':est
},
//We received the response from our php file which may be a code as in the example...
function(data){
if(data=="200"){
//If yes, update the content of the selected item in real time
$("#"+id).html('Deactivate');
}else{
//In case of error, we send the information
alert("Unable to disable user");
}
})
})
})
</script>
</body>
The code is written for your understanding

Options in tables with data from database

This is a tough one to explain...
I'm developing a restaurant system where the user add the dishes available to sell, but the user has to have an option to edit/delete AFTER the dish was registered.
So what i thought was: k, gonna make a table fetching the data from the DB and in the last column put some options like edit/delete... Here is the code for better understanding:
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img src="img/icons/16/delete.png" alt="delete" height="16" width="16">'.'</td>';
echo '</tr>';
}
Like you've saw the delete option has already there (with no function/action yet) Here is the thing... I could put a link to a file in href="delete.php? but when a user clicks on this link will lead them to the delete.php page, leaving the administration page... I would like that when the user clicks the delete img, worked as/similar AJAX. I don't want the user exit the page....
Sorry for bad english (not my mothertongue), if you guys want more details just ask.
Ps: New PHP Programmer
Thanks in advance.
use javascript or jQuery to do an ajax request to delete.php with the id of the row you want to delete. I often put the id in the <tr> like echo "<tr data-id='{$row['id']}'>" and my jQuery would look something like this
$(".delete").on('click', function() {
var id= $(this).parents('tr').data('id');
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function(data, textStatus, jqXHR) {
// do something with the data returned. I usually output "success" from my
// delete.php and then check for data.indexOf('success') != -1
$("tr[data-id="+id+"]").remove();
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Error: "+jqXHR+" "+textStatus+" "+errorThrown);
}
});
});
on my delete.php page i check that $_POST['id'] is not empty before continuing. If you use $_REQUEST['id'] it will also work with a direct link to delete.php?id=999
You can call Delete.php using AJAX, so the request is executed without leaving the page.
The advantage of making an actual link to the delete page, is that it also works without Ajax/Javascript. So you can start by building a plain delete page, and add the Ajax later.
First, you should also print a record_id because just deleting based on the name is a very bad idea where encoding will hunt you down.
Having said that, here is what I would do using jQuery:
//PHP
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img class="delete-btn" src="img/icons/16/delete.png" alt="delete" height="16" width="16" data-order-id="$row['id']">'.'</td>';
echo '</tr>';
}
//JQUERY
$(document).ready(function(){
$(".delete-btn").click(function(){
$.post("/delete.php", {order_id: $(this).attr("data-order-id")}, function(){
$(this).closest("tr").remove();
});
});
});

$.ajax script not pulling php data into div

I've spent the last couple of days wrestling with a .hover script that posts data to a php script then retrieves related data from a database.
Posting id data to the details.inc.php page is working fine. An alert in the script retrieves and show's the data correctly.
The problem arises when i try to include the data in a div, nothing seems to happen. Firefox show's the script to be executing and retrieving the correct id info as it should.
I don't know where from here. I've tried all i can, but my understanding of java is limited
Thanks for any help in advance.
A mouse over function executes and retrieves the id from an image
<img src="#" class="latest" id="id_retrieved_from_DB">
id is then passed through jquery and ajax which retrieves data linked to id from details.inc.php, the data retrieved should then be included in the "details" div
<script type="text/javascript">
//Mouse over
$(function(){
$('.latest').hover(function() {
id = $(this).attr('id');
$.ajax({
cache: false,
url: "details.inc.php",
data: 'hovered_id='+id,
success:function(data){
alert(data);//showing data correctly
//not working here
$("#details").load('details.inc.php', data);
}
});
return false;
}
});
</script>
details.inc.php
<?php require_once('../../Connections/userauthentication_conn.php'); ?>
<?php
require_once('../../includes/session_remap.inc');
require_once('../../includes/tNG_functions.inc.php');
?>
<?php
$KTColParam1_rsDetails = "0";
if (isset($_GET["hovered_id"])) {
$KTColParam1_rsDetails = (get_magic_quotes_gpc()) ? $_GET["hovered_id"] : addslashes($_GET["hovered_id"]);
}
mysql_select_db($database_userauthentication_conn, $userauthentication_conn);
$query_rsDetails = sprintf("SELECT tbl_entries.id_ent, tbl_entries.country_ent, tbl_entries.date_ent, tbl_entries.title_ent, tbl_entries.subject_ent, tbl_entries.description_ent, tbl_entries.image_ent, tbl_entries.url_ent FROM tbl_entries WHERE (tbl_entries.id_ent=%s) ORDER BY tbl_entries.date_ent DESC ", $KTColParam1_rsDetails);
$rsDetails = mysql_query($query_rsDetails, $userauthentication_conn) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = mysql_num_rows($rsDetails);
?>
<!-- Details -->
<a href="<?php echo $row_rsDetails['url_ent']; ?>" title="Go to <?php echo $row_rsDetails['title_ent']; ?>">
<?php
//show if file exists
if (file_exists("../../images/entries/" . $row_rsDetails['id_ent'] . "__img.jpg")) {
?>
<img src="../../images/entries/<?php echo $row_rsDetails['id_ent']; ?>__img.jpg" width="70" height="70">
<?php
}
//end show if file exists
?>
<p class="seriesName"><?php echo $row_rsDetails['subject_ent']; ?></p>
<h4 class="programTitle"><?php echo $row_rsDetails['title_ent']; ?></h4>
</a>
<!-- End -->
<?php
mysql_free_result($rsDetails);
?>
Why are you doing a second ajax call?
If you already have the data available in javascript, you can replace:
$("#details").load('details.inc.php', data);
with:
$("#details").html(data);
if $("#details") is in the script page and that's the div you wish to display the result, you could use only load:
//Mouse over
var id = $(this).attr('id');
$("#details").load('details.inc.php', 'hovered_id='+id, function(data){alert(data);});
Or you could use $.get()
Jquery manual
The POST method is used if data is provided as an object; otherwise, GET is assumed.
And your PHP script uses get.

How do I show next result in MySQL on "onclick" in JavaScript?

I want to show a certain amount of results (say, 5) and make a:
<a href="" onclick="<?php ShowNextResult(); ?>">
And use onlick to show the next 5 results.
EDIT ::
HTML
<div id="results">
<div class="result"></div>
<div class="result"></div>
<div class="result"></div>
</div>
<a href="#" id="showMore" />Show more</a>
JAVASCRIPT
Use Jquery as below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#showMore').click(function(event) {
event.preventDefault();
$number = $('.result').size();
$.ajax({
type: "POST",
url: "getNext.php",
data: "count=$number",
success: function(results){
$('#results').append(results);
}
});
});
});
</script>
PHP
you should make a new php page (getNext.php ) that will get query results
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons LIMIT {$_POST['count']},5");
while($row = mysql_fetch_array($result))
{
echo "<div class='result'>".$row['FirstName'] . " " . $row['LastName']."</div>";
}
mysql_close($con);
?>
HELP
you can use SQL something like
SELECT x,xx,xxx FROM XxXxXs Limit $_POST['count'],5
Since you specifically mention JavaScript I assume you don't want to reload the page or anything like that. Your onClick will have to trigger an AJAX call to a php page on your server that will handle the request and give you back the next five records (or the last 5, or random ones, etc...).
JQuery is really popular for doing this and have built in functionality to make this process easier.
http://api.jquery.com/jQuery.ajax/
Here are some tutorials: http://docs.jquery.com/Tutorials
Your best bet is to write this functionality w/o using JavaScript. Make the page accept arguments to show specific records. Once you have that code done, then put the AJAX on top of it, but that way you'll have the older stuff to fall back on if you need to for compatibility or things don't work the way you need them to.
These are pretty general answers, do you need specific help making the query to only show the next 5 records? Or the specific PHP code to tie it together? Or just the JS to do the AJAX stuff? Could you be more descriptive if you need more info.
change
data: "count=$number",
to
data: "count=" + $number,
because then it isn't work!
Here's my solution that showing quiz questions partially with next button means on each click at Next Button 5 more question will display.
<?php
$strSQL="SELECT * FROM `quizes` WHERE Q1 IS NOT NULL ORDER BY RAND()";
$result=mysql_query($strSQL);
while($row=mysql_fetch_array($result)){
$c=0;
$q[]= $row['Q1']; // This is database record that has all question stored as array
?>
<?php
for($inc=0; $inc < $ret; $inc++){ ?>
<table>
<tr id="<?php echo "i".$inc ?>">
<td id="qs"> <?php print_r($q[$inc]); ?></td>
</tr></table>
<!-- here in i am display all question with loop in this variable $q[$inc] -->
<?php } ?>
// Now we are going to display partial
instead of all so data will display partially with next button
Next/Show More
//this is anchor/button on which more questions will load and display when clicked
//CSS question are placing in tr (table row) so first hide all question
<style>
tr{
display:none
}
</style>
//jquery now we will show partial question 5-questions at each click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("[id=i0],[id=i1],[id=i2],[id=i3],[id=i4],[id=i5]").show();
//Display first 5-question on page load other question will
//show when use will click on next button
var i=0;
$("#more").click(function(){ // Next button click function
//questions tr id we set in above code is looping like this i1,i2,i3,i4,i5,i6...
i=i+5; //at each click increment of 5 question
var e=i+5;
//start after the last displayed question like if previous result was 1-5 question then next result should be 5-10 questions...
for(var c=i; c < e; c++ ){
$("[id=i"+c+"]").show();
}
});
});
</script>

Categories