i am new to ajax i am trying to build a website for movies so i need ajax to change the servers for the video but i can not do it how much i tried the div that i want to show is not being shown at all here is my codes
HTML
<?php
$get = $data->show(" SELECT * FROM servers ");
foreach ($get as $row) {
$id=$row['server_id'];
$name=$row['server_name'];
$link=$row['link'];
$movie=$row['film_name'];
?>
<button type="button" id="btn" class="btn btn-warning"><?php echo "$name"; ?></button>
<input type="hidden" id="serverid" value="<?php echo $id ?>">
<?php } ?>
<div id="show">
</div>
AJAX
<script type="text/javascript">
$(document).ready(function (){
$('#btn').click(function (){
var serverid = $('#serverid').val()
$.ajax({
url:"../../control/operation/index/view_movie.php",
method:"POST",
data:{serverid:serverid},
success:function(data)
{
$("#show").html(data);
}
});
});
});
</script>
view_movie.php
if (isset($_POST['serverid'])) {
$id=$_POST['serverid'];
$getuser = $data->getdata(" SELECT * FROM servers WHERE server_id='$id' ");
$link=$getuser['link'];
} ?>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="<?php echo $link ?>" allowfullscreen></iframe>
</div>
</div>
nothing is shown on the div that called show
Related
i search any video and it display results from the youtube. now i want to display results through ajax. whenever i search for any video, it should display videos without reloading the page. i have written a little bit code of ajax. i dont know how to pass videos result in the ajax. below is the code.
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<div class="search">
<div class="navbar-nav mr-auto">
<form action="fetch.php" method="POST" class="form-inline">
<input class="form-control mr-sm-2" type="text" name="vid" id="vid" placeholder="Search">
<button class="btn btn-success" type="submit" name="search" id="search">Search</button>
</form>
</div>
</div>
<div class="navbar-nav ml-auto">
<?php
if(isset($_SESSION['email']))
{
echo "<a href='logout.php'>Logout</a>";
}
?>
</div>
</nav>
<br>
<?php
if(isset($_POST['search']))
{
$query = $_POST['vid'];
}
$API_key = '';
$maxResults = 10;
$api_url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q='.urlencode($query).'&maxResults='.$maxResults.'&key='.$API_key.'';
$videoList=json_decode(file_get_contents($api_url, true));
echo "<div class='left-display'>";
echo '<iframe id="play-video" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
echo "</div>";
echo "<div class='right-display'>";
echo "<h4>Up Next</h4>";
foreach($videoList->items as $item)
{
if(isset($item->id->videoId))
{
echo '<div id="youtube-video">
<div>
<img class="image" width="240" height="150" src="https://i.ytimg.com/vi/'.$item->id->videoId.'/default.jpg" data="https://www.youtube.com/embed/'.$item->id->videoId.' ">
<p>'. $item->snippet->title .'</p>
</div>
</div>';
}
}
echo "</div>";
?>
<script type="text/javascript">
$('.image').click(function()
{
const value = $(this).attr("data");
$('#play-video').attr("src", value);
});
$(document).ready(function(){
$('#search').click(function(e){
var searchterm = $('#vid').val();
e.preventDefault();
$.ajax({
method: "POST",
url: fetch.php,
data: {search, searchterm},
datatype: "html",
success: function(data){
$('#youtube-video').html(data);
}
});
})
});
</script>
I can see a few possible issues with your code:
You've written $('#youtube-video').html(data); to append the results of the AJAX call into your page, but there is no element called "youtube-video" ready-made in your page, so there's nowhere for the data to go. You need a ready-made element to put the results into. (Your PHP code defines an element called "youtube-video" but it only outputs it during the AJAX request, so it's there in data - but you haven't processed that yet so it doesn't exist in the page at the time you try to use it.)
Your format for sending the data is wrong - to define a property called "search" it should be {search: searchterm}
You're not fully separating the PHP code which runs when the page loads from the code which runs when AJAX is called. The PHP code which tries to search will run every time you execute the page, so you could get errors when it first loads (because $query won't be defined) and also the response to your AJAX would have other bits of the page mixed up in it as well (including the static HTML sections).
Short of putting the AJAX-related PHP code into a separate file, the next best thing is to put it all into an if statement at the top of the script, and finish it with an exit() command so it doesn't output anything else it shouldn't.
$query = $_POST['vid']; looks for a parameter called "vid" which isn't being submitted b the AJAX request. You only send "search" in the AJAX request, which contains the query to search for, so you need to look for that in $_POST instead - i.e. $query = $_POST['search'];.
Your AJAX call sets the URL of the request to "fetch.php". It's not clear whether this is the name of the file containing the code you've shown us, or another file. But the code to search and display the videos is in the code you've shown us, so the URL needs to be the name of that file.
Here's a version of the code which resolves those problems (apart from number 5 because I can't tell if that's a mistake or not):
<?php
if(isset($_POST['search']))
{
$query = $_POST['search'];
$API_key = '';
$maxResults = 10;
$api_url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q='.urlencode($query).'&maxResults='.$maxResults.'&key='.$API_key.'';
$videoList = json_decode(file_get_contents($api_url, true));
echo "<div class='left-display'>";
echo '<iframe id="play-video" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
echo "</div>";
echo "<div class='right-display'>";
echo "<h4>Up Next</h4>";
foreach($videoList->items as $item)
{
if(isset($item->id->videoId))
{
echo '<div class="youtube-video">
<div>
<img class="image" width="240" height="150" src="https://i.ytimg.com/vi/'.$item->id->videoId.'/default.jpg" data="https://www.youtube.com/embed/'.$item->id->videoId.' ">
<p>'. $item->snippet->title .'</p>
</div>
</div>';
}
}
echo "</div>";
exit();
}
?>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<div class="search">
<div class="navbar-nav mr-auto">
<form action="" method="POST" class="form-inline">
<input class="form-control mr-sm-2" type="text" name="search" id="vid" placeholder="Search">
<button class="btn btn-success" type="submit" name="submit" id="search">Search</button>
</form>
</div>
</div>
<div class="navbar-nav ml-auto">
<?php
if(isset($_SESSION['email']))
{
echo "<a href='logout.php'>Logout</a>";
}
?>
</div>
</nav>
<br>
<div id="videos"></div>
<script type="text/javascript">
$('.image').click(function()
{
const value = $(this).attr("data");
$('#play-video').attr("src", value);
});
$(document).ready(function(){
$('#search').click(function(e){
var searchterm = $('#vid').val();
e.preventDefault();
$.ajax({
method: "POST",
url: fetch.php,
data: {search: searchterm},
datatype: "html",
success: function(data){
$('#videos').html(data);
}
});
});
});
</script>
I have created a product page for my website. When I Clicked the First Add to Cart the jQuery code works perfectly. but when the second Add to Cart is clicked, then the jQuery code is not working.
This is the image of the product page:
enter image description here
<?php
$query = 'SELECT * FROM `products` order by product_id DESC';
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_array($result)) {?>
<div class="col-sm-12 col-md-6 col-lg-4 p-b-50">
<!-- Block2 -->
<div class="block2" id="image">
<div class="block2-img wrap-pic-w of-hidden pos-relative block2-label">
<img src="<?php echo $base_url .'pages/Ajax/'.$row['product_img1']; ?>" alt="IMG-PRODUCT">
<div class="block2-overlay trans-0-4">
<a href="#" class="block2-btn-addwishlist hov-pointer trans-0-4">
<i class="icon-wishlist icon_heart_alt" aria-hidden="true"></i>
<i class="icon-wishlist icon_heart dis-none" aria-hidden="true"></i>
</a>
<div class="block2-btn-addcart w-size1 trans-0-4">
<!-- Button -->
<button class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4" id="add_cart">
Add to Cart
</button>
</div>
</div>
</div>
<input type="text" value="<?=$row['product_id'];?>" name="hiddenID" id="hiddenID">
<input type="text" value="<?=$row['product_title'];?>" name="name" id="name"><input type="text" value="<?=$row['product_price'];?>" name="price" id="price">
<div class="block2-txt p-t-20">
<a href="product-detail.php?id=<?=$row['product_id'];?>" class="block2-name dis-block s-text3 p-b-5">
<?php echo $row['product_title']; ?>
</a>
<span class="block2-price m-text6 p-r-5">
$<?php echo $row['product_price']; ?>
</span>
</div>
</div>
</div>
<?php } ?>
JQuery Code
<script>
$(document).ready(function(){
$('#add_cart').on('click', function(e){
e.preventDefault();
var name = $('#name').val();
var hiddenID = $('#hiddenID').val();
var price = $('#price').val();
alert(name);
alert(hiddenID);
alert(price);
});
});
</script>
Your button all have the same id.
Your need to use class or make the button id unique dynamically.
Like :
<button class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4" id="add_cart_<?php echo $row['product_id']?>">
Add to Cart
</button>
Then use jsquery
<script>
$(document).ready(function(){
$('[id^="add_cart_"]').on('click',function(e) {
var index = $(this).attr('id').split("_")[1]; //product ID of the clicked button
e.preventDefault();
var name = $('#name').val();
var hiddenID = $('#hiddenID').val();
var price = $('#price').val();
alert(name);
alert(hiddenID);
alert(price);
});
});
</script>
Edit :
You can also add the product details on the button using the data attribute.
<button class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4" id="add_cart_<?php echo $row['product_id']?>" data-product="<?php echo $row['product_title']?>" data-price="<?php echo $row['product_price']?>">
Add to Cart
</button>
Then :
<script>
$(document).ready(function(){
$('[id^="add_cart_"]').on('click',function(e) {
e.preventDefault();
var hiddenID = $(this).attr('id').split("_")[1]; //product ID of the clicked button
var name = $(this).data('product');
var price = $(this).data('price');
alert(name);
alert(hiddenID);
alert(price);
});
});
</script>
The issue is because you're repeating the same id attributes in your loop. They need to be unique within the DOM. To fix this change them to classes. Then you will need to use DOM traversal to find inputs related to the button which was clicked. To do that you can use a combination of closest() and find(), like this:
$(document).ready(function() {
$('.add_cart').on('click', function(e) {
e.preventDefault();
var $container = $(this).closest('.col-sm-12');
var name = $container.find('.name').val();
var hiddenID = $container.find('.hiddenID').val();
var price = $container.find('.price').val();
console.log(name);
console.log(hiddenID);
console.log(price);
});
});
<?php
$query = 'SELECT * FROM `products` order by product_id DESC';
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_array($result)) {?>
<div class="col-sm-12 col-md-6 col-lg-4 p-b-50">
<div class="block2 image">
<div class="block2-img wrap-pic-w of-hidden pos-relative block2-label">
<img src="<?php echo $base_url .'pages/Ajax/'.$row['product_img1']; ?>" alt="IMG-PRODUCT">
<div class="block2-overlay trans-0-4">
<a href="#" class="block2-btn-addwishlist hov-pointer trans-0-4">
<i class="icon-wishlist icon_heart_alt" aria-hidden="true"></i>
<i class="icon-wishlist icon_heart dis-none" aria-hidden="true"></i>
</a>
<div class="block2-btn-addcart w-size1 trans-0-4">
<button class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4 add_cart">Add to Cart</button>
</div>
</div>
</div>
<input type="text" value="<?=$row['product_id'];?>" name="hiddenID" class="hiddenID">
<input type="text" value="<?=$row['product_title'];?>" name="name" class="name"><input type="text" value="<?=$row['product_price'];?>" name="price" id="price">
<div class="block2-txt p-t-20">
<a href="product-detail.php?id=<?=$row['product_id'];?>" class="block2-name dis-block s-text3 p-b-5">
<?php echo $row['product_title']; ?>
</a>
<span class="block2-price m-text6 p-r-5">
$<?php echo $row['product_price']; ?>
</span>
</div>
</div>
</div>
<?php } ?>
i'm working on a a website and i've made a php file that will show my search results, (i'm working on request appointment) so when i click that it works but the only problem is my webpage refresh and it shows a blank page until i click on home button to redirect
// my research loop...
if(isset($_GET['submit-search'])) {
$search = mysqli_real_escape_string($conn, $_GET['search']);
$sql = "SELECT * FROM doctor WHERE DoctorFullName LIKE '%$search%' OR DoctorLocation LIKE '%$search%' OR DoctorSpeciality LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
?>
<div class="container overflow">
<div class="container overflow">
<span class="mentor">
<h2 class="display Text-mentor">
<span class="mentor-admin">If the result shown bellow not seems like what you need then ;</span>
<span class="mentor-admin-quote">select the speciality of the doctor you need and your insurance, and <span class="turquoise">search</span> again</span>
</h2>
</span>
</div>
<div class="container overflow">
<p class="p-about-results"><?php echo "There is ".$queryResult." result matching your search"?></p>
<p class="p-about-results">we hope that these results are the ones you are looking for :</p>
</div>
<?php
while ($row = mysqli_fetch_assoc($result)) :
?>
// my calendar for so i can submit appointment
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<form>
<input type="text" name="ap-time" id="t1" class="modal-input-text" placeholder="Choose a date">
<div id="sub" style="top: 40px;left: 5px;z-index:1;text-align: center;"></div>
<input type=submit name="ap_validation" value="request appointment" class="input-requestdate">
</form>
</div>
</div>
//Ajax code that i've been working on
<script type="text/javascript">
$(document).ready(function(){
//alert("jquery is working");
$(".input-requestdate").click(function(){
var name = $(".modal-input-text").val();
$.ajax({
url: "Appointment.php",
type: "POST",
async: false,
data: {
"done": 1,
"message": name,
},
success: function(data){
alert("requested");
window.location = window.location.href
}
})
});
});
</script>`
thanks for helping :)
I am building a CI application. here i show the Login and Logout of Employees. now i have a drop down where i fetch all the users from database and below that i have a table that shows the all users and their relevant login logout. Now i want to do something like when i select a user from drop down i can seen only his information and not all others.
The Controller:
public function index()
{
$this->data['attendances'] = $this->attendance_m->join_data();
$this->data['attendance_dropdown'] = $this->attendance_m->get_emp_list();
$this->data['subview'] = 'admin/attendance/index';
$this->load->view('admin/_layout_main', $this->data);
}
The Model:
function get_emp_list() {
$q = $this->db->select('name')
->from('users')
->get();
return $q->result_array();
}
Below is my code to fetch the users:
<script type="text/javascript" src="<?php echo site_url('js/bootstrap.min.js');?>"></script>
<h2>Upload CSV To Import Users</h2>
<!-- in the action you need to place /controller/function in our case #Attendance, #upload -->
<form method="post" action="<?php echo site_url('admin/attendance/upload');?>" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<br>
<input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
</form>
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<h1><label for="sel1">Select list:</label></h1>
<select name="attendance-list" id="attendance-list" class="form-control" >
<?php foreach($attendance_dropdown as $value) { ?>
<option value="<?php echo $value['name'];?>"><?php echo $value['name']; ?> </option>
<?php } ?>
</select>
</div>
<h1 class="page-header">Attendance Details</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
All Calls Records
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Emp_ID</th>
<th>Name</th>
<th>Date</th>
<th>Entry</th>
</tr>
</thead>
<tbody>
<?php if(count($attendances)): foreach($attendances as $attendance): ?>
<tr class="odd gradeX">
<td><?php echo trim($attendance->emp_id,'">'); ?></td>
<td><?php echo trim($attendance->name.$attendance->last_name,'">'); ?></td>
<td><?php echo trim($attendance->date_data,'">'); ?></td>
<td><?php trim($attendance->entry,'">'); ?> <?php if($attendance->entry >100)
{
echo "Logged In";
}
else
{
echo"Logged Out";
}?>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3">We could not find any Data.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<!-- /.row -->
<!-- jQuery -->
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- DataTables JavaScript -->
<script src="../bower_components/datatables/media/js/jquery.dataTables.min.js"></script>
<script src="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<!-- Page-Level Demo Scripts - Tables - Use for reference -->
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
});
</script>
You have to bind on change event for given dropdown if value is not empty the call ajax and get info of that particular user
in you js :
<script>
site_url="http://localhost/ci_root/index.php/";
$('#attendance-list').on('change', function () {
var select_emp_name=$(this).val();
if(select_emp_name!=""){
var params={};
params["name"]= select_emp_name;
$.ajax({type: 'POST', url: site_url + 'employee/getUserInfo', data: params,success: function (response) {
//write on response logic/set employee details
var user_data=JSON.parse(response);
}, async: true});
}
})
</script>
in Controller function
public function getUserInfo()
{
$name=$this->input->post("name",true);
$data = $this->attendance_m->get_emp_data($name);
echo json_encode( $data);
exit;
}
in Model Function:
function get_emp_data($name) {
$q = $this->db->select('*')//required fields
->from('users')
->where('name',$name) // considering name is unique field
->get();
return $q->result_array();
}
Suggestion : Its better practice to send user id or unique field for dropdown values instead of name like user_id=>1,name=>sanjay
and we can set user_id as value at dropdown and name as label for option
it will look like
<?php foreach($attendance_dropdown as $value) { ?>
<option value="<?php echo $value['user_id'];?>"><?php echo $value['name']; ?> </option>
<?php } ?>
according your where clause also change
let me know if you need more support
here is your display code for Scipt only
<script>
site_url = "http://127.0.01/project/admin/";
$('#attendance-list').on('change', function() {
var select_emp_id = $(this).val();
if (select_emp_id != "") {
var params = {};
params["id"] = select_emp_id;
$.ajax({type: 'POST', url: site_url + 'attendance/getUserInfo', data: params, success: function(response) {
//write on response logic/set employee details
var user_data = JSON.parse(response);
var row = '<tr class="odd gradeX"><td>' + user_data.emp_id + '</td><td>' + user_data.name + ' ' + user_data.last_name'</td><td>' + user_data.date_data + '</td><td>' + user_data.entry + ' ' + (user_data.entry > 100?"Logged In":"Logged Out") + '</td> </tr>';
$("#dataTables-example tbody").find('tr').remove();
$("#dataTables-example tbody").append(row);
}, async: true});
}
});
</script>
Here is how to grab data in codeigniter with a post:
Controller
function catchPost(){
$this->form_validation->set_rules("nametage", "something", "required");
if($this->form_validation->run() == TRUE){//Formvalidation worked
$this->load->model("model_name");
$data['userInfo'] = $this->model_name->function();
$this->load->view("view", $data);
}else{
redirect("prevUrl", "refresh");
}
}
Model:
function getData(){//No parameters because we work directly with the post. You should filter the post before you actually use it.
$query = $this->db-select("*")
->from("users")
->where("username", $this->input->post("username"))
->get()
->result_array();
return $query
}
This is a general way of grabbing specific data.
All the other attribute changes seem to work fine inside the modal. The rating button inside the modal doesn't load its value on loading. But the inspect element seems to display the proper rating value.
I am new to php and jquery. Kindly excuse me from silly programming methodologies implemented in the above mentioned code.
Any help would be deeply appreciated.
HTML :
<div class="item" style="width: 400px; height: 230px">
<!-- Link trigger modal -->
<a data-img-url="upload/<?php echo $row['image_name'] ?>" data-toggle=
"modal" href="#myModal" id="<?php echo $row['image_id'] ?>" onclick=
"modalload(this.id, '<?php echo $row['image_title'] ?>' , '<?php echo $row['image_description'] ?>', <?php echo $TAVG ?> );"><img class="img-responsive carousal_scale"
src="upload/%3C?php%20echo%20$row['image_name']%20?%3E"></a>
<div class="carousel-caption">
<p><?php echo $row['image_title'] ?></p>
</div>
</div><!-- Modal -->
<div class="modal fade modal-dialog modal-content" id="myModal" tabindex="-1">
<div class="modal-header">
<button class="close" data-dismiss="modal" type=
"button"><span>×</span><span class="sr-only">Close</span></button>
<h2 class="modal-title" id="myModalLabel"></h2>
</div>
<div class="modal-body well">
<img class="img-responsive carousal_scale" src=""> <input class="rating"
data-size="xs" id="" max="5" min="0" onchange="test(this.id, this.value);"
step="0.1" style="alignment-adjust: auto;" type="number" value="">
</div>
<div>
<p style="text-align: center; font-size: 15px;"></p>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" type=
"button">Close</button>
</div>
</div>
JS :
$(document).ready(function() {
$(".rating-kv").rating();
});
function modalload(id, title, description, avg) {
alert(avg);
// alert(description);
$('#myModal img').attr('src', $('#' + id).attr('data-img-url'));
$('#myModal input').attr('value', avg);
$('#myModal input').attr('id', id);
$('#myModal h2').text(title);
$('#myModal p').text(description);
}
function test(id, val) {
var pic_id = id;
var pic_val = val;
$.ajax({
type: 'POST',
url: 'rating.php',
data: {
'pic_id': pic_id,
'pic_val': pic_val
},
}).done(function(data) {
// alert(data);
});
}
"The rating button inside the modal doesn't load its value on loading." You currently have your modalload()function only activate on click of an a tag so your rating isn't going to get it's value/id populated on load, but rather on click.
Try this instead inside your modalload() function,
$('.rating').attr('value', avg);
$('.rating').attr('id', id);
Also, note that there is no jQuery rating() function, and that you have no element with the class rating-kv in your HTML, therefore the below code will do nothing.
$(".rating-kv").rating();
In other words, you have a lot of bad coding practices and incomplete code. You should consider revising what you have and re posting it.