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;
}
Related
function add_comment(ele) {
event.preventDefault();
var username = "<?php echo $current_user; ?>";
var user_id = "<?php echo $current_user_id; ?>";
var post_id = $(ele).data('id');
var comments = $(ele).parent(".comment-section").find(".comment").val();
alert(comments);
if (username == "") {
alert("Please Log in to Star the Post");
window.location = "http://tobbyandscooby.com/log.php";
return;
}
$.ajax({
type: 'POST',
url: 'add_comment.php',
data: {
postid: post_id,
uname: username,
uid: user_id,
comment: comments
},
success: function(response) {
//alert("Successfully Comment is Added! ");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-section">
<textarea id="<?php echo $post_id; ?>" class="comment" value="" data-id="<?php echo $post_id; ?>"></textarea>
<button id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(this);">Comment</button>
<div class="comment-show"></div>
</div>
<?php
include("connect.php");
$username = $_POST['uname'];
$post_id = $_POST['postid'];
$user_id = $_POST['uid'];
$comments = $_POST['comment'];
$sql = "INSERT INTO comments (user_id,username,post_id,comment) VALUES ($user_id,'$username',$post_id,'$comment')";
$result = $db->query($sql);
?>
I am trying to make a comment system with Ajax. I have done similar thing like favourite, down vote, upvote with Ajax. But now with this above code, I couldn't enter the data into the DB and also on clicking comment button the page refreshes even though I have used *preventDefault();
I know I have made some mistake but couldn't debug it. Also please suggest me how to add the entered comment into div .comment-show using the success in ajax.
**NOTE: I could get the alert(comments); working when preventDefault(); function is removed! I have added the XHR requests for other elements which are working fine! **
The problem is the preventDefault().
You now pass this with that function call in onClick.
To solve it, make the button a submit-button by adding <button type="submit" ..
and pass event with your function call: ...onClick="add_comment(event);"
// complete line:
<button type="submit" id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(event);">Comment</button>
But now you need to rewrite pieces of the function, because ele is now the event, not the element anymore:
Change every $(ele) to $('#id')
And obviously in the beginning of the function the variable name for the passed-in event needs to match:
function add_comment(e) { // whatever you wanna name it, e has to be the same
e.preventDefault(); // as this e
Another solution would be to keep the button just a normal button, remove the onClick there, and add onSubmit="add_comment(event);" to your <form..>
Trying to delete a record by using JQuery/Ajax function so that my page will not reload everytime I delete. I have a Movie.php that serves as a model object for Movie and this is where I put the function called delete_movie to delete based on movieId parameter. I have tried to call it inside my Jquery call but it looks like it is not calling my function delete_movie(movieId).
This is my Movie.php
<?php
class Movie {
public static function delete_movie($movieId) {
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
}
}
?>
movielist.php
<tr class="delete_mem<?php echo $movie['movieId'];?>">
<td><?php echo $movie['title']; ?> </td>
<td><?php echo $movie['releaseYear']; ?></td>
<td><?php echo $movie['imdbId']; ?></td>
<td><?php echo $movie['description']; ?></td>
<td><button type="submit" class="btn btn-danger" id="<?php echo $movie['movieId'];?>">Delete</button></td>
</tr>
JQScript.js
$(document).ready(function() {
$('.btn-danger').click(function() {
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "model/Movie.php",
data: {
delete_movie : id
},
success: function() {
alert('Success deletion!');
}
});
} else {
return false;
}
});
});
When PHP is running movie.php, it's just processing the class. The PHP within the file doesn't actually say to do anything.
If you don't need classes, you could just change your movie.php to
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
If there's more in the file or you must use classes, then you need a controller that receives the url POST, and then calls Movie::delete_movie($id).
You appear to be following the MVC pattern, the model and view you have, and adding this controller to control the actions, would be the final part.
You cannot call PHP code from JavaScript (not easily, at least). Fortunately for you, you can do what you're trying to achieve because you're sending a POST message to Movie.php. All that you have to do now is to handle that POST message in Movie.php.
<?php
class Movie {
public static function delete_movie($movieId) {
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
}
}
// add this
if (isset($_POST["delete_movie"])) {
Movie.delete_movie($_POST["delete_movie"]);
}
?>
I suggest you don't forget to add authentication. Otherwise, anyone can delete any movie from your database. Try adding a session. That's outside the scope of this question, though.
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
index.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<div id="container">
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
</div>
<button id="loadMore">Загрузить ещё...</button>
<script src="/jquery-1.11.3.min.js"></script>
<script src="/script.js"></script>
item.php
<?php
class Item
{
public $id;
public $text;
function __construct($id = null, $text = null)
{
$this->id = $id;
$this->text = $text;
}
public function show()
{
return $this->text;
}
}
loadmore.php
<?php
$offset = 0;
$limit = 10;
$statement = $pdo->prepare('SELECT * FROM credit LIMIT ?, ?');
$statement->bindValue(1, $offset, PDO::PARAM_INT);
$statement->bindValue(2, $limit, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
$items = [];
foreach ($data as $item)
{
$items[] = new Item($item['id'], $item['tel']);
}
pdo.php
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
script.js
function getMoreItems() {
var url = "/loadMore.php";
var data = {
//
};
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
//
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
}
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
I think 2 hours and I can not understand.
Help.(
I understand your confusion, I believe you're wondering why your php code in index.php doesn't work properly after you call loadMore.php using ajax.
There's one distinction you need to understand to be capable of developing for the web. The difference between server-side and client-side code.
PHP is a server-side programming language, which means that it only executes on the server. Your server returns html, or json, or text, or anything to the browser and once the response arrives at the browser, you can forget about php code.
Javascript on the other hand is a client side programming language (at least in your case) It executes on the browser.
You basically have two options:
To send back some json and loop over it using jQuery, which is the preferable choice, but I fear it requires more work.
Send back html and append it to your page, first create a file called async.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
in your js add to your success callback
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
$('#container').append(res);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
don't forget var url = "async.php";
First you need to attach the buttons onclick="" attribute with the ajax-method.
<button ... onclick="getMoreItems">...</button>
Second, your loadmore.php need to require_once the files it depends on:
require_once('pdo.php');
require_once('item.php');
Third, separate your logic for querying the database to a function in the pdo.php file you can call with the limits as parameters, i.e.
function getData($offset = 0, $limit = 10){
//logic
}
You should also always try to use require_once or include_once to be sure files aren't loaded several times.
Now you can call the function getData(...) from index.php before the container div to load up the initial data, remove the include to loadmore.php from index.php, and in loadmore.php write the logic to use the parameters sent from the webpage to get the next chunk of data.
The data:... in your ajax needs to pass along the "page" it wants to get, perhaps simply a counter as to how many times you have loaded more. In the loadmore.php script you then just multiply the page by the limit to get the offset.
Return the data as JSON to the ajax, parse the JSON so you can build a new div for each item, then add each div to the container-div using javascript.
Im not going in detail on all topics here, but you at least will know what tutorials to search for on google :)
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;
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
}