I have create this example code:
// Create connection
$conn = Connection();
$result = $conn->query("SELECT * FROM `users` WHERE 1");
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$name= $row["name"] ;
$id= $row["id"] ;
echo "<div class='media text-muted pt-3'>";
echo "<button class='mr-2 rounded btn-primary icon32 select_c'></button>";
echo "<p class='media-body pb-3 mb-0 small lh-125 border-bottom border-gray'>";
echo "<strong class='d-block text-gray-dark'>". $name ."</strong>";
echo $id;
echo "</p>";
echo "</div>";
}
I want to pass the id variable when the reference button is pressed using the post method. How can I do?
You can use value on the button then use ajax:
echo "<button class='mr-2 rounded btn-primary icon32 select_c' value='".$row["id"]."' onClick='ajaxpost(this)'></button>";
Now use Ajax:
js:
function ajaxpost(elem) {
var id = elem.value;
$.ajax({
url: "page.php",
type: "POST",
data: {
id: id
},
success: function(data) {
//what you want
}
});
}
Related
So what I want to do here is when I click a button(with id) it will redirect me to a page according to its id. But my error is undefined index: dataId
This is the ajax code
$(document).ready(function(){
$(".btn-clinic").click(function(){
var dataId = $(this).data("id");
var baseUrl = "<?php echo base_url(); ?>clinic/getId";
alert("The data-id of clicked item is: " + dataId);
$.ajax({
type:'POST',
url:baseUrl,
dataType:'json',
data:{'dataId': dataId},
cache:false,
success:function(data){
}
});
});
This is my code in my controller
function getId(){
$id = $_POST['dataId'];
if(!empty($id)){
echo 'not empty' + $id;
}
else{
echo 'empty data id ';
}
}
but the error is undefined index
This is the code of my view
foreach($data as $row)
{
echo "<div class='card mb-4'>";
echo "<div class='row g-0'>";
echo "<div class='col-md-4'>";
echo "<img src='...' alt='...'>
</div>";
echo "<div class='col-md-8'>";
echo "<div class='card-body'>";
echo "<h5 class='card-title'>".$row->clinicname."</h5>";
echo "<p class='card-text'>".$row->clinicname."</p>";
echo "<p class='card-text'><small class='text-muted'>".$row->clinicaddress."</small></p>";
echo "<a id='clinic' href=";?><?php echo base_url(). "clinic";?> <?php echo "value=".$row->clinicid." class='btn-clinic d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm' data-id=".$row->clinicid."><i class='fas fa-download fa-sm text-white-50'></i> See more</a>";
echo "</div>
</div>
</div>
</div>";
}
If you are using a jquery version having a version greater or equal to 1.5, you have to replace "type" with "method" this way.
$.ajax({
method: 'POST',
URL: baseUrl,
dataType: 'json',
data: {'dataId': dataId},
cache: false,
success:function(data){
}
});
I'm having trouble passing a variable in my a php file to another php file using jquery ajax. I don't know why it doesn't read it though because everytime I echo the variable it's undefined or just plain blank.
teams.php
<?php
// Display members from database
$connect = mysqli_connect('localhost', 'root', '', 'chansandbox');
if(isset($_POST['display'])){
$team = "SELECT * FROM team";
$resultTeam = mysqli_query($connect, $team);
?>
<ul class="teams">
<li><a id="teamheader">LIST OF TEAMS</a></li>
</ul>
<?php
while($arrayTeam = mysqli_fetch_array($resultTeam)){
$team_id = $arrayTeam['team_id'];
?>
<ul class="teams" name="teamId" value="<?php echo $team_id ?>">
<li><?php echo $arrayTeam['team_name']; ?>
<ul class="menu">
<li class="memberdivholder">
<div class="gradeview">
<h1 id='options'><i class="fa fa-cog"></i>
Options:
<button class="topbutton">Grade Team</button>
<button class="topbutton">View Team</button>
<button class="teamdelete">Delete Team</button>
</h1>
</div>
<?php
$member = "SELECT * FROM employee WHERE team_team_id = '$team_id' ORDER BY position_pos_id=17 desc";
$resultMember = mysqli_query($connect, $member);
while($arrayMember = mysqli_fetch_array($resultMember)){
?>
<div class="memberholder">
<h1 class="clearfix">
<?php
if($arrayMember['position_pos_id']==17){
echo "<i class='fa fa-star-o' aria-hidden='true'></i>";
}
?>
<?php echo $arrayMember['emp_fname'] . " " . $arrayMember['emp_lname']; ?>
<button class="viewprofile">View Profile</button>
</h1>
</div>
<?php
}
?>
</li>
</ul>
</li>
</ul>
<?php
}
exit();
mysqli_close($connect);
}
?>
script.js
$('.teams').on('click', '.teamdelete', function(){
var teamId = $(.teams).attr("value");
if(confirm("Are you sure?")){
$.ajax({
url: "http://localhost:81/chansandbox/wp-content/themes/Skeleton/teamdelete.php",
method: "POST",
type: "POST",
data: {
team_id: teamId
},
success: function(data)
{
alert(data);
eval(data);
}
});
}
});
teamdelete.php
<?php
$connect = mysqli_connect('localhost', 'root', '', 'chansandbox');
$team_id = $_POST['teamId'];
$update = "UPDATE employee SET team_team_id = NULL WHERE team_team_id = '$team_id'";
if(mysqli_query($connect, $update)){
echo "Employees Updated";
$deleteteam = "DELETE FROM team WHERE team_id = '$team_id'";
if(mysqli_query($connect, $deleteteam)){
echo "Team deleted '$team_id'";
}
else{
echo "Team not deleted";
}
}
else{
echo "Employees not updated";
}
mysqli_close($connect);
?>
As you can see I'm trying to get the value of the ul (class=teams) in the teams.php and passing it on to the js script file using ajax and var teamId = $(this).attr("value"); and passing it onto teamdelete.php but it doesn't seem to work. Any help would really be appreciated thank you.
because $('.teamdelete') has no attr value ..
in your html you should put
<button class="teamdelete" value="<?php echo $arrayTeam['team_id']; ?>">Delete Team</button>
and in your javascript do this
var teamId = $(this).attr("value");
and in your php .. since the name of the post data = team_id you should do
$team_id = $_POST['team_id'];
Your data variable is incorrect...
The ajax data is sent as data: { NAME : VALUE }. The PHP is essentially calling $_POST['VALUE'] So the php doesn't know what that value is.
The PHP calls:
$_POST['teamId'];
But the ajax sends
team_id:
Try changing the PHP on teamdelete.php to:
$team_id = $_POST['team_id'];
There are additional issues as well...
html:
<button class="teamdelete" value="<?php echo $arrayTeam['team_id']; ?>" >Delete Team</button>
js:
$('.teams').on('click', '.teamdelete', function(){
var teamId = $(this).attr("value"); // ------------ CHANGED
console.log(teamId); // ----------- CHANGED should show the right ID in console
if(confirm("Are you sure?")){
$.ajax({
url: ".....teamdelete.php",
method: "POST",
type: "POST",
data: {
team_id: teamId
},
success: function(data)
{
alert(data);
eval(data);
}
});
}
});
PHP:
<?php
$connect = mysqli_connect('localhost', 'root', '', 'chansandbox');
$team_id = $_POST['team_id']; // ----------- CHANGED
$update = "UPDATE employee SET team_team_id = NULL WHERE team_team_id = '$team_id'";
if(mysqli_query($connect, $update)){
echo "Employees Updated";
$deleteteam = "DELETE FROM team WHERE team_id = '$team_id'";
if(mysqli_query($connect, $deleteteam)){
echo "Team deleted '$team_id'";
}
else{
echo "Team not deleted";
}
}
else{
echo "Employees not updated";
}
mysqli_close($connect);
?>
You can use the developers panel and inspector to confirm that the delete button has the correct value for the team.
I am receiving a 500 internal server error when making an ajax call.
$(document).ready(function(){
$("#txtSearch").change(function(){
var search = $("#txtSearch").val();
var str = 'search=' + search;
$.ajax({
type: "POST",
url: "searchProcess.php",
data: str,
dataType: "json",
success: function(data) {
if (data["type"] == "1") {
alert('Please Enter Value To Search');
}else if (data['type'] == "2") {
alert('No Such of This Event In Database');
}else if (data['type'] == "3") {
$('#gallery').hide().html(data['data']).fadeIn('5s');
}
}
});
});
});
searchProcess.php
if (!isset($_POST["search"])) {
print json_encode(['type'=>'1']);
}else{
$seValue = "%{$_POST['search']}%";
$querySel = "SELECT * FROM gallery WHERE galleryTitle LIKE :title OR date LIKE :dat";
$stmtquerySel = $conn->prepare($querySel);
$stmtquerySel->bindParam('title',$seValue);
$stmtquerySel->bindParam('dat',$seValue);
$stmtquerySel->execute();
if ($stmtquerySel->rowCount() == 0) {
print json_encode(['type'=>'2']);
}else{
$galleryGrid = "";
while ($rowQuerySel = $stmtquerySel->fetch()) {
$id = $rowQuerySel['galleryId'];
$image = $rowQuerySel['image'];
$title = $rowQuerySel['galleryTitle'];
$date = $rowQuerySel['date'];
$galleryGrid .= "<div class='col-lg-4 col-sm-6'>
<div class=''>
<a href='gallerydetails.php?id=$id'>
<img src='img/$image' width='100%'>
<div>Event Name:$title</div>
<div>Date :$date</div>
</br></br>
</a>
</div>
</div>
";
}
$galleryGrid .="<div class='col-md-11 text-center'>
<button type='submit' class='btn btn-primary btn-lg' onClick=location.href='gallery.php'>Back</button>
</div>";
print json_encode(['type'=>'3', 'data'=>$galleryGrid]);
}
}
when I try it on localhost it run , but when upload to server then will get 500 internal error
Use this
print json_encode(array('type'=>'3', 'data'=>$galleryGrid));
instead of
print json_encode(['type'=>'3', 'data'=>$galleryGrid]);
I want to pass user id from my table to modal via ajax but only think i get is "undefined".
When i replace var dataString = 'id=' + recipient;
with var dataString = 'id=' + 1; it working fine so for some reason i cant get value on click to variable. What i'm missing??
PHP:
<?php
$query = mysql_query("select * from users");
$i=0;
while($fetch = mysql_fetch_array($query)):
echo '<tr>';
echo'<td> '.$fetch['user_id'].'</td>';
echo'<td> '.$fetch['user_name'].'</td>';
echo'<td> '.$fetch['user_email'].'</td>';
echo'<td> '.$fetch['user_imie'].'</td>';
echo'<td> '.$fetch['user_nazwisko'].'</td>';
echo'<td> '.$fetch['user_telefon'].'</td>';
echo'<td> '.$fetch['user_konto_akty'].'</td>';
echo'<td> '.$fetch['user_uprawnienia'].'</td>';
echo'<td>' .date("d.m.Y, H:i", $fetch['user_regdate']). '</td>';
echo'<td> <a class="btn btn-primary btn-sm" href="Kasuj_tab.php?user_id='.$fetch['user_id'].'">UsuĊ</a></td>';
?>
<td>
<a class="btn btn-small btn-primary" data-toggle="modal" data-target="#exampleModal_user" data-whatever1="<?php echo $fetch['user_id']; ?>">Edit</a></td>
<?php
echo '</tr>';
endwhile;
?>
Ajax:
$('#exampleModal_user').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever1') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'id=' + recipient;
$.ajax({
type: "GET",
url: "Modal_user.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.ct').html(data);
},
error: function(err) {
console.log(err);
}
});
})
PHP:
<?php
include 'Panel_Logowanie/config.php';
db_connect();
$id = $_GET['id'];
echo"$id";
?>
*I know MYSQL is depricated. I am just using it as a learning tool for now.
UPDATED QUESTION:
I updated my question to make a lil more sense...
How can I display the output array (json data in PHP file) on my HTML page assuming I wanted to add it to the div id rvotes?
JavaScript
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(row[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
PHP
function showVotes()
{
$sql = "SELECT * FROM mms";
$result = mysql_query($sql) or die(mysql_error());
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$response = array();
while($row = mysql_fetch_assoc($showresult))
$results[] = $row;
echo json_encode($results);
}
ADDING my HTML code
<div id="wrapper">
<div id="red" data-color="red" class="answer">
<img src="images/red.jpg" width="100%" />
</div>
<div id="blue" data-color="blue" class="answer">
<img src="images/blue.jpg" width="100%" />
</div>
<div id="green" data-color="green" class="answer">
<img src="images/green.jpg" width="100%" />
</div>
<div id=rvotes>
TEST
</div>
<div id=bvotes>
TEST
</div>
How can I display the output from the array back at my HTML page?
I think this is similar to this question.
Get data from php array - AJAX - jQuery
You cannot access the php array as it is in your ajax. You need to represent it first as JSON by passing your php array to json_encode() function and echo it.
echo json_encode($results);
And it will be passed to your ajax callback as parameter.
In you success ajax callback,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
Personally, I would have my php spit out pre-rendered html like so:
$sql = "SELECT * FROM mms";
$result = mysql_query($sql) or die(mysql_error());
//I cleaned up redundant queries here...
//echo top border
echo "<table border='1'>
<tr>
<th>Color</th>
<th>Votes</th>
</tr>";
while($row = mysql_fetch_assoc($showresult))
while($row = mysql_fetch_assoc($showresult)
{
echo "<tr>";
echo "<td>" . stripslashes($row['color']) . "</td>";
echo "<td>" . stripslashes($row['votes']) . "</td>";
echo "</tr>";
}
After it spits out html, just do this:
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
success: function (showVotes) {
$("#votes").html(showVotes); //this edits the text inside the div to be whatever your php spits out
},
error: function (jqXHR) {
}
})
})
});
</script>
<div id="votes></div>