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";
?>
Related
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
}
});
}
I'm trying to load posts of users from my database to the website but the ajax part isn't loading for some reason. It was working on localhost but not working on the live server. Is there some problem in the ajax code or the code written in the index page?
Here in the index page the posts_area div part isn't loading
index.php
<?php
include("includes/header.php");
if(isset($_POST['post'])){
$post = new Post($con, $userLoggedIn);
$post->submitPost($_POST['post_text'], 'none');
}
?>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Got something to say?"></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<div class="user_details column">
<h4>Popular</h4>
<div class="trends">
<?php
$query = mysqli_query($con, "SELECT * FROM trends ORDER BY hits DESC LIMIT 9");
foreach ($query as $row) {
$word = $row['title'];
$word_dot = strlen($word) >= 14 ? "..." : "";
$trimmed_word = str_split($word, 14);
$trimmed_word = $trimmed_word[0];
echo "<div style'padding: 1px'>";
echo $trimmed_word . $word_dot;
echo "<br></div><br>";
}
?>
</div>
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "https://bestconnect.000webhostapp.com/includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') {
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>
</div>
ajax_load_posts.php
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['posts'])) {
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
<?php
header("Access-Control-Allow-Origin: *");
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['userLoggedIn']))
{
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
i am creating an e-commerce website. if i click a category on the checkbox relevant product should display.but result displayed undefined. what i tried so far i wrote it below.example if select the category as Tv on checkbox. tv product should display. i having a problem on jquery. can you check the jquery if i write correct or not checkbox click part.
Form Design
Category
<div align="left" >
<li class="list-group-item list-group-item-action active" ><h4>Categories</h4></li>
<li id="displayResults" class="list-group-item list-group-item-action">
</li>
</div>
JQuery
function getCategory(){
$.ajax({
type: 'GET',
url: 'get_category.php' ,
dataType: 'JSON',
success: function (data)
{
for (var i = 0; i < data.length; i++)
{
var catname = data[i].catname;
var catid = data[i].id;
var catstatus = data[i].status;
if(catstatus){
$('#displayResults').append('<li id='+catid+' class="list-group-item list-group-item-action"><input id="cat_id'+ catid +'" type="checkbox" value="true" > '+ ' ' + ' <b>'+ data[i].catname + '<b></li>');
}else{
$('#displayResults').append('<li id='+catid+' class="list-group-item list-group-item-action"><b>'+ data[i].catname + '<b><input id="cat_'+ catid +'" type="checkbox" ></li>');
}
}
},
error: function (xhr, status, error)
{
console.log(xhr.message)
}
});
}
Checkbox click
$(document).ready(function() {
$('#displayResults').click(function(){
var cat = $('#cat_id').attr('checked');
alert(cat);
$.ajax({
url: 'get_product.php',
type: 'POST',
data: {cat: cat},
success: function(data){
var len = data.length;
console.log(data);
$("#Products").empty();
for (var i = 0; i < data.length; i++) {
var price = data[i].price;
var image = data[i].image;
var description = data[i].description;
$("#Products").append("<div class='col-md-4'> " +
"<div class='panel panel-info' id='Products'>" +
"<div class='card-body'>" +
"<div class='panel-heading'>" + "<h4> " + description + "</h4> " +
"<p class='panel-body'>" + "<h3> " + price + "</h3>" +
"<p class='panel-body'> <img class='card-img-top' style='width:250px' height='250px' id='theImg' src='images/" + image + "' /> </p>" +
" <a href='#' class='btn btn-primary'>View More</a> </div> </div></div> </div>");
}
}
});
});
});
get_product.php
<?php
include("db.php");
$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products where cat_id = ? order by RAND() LIMIT 0,6");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
$cid = $_POST["cat"];
$stmt->bind_param("s", $cid);
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("id"=>$id, "cat_id"=>$cat_id,"brand_id"=>$brand_id,"price"=>$price,"description"=>$description,"image"=>$image,"keywords"=>$keywords);
}
echo json_encode($output);
}
$stmt->close();
?>
$("#cat_id") is wrongly used. There are many category your category id is defined as id="cat_id'+ catid +'".
I am assuming you need to check on single checkbox. if so then it will be better if you use input type radio.
But as you have use checkbox then you can do like this
$(":checkbox").each(function(){
if($(this).is(':checked')){
cat=$(this).val();
alert(cat);
}
});
if you want to select multiple checkbox make cat as array and then pass it to data field.
How to display the value in table..I am not able to display the value.In ajax i've sent all the value and after retrieving the records from database. I've to display the result in table
Output is
[{"ID":"15","patient_name":"Sangeeta","patient_email":"sangeetha#gmail.com","gender":"Female","age":"26","address":"Jayanagar","city":"Bangalore","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","referral_pat_id":"18","active":"1","created_on":"2017-06-13"}]
How to retrieve each value
AJAX Script
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
alert(rowid);
console.log(rowid);
$.ajax({
type : 'post',
url : 'url', //Here you will fetch records
data : 'id='+ rowid, //Pass $id
success : function(resp){
alert(resp);
var trHTML = '';
$.each(resp, function (i, userData) {
for (i = 0; i < resp.UserData.length; i++) {
alert(trHTML);
trHTML +=
'<tr><td>'
+ resp.userData[i].ID
+ '</td><td>'
+ resp.userData[i].patient_name
+ '</td><td>'
+ resp.userData[i].patient_email
+ '</td></tr>';
}
});
$('#tBody').append(trHTML);
}
});
});
});
Controller
public function fetch_records()
{
print_r($_POST);
$this->load->model('Physician_confirm_m');
$id = $_POST['id']; //escape string
print_r($id);
$result=$this->Physician_confirm_m->fetch_history_records($id);
echo json_encode($result);
}
Model
public function fetch_history_records($id)
{
$this->db->where('referral_pat_id',$id);
$this->db->from('referral_confirmation_details');
$q = $this->db->get();
return $q->result();
}
HTML
<button type="button" class="btn btn-info disablebtn" style="text-align: center;" data-toggle="modal" data-target="#myModal" data-id="<?php echo $post->referral_patient_id;?>"><i class="fa fa-history" aria-hidden="true"></i><strong> HISTORY</strong></button>
<div class="modal-body">
<table>
<tbody id="tBody"></tbody>
</table>
</div>
</div>
You can do in another way to achieve this.
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
console.log(rowid);
$.ajax({
type : 'post',
url : 'url', //Here you will fetch records
data : 'id='+ rowid, //Pass $id
success : function(resp){
var obj = jQuery.parseJSON(resp);
$('#tBody').append(obj.ajaxPage);
}
});
});
});
In Your Controller should be like
public function fetch_records()
{
$this->load->model('Physician_confirm_m');
$id = $_POST['id']; //escape string
$data['result']=$this->Physician_confirm_m->fetch_history_records($id);
$result['ajaxPage'] = $this->load->view('pages/result_table', $data, true);
echo json_encode($result);
}
result_table view page should be
<?php if($result){ foreach($result as $row){ ?>
<tr>
<td><?=$row['ID']?></td>
<td><?=$row['patient_name'];?></td>
<td><?=$row['patient_email'];?></td>;
</tr>
<?php
}
}?>
I have a form in my view page where there have two select boxes and three input boxes in a row .I put them in a for loop and make five rows in which every row there is two select box and 3 simple text boxes .I write a function in jquery where if i select value from one select box it will appear in 2nd select box .But after making five rows in a loop ,this function is working only in the first row not other four rows . I don't know how to do that .If any one can code it for me,then thanks to him ...
This is my view page
<tr>
<th>Category:</th>
<th>Items:</th>
<th>Selling Price:</th>
<th>quantity:</th>
<th> total:</th>
</tr>
<?php for ($i = 0; $i < 5; $i++) {
?>
<tr>
<td>
<?php echo form_dropdown('cat_id', $records2, '#', 'id="category"');?>
</td>
<td>
<?php echo form_dropdown('item_id', $records3, '#', 'id="items"'); ?>
</td>
<td><?php echo form_input($price); ?> </td>
<td><?php echo form_input($quantity); ?></td>
<td> <?php echo form_input($total); ?>
</td></tr>
<?php }?></table>
My JavaScript for two select boxes.
$(document).ready(function(){
$('#check').click(function(){
alert("hello");
return false;
});
$('#category').change(function(){
$("#items > option").remove();
var category_id = $('#category').val();
$.ajax({
type: "POST",
url: "stockInController/get_Items/"+category_id,
success: function(items) //we're calling the response json array 'cities'
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$('#items').append(opt);
});
}
});
});
});
JavaScript for sending values to the controller
<script type="text/javascript">
$('#btn').click(function() { // $("#form").serialize()
var cust_id = $('#cust_id').val();
var item_id = $('#items').val();
var sales_date = $('#sales_date').val();
var sales_bill_no = $('#sales_bill_no').val();
var price = $('#price').val();
var quantity = $('#quantity').val();
var form_data = {
cust_id: $('#cust_id').val(),
sales_date: $('#sales_date').val(),
sales_bill_no: $('#sales_bill_no').val(),
price: $('#price').val(),
quantity: $('#quantity').val(),
item_id: $('#items').val(),
};
$.ajax({
url: "<?php echo site_url('salesController/addSales'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$(".success").fadeIn(500).delay(2000).fadeOut(500);
alert("true");
}
else{
alert("false");
}
}
});
return false;
});
</script>
i have done this but this not working
<?php echo form_dropdown('cat_id', $records2, '#', "id='category_".$i."'");?>
<?php echo form_dropdown('item_id', $records3, '#', "id='items_".$i."'"); ?>
<script type="text/javascript">// <![CDATA[
$(document).ready(function()
{
for (var i= 0; i<5; i++)
{
$('#category_'+ i).change(function(){
$('#items_'+ i > option").remove();
var category_id = $('#category_'+ i).val();
$.ajax({
type: "POST",
url: "stockInController/get_Items/"+category_id,
success: function(items)
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$('#items_'+ i).append(opt);
});
}
});
});
}
});
I think the problem here is that in each row you have to inputs that have ID's "category" and "items". Each element on the page should have a unique ID. Maybe for row 1 they are "cat_1" and "item_1" or something similar.
Right now it is kind of like you have a room with 10 people, 5 named Johnny and 5 named Sarah. If you walk in and ask for Johnny, you will have a problem.
<?php for ($i = 0; $i < 5; $i++) {
?>
<tr>
<td>
<?php echo form_dropdown('cat_id', $records2, '#', "id='category".$i."'");?>
</td>
<?php echo form_dropdown('item_id', $records3, '#', "id='items".$i."'"); ?>
</td>
Similarly,run a loop in your javascript and get the values of categories and items
EDIT:
for(i=0;i < 5; i++){
$("#category"+i).change(function(){
$("#items"+i+" > option").remove();
var category_id = $("#category"+i).val();
$.ajax({
type: "POST",
url: "stockInController/get_Items/"+category_id,
success: function(items) //we're calling the response json array 'cities'
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$("#items"+i).append(opt);
});
}
});
}