Ajax: Data passing through button value not working - javascript

Problem: All the other portions of the program works. When I add data:$("#friendadd").val() it won't update the table. I believe the problem might be with the value form? I've seen others use it to get the value of textboxes but shouldn't it still work when using a submit button?
Purpose: each user on the website has an add-as-friend button next to it. When you click on that button, I want to put the userid of that user into a database "friends".
Javascript
<script>
$(document).ready(function(){
$("#friendadd").submit(function(){//Used to be .each
$.ajax({
type:"POST",
url:"getuser.php",
data:$("#friendadd").val()
});//Add data: and success:function
//$.post('getuser.php');//JSON AJAX, {UserId:"13", FriendId:"16"}
})
});
</script>
PHP and HTML; $ctk_values are each of the users
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" value="<?php echo $ctk_values[$i][4];?>"><br>
<?php
}//Ends for loop
?>
</form>
<?php
}
}
?>
getuser.php
<?php
if(!isset($_SESSION)){
session_start();
}
require "conn.php";
$gtu = $dbh->prepare("INSERT INTO friends (AskerId, AcceptorId, mutual, type) VALUES(:AskerId, :AcceptorId, :mutual, :type)");
$gtu->execute(array(
'AskerId'=>$_SESSION['UserId'],
'AcceptorId'=>$_POST['friendadd'],
'mutual'=>false,
'type'=>'friend'
));
?>

Related

How to make ajax show table list without clicking the text field

I have created a live search using ajax and it worked perfectly well. However the problem is that I need to click the input field first to show all the listed data. The reason for this may be the keyup function. I don't know what to replace that. I did tried to change to focus and so on but then ajax not showing my data at all. I am not familiar with ajax.
Here is my input code and ajax.
<p style="text-align: center">Enter your search here: <input type="text" id="search" name="search" placeholder="Enter your search here"> <b><i>ex: d1234567891.. hazwan.. etc.. </i></b></p>
<div id="result" class="login"></div>
<script type="text/javascript">
$(document).ready(function(e) {
$("#search").keyup(function() {
$("#result").show();
var x = $(this).val();
$.ajax({
type:'POST',
url:'res.php',
data:'q='+x,
cache:false,
success:function(data){
$("#result").html(data)
}
});
});
});
</script>
</div>
and here is my database code and display result.
//print_r($_GET);
$q=$_POST['q'];
$query="SELECT *
FROM
viewlibrary
WHERE
studentname LIKE :q OR
matricno LIKE :q OR
title LIKE :q OR
programme LIKE :q OR
serialno LIKE :q
ORDER BY studentname ASC";
$stmt = $db->prepare($query);
$stmt->bindValue(':q','%'.$q.'%');
$stmt->execute();
$a = 0;
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>No.Matric</th>";
echo "<th>Name</th>";
echo "<th>Programme</th>";
echo "<th>Title</th>";
echo "<th>Serial Number</th>";
echo "<th>Availability</th>";
echo "<th>Edit</th>";
echo "<th>Delete</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($r as $row){
echo "<tr align='center'><td>". ($a+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td><a href='editpage.php?idstudent=".$row['matricno']."&idbook=".$row['serialno']."'><img src='pic/edit-icon.png' width=15px></a></td><td><a href='deletepage.php?idstudent=".$row['matricno']."&idbook=".$row['serialno']."'><img src='pic/remove-icon-png-15.png' width=15px></a></td></tr>";
$a++;
}
echo "</tbody>";
echo "</table>";
}
else{
echo "<p align='center'>Nothing to show you :( I am really sorry for this T_T </p>";
}
?>
The thing everytime I do some editing towards ajax code, its not running anymore. I try looking on the internet but can't find one suitable with ajax.
So what I want actually is to show all data listed when the page loaded and not after the user click the input field.
Please help.
Have you tried moving the ajax to a separate function?
Ex.
function ajaxSearchUpdater(){
$("#result").show();
var x = $('#search').val();
$.ajax({
type:'POST',
url:'res.php',
data:'q='+x,
cache:false,
success:function(data){
$("#result").html(data)
}
});
}
$(document).ready(function(e) {
ajaxSearchUpdater(); // fires on document.ready
$("#search").keyup(function() {
ajaxSearchUpdater(); // your function call
}
}

using ajax to get a php database result and then show the result in a button

I'm attempting to create a shipping status page and I want a really basic feature to work. I want to be able to press a button on this page that says "Mark Shipped". Then I want the button's text to change to "Shipped". I then want the option to change the status of that back to "Mark Shipped', but have an alert prevent it from doing it until you click Proceed or something like that.
I am attempting to do this with php and ajax. I've never used Ajax before or too much JS, so I'm not too sure on how to use the two simultaneously.
I have created a database table that will house the status of the 'shipped' status, so whenever I click the 'mark as shipped' button the word 'shipped' will go into my db table with the id of the order and then I want the word shipped to echo back into that button and remain there indefinitely. The php query was working great until I changed the action of the Ajax script.
So this is my table...
if( $result ){
while($row = mysqli_fetch_assoc($result)) :
?>
<form method="POST" action="shippingStatus.php">
<tr>
<td class="tdproduct"><?php echo $row['order_id']; ?> </td>
<td class="tdproduct"><?php echo $row['date_ordered']; ?> </td>
<td class="tdproduct"><?php echo $row['customer_name']; ?> </td>
<td class="tdproduct"><?php echo $row['streetline1'] . "<br />" . $row['streetline2'] . "<br />" . $row['city'] . ", " . $row['state'] . " " . $row['zipcode']; ?> </td>
<td class="tdproduct"><?php echo $row['product_name']; ?> </td>
<td class="tdproduct"><button data-text-swap="Shipped">Mark Shipped</button></td>
<input type="hidden" name="product_id" value="<? echo $row['id']; ?>"/>
<td class="tdproduct"><input name="delete" type="submit" value="DELETE "/></td>
</tr>
</form>
<?php
endwhile;
}
?>
</table>
This is my Ajax script. At first I had 'shipped' as the action, but it wasn't saving the status. When I would reload the page it would go back to 'Mark Shipped'.
<script>
$("button").on("click", function(e) {
e.preventDefault()
var el = $(this);
$.ajax({
url: "shippingStatusSend.php",
data: {action: "<?php echo $shipped; ?>", order: order_id},
type: "POST",
dataType: "text"
}).fail(function(e,t,m){
console.log(e,t,m);
}).done(function(r){
//Do your code for changing the button here.
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
});
</script>
My php in a page called shippingStatusSend:
<?php
//connection to db
$con = mysqli_connect("localhost", "root", "", "bfb");
//Check for errors
if (mysqli_connect_errno()) {
printf ("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$order_id = trim($_POST['order_id'] );
$status = trim($_POST['action'] );
$shipped = "Shipped";
$markshipped = "Mark Shipped";
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "INSERT INTO shippingStatus (order_id, status, date_Shipped) VALUES (?, ?, NOW())")) {
/* bind parameters for markers */
$stmt->bind_param('is', $order_id, $status);
/* execute query */
$stmt->execute();
echo $shipped;
/* close statement */
mysqli_stmt_close($stmt);
}
while($row = mysqli_fetch_assoc($stmt)){
$shipped = $row['status'];
$markshipped = "Mark Shipped";
}
else
echo $markshipped;
?>
I am not sure what I am doing wrong, could anyone point me in the direction of what is wrong? Is it my php code or the way I'm attempting to do this with Ajax or both. Which area of my code is wrong?

2 dropdown lists dependent on each other in php include. Need to reload only the include file not the entire page

I have 2 simple drop down lists one dependent on the other in a php include.
When one is selected it refreshes the page and then populates the second with the correct data, (works great).
The problem is that it refreshes the whole page instead of just the include file.
Is there a way to do just refresh the include? I have looked at many other examples (Ajax, Javascript etc) on here and other sites and cannot seem to get it to work.
A huge thank you in advance to anyone who can point me in the right direction.
<form enctype="multipart/form-data" action="advanced_search2.php" method="POST">
<?php require 'config.php'; ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<?
echo '<div id="publication">';
echo "<select name='cat'><option value=''>Select one</option>";
$quer2="SELECT DISTINCT id,publication FROM publication WHERE appear = 'Yes' and Search = 'Yes'";
foreach ($dbo->query($quer2) as $noticia2) {
echo "<option selected value='$noticia2[publication]'>$noticia2[publication]</option>"." <BR>";
}
echo "</select>";
echo '</div>';
?>
<?
echo '<div id="section">';
echo "<select name='subcat'><option value=''>Select one</option>";
$quer="SELECT DISTINCT section FROM sandbox WHERE publication = '$cat' AND appear = 'Yes'";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[section]'>$noticia[section]</option>";
}
echo "</select>";
echo '</div>';
?>
<form>
<script>
$('#publication').change(function(){
var page = $( this ).attr('data-page');
$.ajax({
type:'POST',
url:page,
success: function(response){
$('#section').html(response);
}
});
})
</script>
wrap your second select box with a div
in you js function 'reload', call a ajax (another page) where you pass the catid and echo your second select box in that page
update your div html with the ajax response.
Your main page can look like this
<?php require 'config.php'; ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<?
echo '<div id="publication">';
echo "<select name='cat'><option value=''>Select one</option>";
$quer2="SELECT DISTINCT id,publication FROM publication WHERE appear = 'Yes' and Search = 'Yes'";
foreach ($dbo->query($quer2) as $noticia2) {
echo "<option selected value='$noticia2[publication]'>$noticia2[publication]</option>"." <BR>";
}
echo "</select>";
echo '</div>';
?>
<div id="section"></div>
<script>
$('#publication').change(function(){
$('#section').load('subcat.php?cat='+$(this).val());
});
})
</script>
And another page for getting subcat (subcat.php)
<?php
require 'config.php';
$cat = $_GET['cat'];
echo "<select name='subcat'><option value=''>Select one</option>";
$quer="SELECT DISTINCT section FROM sandbox WHERE publication = '$cat' AND appear = 'Yes'";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[section]'>$noticia[section]</option>";
}
echo "</select>";
?>

I am trying to update records by php code. but having trouble in my code

I am trying to update records by php code. but having trouble in my code.
code is running without using functions (get40(),show()) but i want to use buttons to call these functions.
code is give below:
this is main code file:
<?php
$data;
$count=0;
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
$result;
$query;
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
function get40($off='0', $rcd='2')
{
global $db,$result,$query;
$query="SELECT sword, tword, reviewed from TempDictionary LIMIT $off,$rcd";
$result = $db->query($query)or trigger_error($db->error);
}
function show()
{
global $db,$result,$query;
echo "<form action='testSave.php' method='POST'>";
echo "<table border=1 >";
while($row = mysqli_fetch_array($result))
{
global $count;
$count+=1;
echo "<tr>";
echo "<td><input type='text' name='s[]' value=" . $row['sword'] . "></td>";
echo "<td><input type='text' name='t[]' value=" . $row['tword'] . "></td>";
echo "<td><input type='text' name='r[]' size='1' value=" .$row['reviewed'] . "></td>";
echo "</tr>";
}
echo "</table>";
echo "<input type='text' name='no' size='2' value=" .$count. ">";
echo "<input type='submit' value='Save'>";
echo "</form>";
}
//get40(1,2);
//show();
mysqli_close($db);
?>
<script type="text/javascript">
function get()
{
<?php
get40(0,3);
show();
?>
}
</script>
<form action="" method="POST">
<input type=button name=btnGet value=Get onclick="get()">
</form>
and savetest.php file is:
<?php
$no=$_POST['no'];
$i=0;
$s=$_POST['s'];
$t=$_POST['t'];
$r=$_POST['r'];
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
// display
foreach ($s as $key=>$value)
{
print "$key = $value $t[$key] $r[$key]";
echo '<br>';
}
// save to DB
foreach ($s as $key=>$value)
{
// $query="UPDATE TempDictionary set sword=".$value.",tword=".$t[$key].",reviewed=".$r[$key]."
// WHERE sword=".$value;
$query="UPDATE TempDictionary set sword='$value',tword='$t[$key]',reviewed='$r[$key]'
WHERE sword='$value'";
$result = $db->query($query)or trigger_error($db->error);
}
mysqli_close($db);
?>
the problem is while i click button it does not works.
AFAIK you are trying to run PHP code with Javascript code.
Use Jquery/Ajax to solve your problem. You can Google for that or look at stackoverflow.
Step 1: Learn how a click on a button can run PHP
Run php function inside jQuery click
Step 2: Learn how to use data from a database and populate a form with it:
ajax call to populate form fields from database query when select value changes
That's the first step in solving your problem. (sorry it's no copy/paste solution, just a pointer in the right direction)

How to use the data from the row selected?

How can I collect the data on the row from the table that I select and use it in the result?
Here is the javascript I am using to show the data entry screen, once the function has been called by selecting the row. Now I just need to design a form in PHP that will include (1) some of the data from the row selected and (2) some new data that will be collected.
Here is the Javascript to select the row and call the data entry form
$(document).ready(function () {
$("tr").live('click',function(){
$.post('data_entry_form.php', function(data) {
$('#section2').html(data);
});
});
});
Here is the PHP Script
<?php
require_once "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$result = $dbh->query("SELECT aif_id, fee_source_id, company_name_per_sedar, document_filing_date FROM a_aif ORDER BY aif_id DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);
echo "<table id=\"all_aifs\">";
echo "<tr>";
echo "<th><b>Document ID</b></th>";
echo "<th><b>Pubco Name</b></th>";
echo "<th><b>Filing Date</b></th>";
echo "<th><b>PDF</b></th>";
echo "</tr>";
foreach($result as $index => $row) {
echo "<tr>";
echo "<td>$row[fee_source_id]</td>";
echo "<td>$row[company_name_per_sedar]</td>";
echo "<td>$row[document_filing_date]</td>";
echo "<td>Placeholder</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
$dbh = NULL;
?>
The "Correct" answer to this problem is NOT to read from the DOM. Never a good idea. I suggest you pass the record id to the ajax call and have the ajax call return an already-populated form.
//PHP
//place the data attribute in the tr
echo "<tr data-recordId='".$row['id']."'>";
//JS
$(document).ready(function () {
$("tr").live('click',function(){
//Get the ID from the row clicked
var id = $(this).data('recordId');
//short-hand
$('#section2').load('data_entry_form.php?id='+id);
});
});
Then your ajax page would just read $_REQUEST['id'] to get the id of the form being edited.
//Ajax side PHP
$id = (int)$_REQUEST['id'];
//Fetch data and use it to pre-populate form item
You would pre-populate your inputs like this
<input type="text" value="<?php echo $row['value']; ?>" />
or
echo '<input type="text" value="'.$row['value'].'" />';
NOTE: If your values contain quotes, you will want to replace them with the code "
echo '<input type="text" value="'.str_replace('"', '"', $row['value']).'" />';
Within the event handler, this and $(this) refer to your selected row:
$("tr").live('click',function(){
// this.cells[1] is the cell that contains Pubco Name
// You can also use $(this).children("td")[1]
...
});

Categories

Resources