I have a foreach loop on index page that displays a list of few ids and in front of each id there is a link (named as detail) which is related to that id only.
The code on index page is
<?php if($request_detail): ?>
<?php foreach($request_detail as $request): ?>
<?php echo $request->requestid; ?>
<a id="link" href="<?php echo base_url(); ?>recruiter/getrequestdetail/<?php echo $request->requestid; ?>"> Details </a>
<?php endforeach; ?>
<?php endif; ?>
<div id="container">
</div>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
$.ajax({
type: "get",
url: "<?php echo base_url(); ?>recruiter/getrequestdetail/<?php echo $request->requestid; ?>",
success: function(data) {
$('#container').html(data);
}
});
});
</script>
The view i get from above code is
1 details
2 details
3 details
When a user clicks on detail link i wish to fetch the data of that id only from another page and display it under a particular div.
Controller
public function getrequestdetail($id)
{
$data['request_data'] = $this->recruiter_model->get_request_data($id);
$this->load->view('recruiter/request_data_view',$data);
}
Model
public function get_request_data($requestid)
{
/* query is getting executerd here */
return $query->result();
}
The issue is that if i click on first details the id that is being passed in 3 and when i click on other details it gets redirected to another page and has the id 3
But what i want is that
when a user clicks on detail in front of 1 the data of id 1 should get displayed in container div within the same page,
when a user clicks on detail in front of 2 the data of id 2 should get displayed in container div within the same page,
when a user clicks on detail in front of 3 the data of id 3 should get displayed in container div within the same page,
Can anyone please tell how it can be done
Can anybody else have the Driving license number or same passport numbers as yours. Because they are identities and identities are always unique. Then how can you make all your links having same ID as they are coming from a foreach loop.
You must have to use class for the link. And also you were passing the last ID (last foreach iteration) to your ajax call.
<?php if($request_detail): ?>
<?php foreach($request_detail as $request): ?>
<?php echo $request->requestid; ?>
<a class="link" href="<?php echo base_url(); ?>recruiter/getrequestdetail/<?php echo $request->requestid; ?>"> Details </a>
<?php endforeach; ?>
<?php endif; ?>
$(".link").click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
type: "get",
url: url,
success: function(data) {
$('#container').html(data);
}
});
});
correct your controller
$this->load->view('recruiter/request_data_view',$data);
$data = $this->load->view('recruiter/request_data_view',$data, true);
return $data;
Related
I´m trying to call a function into a href, my function is on functions.php
and my href is on views/something.php
so, this is my function:
function discount($connection, $us){
$discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
$discount->execute();
return $discount;
}
and my link button is on an <li> (not in a form):
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
(Do not pay attention to the foreach)
You'll need to change this to use an ajax call or form post to call the PHP function.
Here's a really basic example which should point you in the right direction
discount.php
<?php
// Load $connection from somewhere
// Get user, it's better to get this from a cookie or session rather than GET
$user = $_GET['user']
$discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
$discount->bindParam(':user', $user);
$result = $discount->execute();
// Throw error if something went wrong with the update, this will cause $.ajax to use the error function
if (!$result) {
http_response_code(500);
}
html, assuming $notu[0] contains the user id
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
js, requires jquery
function callDiscount(user_id)
{
// Perform ajax call to discount.php
$.ajax({
url: '/discount.php?user=' + user_id,
error: function() {
alert('An error occurred');
},
success: function(data) {
// Redirect user to notificaciones.php
document.location = '/notificaciones.php';
}
});
// Prevent link click doing anything
return false;
}
I'm trying to get records from the database using a client side (Javascript) clickable list. The problem is that I want the clickable links to be sourced from the data in the database in the first place (MySQL).
I'm having problems passing the data to create the clickable list. I've tried various ideas and hit stumbling blocks to do with client side and server side programming (and briefly looked into JQuery but it appears difficult to do). I've been attempting this with HTML, PHP, Javascript, JQuery (briefly) and MySQL.
So I need to SELECT post_id, post_title FROM posts and make post_title clickable in the list but using the associated post_id to find the relevant data in the DB and post this via innerHTML into another element. Any ideas?
index.php <- List
<html>
<head>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
$sql = 'SELECT post_id AS "id", post_title AS "title" FROM posts';
$posts = $mysqli->query($sql);
?>
<ul id="post_list">
<?php
foreach ($posts as $post) {
?>
<li><a href="#" data-id="<?php echo $post['id'] ?>"><?php
echo $post['title']
?></a></li>
<?php
}
?>
</ul>
<div id="post_content"></div>
</body>
</html>
script.js <- Interactivity (requires jquery)
$(document).ready(function() {
$('#post_list').on('click', 'li a', function() {
$('#post_content').load('get_post.php?id=' + $(this).data('id'));
});
});
get_post.php <- Selected post
<?php
if (!empty($_GET['id'])) {
$sql = 'SELECT * FROM posts WHERE post_id = '.$_GET['id'].'';
$res = $mysqli->query($sql);
if (($post = $res->fetch_assoc())) {
?>
<h1><?php echo $post['post_title'] ?></h1>
<p><?php echo $post['post_body'] ?></p>
<div class="pull-right"><?php echo $post['post_author'] ?></div>
<?php
} else {
header("HTTP/1.0 404 Not Found");
die();
}
}
?>
Maybe I've not understand correctly, but this can solve your problem :
You need at least 2 files (3 if you separate the Js Code)
Index.php :
$arrayItems = array()//The array containing your datas from the database
echo '<div id="listItems">';
for($i = 0; $i < count($arrayItems); $i++){
echo '<div class="item" idFromDB="'.$arrayItems[$i]['post_id'].'">'.$arrayItems[$i]['post_title'].'</div>';
}
echo '</div>';
echo '<div id="containerDetailsItem"></div>';
javascript.js : (which is more Jquery)
$(document).ready(function() {
$('.item').live('click', function(){
$('#containerDetailsItem').load('myAjax.php?idItem='+$(this).attr('idFromDB'));
});
});
and the ajax File (myAjax.php) :
if(isset($_GET['idItem']) && $_GET['idItem'] != ''){
$idItem = (int)$_GET['idItem'];
//Get the infos from the database with the ID given
echo 'datas from BDD';
}
And I think that will do what you need. This is simple PHP with Jquery and Ajax.
PS : There is just minified code. You'll need to include Jquery (from google maybe) and to make the link between index.php and Javascript.js
Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.
Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}
It's part of my view. Me need transmit input name in on which i click.
Below is a script that will get the name input after click
<div class="form_hint"><?=form_error('this get value from javascript after click')?></div>
<?php echo form_open("onenews/" . $onenews['id'] . "#signup", $form_reg['main_form']); ?>
<?php echo form_input($form_reg['login'], $this->form_validation->set_value('login')) ?>
<?php echo form_input($form_reg['email'], $this->form_validation->set_value('email')) ?>
<?php echo form_input($form_reg['password']) ?>
<?php echo form_input($form_reg['conf_password']) ?>
<?= MY_Controller:: create_captcha(); ?>
<?php echo form_input($form_reg['captcha']) ?>
<?php echo form_input($form_reg['submit']) ?>
<?php echo form_close(); ?>
</div>
</div>
jq
<script type="text/javascript">
$(function(){
var curInput = '';
$('#form_reg').find('input').on('click', function(){
curInput = $(this).attr("name");
});
})
</script>
Or i must use ajax?
Thanks!
Your question is not clear at all, but I assume you want to dynamically change the content of the form_hint div. You can't do that with PHP. Once PHP renders the page, it shuts down and does nothing more. So the only way to make PHP show that message is after the form submit, but then you lose your click data. There is a way to save the clicked element in a session for example, but that would be a really bad solution.
So the best solution would probably be to list all the hints in a JavaScript variable, and call the appropriate one upon the click event, and fill the form_hint div with it.
$('.form_hint').text(yourAppropriateMessageHere);
An example with a hidden div for the login input field with exactly how you described would be:
<div class="form_text_login"><?=form_error('login')?></div>
JS
var loginMessage = $('.form_text_login').text();
// list others here
// then make a tree with switch/case or if/else
if (curInput == 'login') {
$('.form_hint').text(loginMessage);
}
else if (curInput == 'email') {
// do the same with the email message, etc.
}