I currently have two php files (index.php and update.php) In index.php, there is some javascript code and a button that sends a variable, called $sid, to update.php, where it is processed based on $sid. Here is the code for both index.php and update.php. I am not pasting it directly into StackOverflow, simply because of how you have to add code to your text on StackOverflow, and how JavaScript works with it's spacing hierarchy.
http://pastebin.com/fq87vvgz
Currently, when you press the button, an alert box does not pop up. If you put the PHP code in a PHP code checker, no errors appear.
Here is my code:
This is what is in index.php
<?php
$sid = 11;
?>
<script type="text/javascript">
$(document).ready(function(){
$('#vote').click(function(){
$.ajax({
url : 'update.php', // Notice how this sends to update.php
type : 'POST',
data : {
action : 'vote_server',
sid : $('#sid').data('sid')
},
dataType : 'JSON',
success : function(result) {
if (result.xhr == 'success') {
alert('You bumped your server!');
} else if (result.xhr == 'voted_already')
alert('You can only bump every 24 hours!')
}
});
});
})
</script>
<input type="button" class="btn btn-primary" id="vote" value="Vote up your server">
This is what is contained in update.php
<?php
define('action',$_POST['action']);
$result = array(
'xhr' => 'error'
);
if (action == 'vote_server')
{
$sid = (int)$_POST['sid'];
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$dbTime = #mysql_result(mysql_query("SELECT `id`, `last_updated` FROM `servers` WHERE `id` = '$sid'"), 0);
$timeDiff = $time - $dbTime;
if($timeDiff >= 86400){
mysql_query("UPDATE `servers` SET `last_updated` = '$time' WHERE `id` = '$sid'");
$result['xhr'] = 'success';
} else { $result['xhr'] = 'voted_already'; }
}
echo json_encode($result);
?>
Use query and ajax
in your index page...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$( ".button" ).click(function() {
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
$.ajax({
type: "POST",
url: 'update.php',
data: {postedVar:var1, postedVar2:var2},
success: function(data)
{
alert(data);
}
});
});
});
</script>
<html>
<button class="button" data-var1="<?php echo "this is var1"; ?>" data-var2="<?php echo "this is var2"; ?>">Button</button>
</html>
On you update page...
access your vars like this
<?php
var1 = $_POST['postedVar1'];
var2 = $_POST['postedVar2'];
echo var1;
?>
...NOT TESTED
Related
I am trying to send an $_GET['CategoryID'] trought ajax to call in the destination file getdata.php and I can't make it work, I don't find the perfect info here. I know that I am really noob, but I am trying really hard to learn.
I been trying a lot of different code and it still not working.
<button type="button" name="btn_more" data-vid="<?php echo $stockID; ?>" id="btn_more" class="btn btn-success form-control">Ver Mais</button>
<input class="form-control" id="PresentCategoryID" name="PresentCategoryID" data-cat="<?php echo $_GET['categoryID']; ?>" value="<?php echo $_GET['categoryID'];
<script>
$(document).ready(function(){
$(document).on('click', '#btn_more', function(){
var last_video_id = $(this).data("vid");
var PresentCategoryID= ('PresentCategoryID');
$('#btn_more').html("<div class=loader></div>");
$.ajax({
url:"getdata.php",
method:"POST",
data:{
last_video_id:last_video_id,
PresentCategoryID:PresentCategoryID},
dataType:"text",
success:function(data)
{
if(data != '')
{
$('#remove_row').remove();
$('#result').append(data);
}
else
{
$('#btn_more').html("No Data");
}
}
});
});
});
</script>
My objective it's to call the categoryID in the getdata.php, like this,
<?php
$output = '';
$stockID = '';
$PresentCategoryID = '';
sleep(1);
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID > ".$_POST['last_video_id']." LIMIT 4";
?>
var PresentCategoryID= ('PresentCategoryID')
should be
var PresentCategoryID= $('#PresentCategoryID').val();
You need to use $ to select the element, add the # prefix to use it as an ID, and .val() to get the value of the input.
hey check this answer which will help your problem
$(document).ready(function() {
$(document).on('click', '#btn_more', function() {
var last_video_id = $(this).data("vid");
var PresentCategoryID = ('#PresentCategoryID').val();
$('#btn_more').html("<div class=loader></div>");
var data = {
last_video_id,
PresentCategoryID
};
$.get('getdata.php', JSON.stringify(data)).done(response => {
console.log(response);
if (response != '') {
$('#remove_row').remove();
$('#result').append(response);
} else {
$('#btn_more').html("No Data");
}
}).fail(() => {
console.log("Something went wrong");
});
});
});
PHP SCRIPT
<? php
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//if you using get request
//recommended way to get the data use the mysqlconn->real_escape_string($_GET['last_video_id']);
$last_video_id = $_GET['last_video_id'];
$PresentCategoryID = $_GET['PresentCategoryID'];
sleep(1);
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID='$$last_video_id'";
" LIMIT 4";
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//if you using post request then in jquery remove $.get to just $.post
$data = json_decode(file_get_contents('php://input'),true);
$last_video_id = $data['last_video_id'];
$PresentCategoryID = $data['PresentCategoryID'];
}
you want to send via 'GET' but you use the method 'POST'.
Best regards
MrKampf
I'm new to jquery & Ajax.
I have a php file with jquery inside it, which loads content from another php file on selection of a date
$("#datepicker3").change(function(){
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
}
});
});
The issue I'm facing is contents in ptreport1.php has links (pagination) contained to browsing scope of that php file. When the user clicks on those links he is directed out of the original page ajax content is loaded from.
Is there anyway to prevent that and load content in original page.
Update # 2.
After ediding the codes with preventDefault, following is my jquery
<script>
$(document).ready(function() {
$("#searchr").hide();
$(function() {
$('#datepicker3' ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd M yy'
});
});
$("#datepicker3").change(function(){
var myValue = $(this).val();
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
var page = $("#pagediv").html();
var timestamp =$("#timediv").html();
var dataString = 'page='+ page + '×tamp='+ timestamp;
$.ajax({
type: "GET",
url: "ptreport1.php",
data: dataString,
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
}
});
});
}
});
});
});
</script>
and ptreport1.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
include "core.php";
connectdb();
$page = $_GET['page'];
$timestamp = $_GET['timestamp'];
$ptdate = $_POST['ptdate'];
if(isset($timestamp)){
$ptdate = date('d M Y', $_GET['timestamp']);
}else{
$timestamp = strtotime($ptdate);
}
if(!isset($page)){
$page=1;
}
if($page=="" || $page<=0)$page=1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."'")or die("error querying");
$numrows = mysqli_num_rows($numresults);
$num_items = $numrows; //changable
$items_per_page= 5;
$num_pages = ceil($num_items/$items_per_page);
if($page>$num_pages)$page= $num_pages;
$limit_start = ($page-1)*$items_per_page;
$npage = $page+1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."' LIMIT $limit_start, $items_per_page")or die("error querying");
$numrows = mysqli_num_rows($numresults);
if($numrows==0){
echo "Sorry, No results for $ptdate.";
exit();
}
echo "<p><table>";
while($msdrow = mysqli_fetch_assoc($numresults)){
$charge= $msdrow['charge'];
$fname= $msdrow['firstname'];
$lname= $msdrow['lastname'];
// $fullname = $fname." ".$lname;
echo "<tr><td>$fname</td><td>$lname</td><td>$charge</td></tr>";
$totalcharge = $totalcharge+$charge;
}
echo "<b><tr><td colspan=\"2\">Total Charge</td><td>$totalcharge</td></tr></b></table></p>";
echo "<div id='pagediv' >";
echo "$page</div>";
echo "<div id='timediv' >";
echo "$timestamp</div>";
echo "<p align=\"center\">";
if($page>1)
{
$ppage = $page-1;
echo "«PREV ";
}
if($page<$num_pages)
{
$npage = $page+1;
echo "Next»";
}
echo "<br/>$page/$num_pages<br/>";
echo "</p>";
What am i doing wrong here, since it after second click it jumps out of ajax directs to original php page.
Thanx
You would need to set onclick event handlers on the pagination links after loading the content in ptreport1.php. You'll need to change .pagination-link to match the links in the content you are loading.
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
});
}
I'm trying to create a HTML table that lists all the rows in a database table. Then, next to each row I want to have a button so the user can delete that entry. I have created the table but I can't get the buttons to work.
I have been searching around and I found this post How to Call a PHP Function on the Click of a Button but I can't get it to work. I've never used ajax before so I might not understand the code correctly.
Here is the code:
Go through all the data from the table and create a button for each entry
<?php
for ($x = 0; $x < sizeof($data); $x++) {
?>
<input type="submit" class="tableButton" name="<?php echo $x ?>" value="<?php echo $x ?>">
<?php
}
?>
When a tableButton is clicked, send its value to ajax.php
$('.tableButton').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = { 'action': clickBtnValue };
$.post(ajaxurl, data, function (response) {
});
});
ajax.php
Get the value of the button that was pressed and do something with it
<?php
if (isset($_POST['action'])) {
$data = $_POST['action'];
echo $data;
}
?>
Currently I just have it echo the value to test it but it's displaying nothing. What I would have it do is run this query:
DELETE from myTable WHERE id = $data;
Or if someone knows a better way to do this please let me know.
Edit
After doing a lot more searching I found out why this wasn't working how I expected. As I suspected since I've never used AJAX before there was something I missed, I didn't know the echo wouldn't print directly to the screen. I just changed the echo to a delete query and tested that and it works... So the code is fine, but I think I should learn AJAX sometime. Thanks for all the responses.
I'm also aware of the sql injection that is possible here, this was just a quick mock-up, thanks.
It is hard to help you from this point of view we got.
You should do some debugging, like:
Check if the associated ajax.php is called (by checking the console with "F12" for example)
If yes, check the data being passed through your ajax POST
If not, maybe the reference link is wrong
Let me hear what you got.
You can try by this way. I think it will help you
Html File
<html>
<head>
<title>Test</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('.tableButton').live('click', function(){
var id = $(this).val();
$.ajax({
url:'ajax.php'
,data:{id:id}
,type:'post'
,success:function(data){
if(data == 'success'){
$('#' + id).remove();
}
}
});
});
</script>
<?php
for ($x = 0; $x < 5; $x++) {
?>
<input type="submit" class="tableButton" id="<?=$x?>" name="<?php echo $x ?>"value="<?php echo $x ?>">
<?php
}
?>
</body>
</html>
ajax.php
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
//delete operation here
//if(deleted) echo 'success';
}
?>
Ok. First of all you need to create the button with row id. You can do it using mySQL and PHP loops. Create it in this following format.
<input type="submit" name="test" data-id="23" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="24" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="25" value="Remove" class="delete_row" />
<input type="submit" name="test" data-id="26" value="Remove" class="delete_row" />
Here replace the data-id in each button with the id of row you are looking to delete.( Replace 23,24 etc with database ids dynamically ).
Java script
$(document).ready(function(){
$(".delete_row").click(function(e){
e.preventDefault();
var deleteId = $(this).attr("data-id");//unique id of the raw to be deleted
var request = $.ajax({
url: "ajax.php",
type: "POST",
data: { id : deleteId },
dataType: "json"
});
request.done(function( msg ) {
if( msg.status )
alert("Deleted successfully!");
else
alert("Something gone wrong!!");
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
ajax.php
<?php
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$delete_id = $_POST["id"];
if( is_numeric( $delete_id ) ){
/*DELETE QUERT WHERE id = $delete_id (Try to use mysqli or PDO ) */
/* $affected_rows = effected_rows() */
if( $affected > 0 )
{
echo json_encode( array("status" => true ) );die;
}
}
echo json_encode( array("status" => false ) );die;
}
die("Get out of here!");
?>
I hope this will help you :)
i have a pretty basic voting system i have implemented on my site. using the following ajax when a user clicks on the link there vote is added to the database and the vote is updated +1.
this all works fine but i would like to check if the user is logged in before allowing them to vote if there not display an error pop up or redirect to the login page (eventually i will display a lightbox popup asking for them to login or register.
<script type="text/javascript">
$(document).ready(function() {
$(".voteup a").click(function() {
var ID = <?php echo $moviedetails['id'] ?>
//$("#vote").text();
var rating = <?php echo $vote['vote_up'] ?>
var queryString = 'id=' + ID + '&vote=' + rating;
$("#voteup").text (rating + 1);
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(html) {
$("#votethanks").html('Thanks');
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
});
});
});
</script>
and vote_up.php
<?php
require_once("header.php");
$data = $_POST['id'];
$updatevote = "UPDATE `vote` SET `vote_up` = vote_up +1 WHERE `movie_id` = '$data'";
mysqli_query($con, $updatevote);
?>
i have tried
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
echo "<script>alert('Please login.')</script>";
}
else { //then the javascript
but it just checks the users logged in on page load, if there not it displays the please login error, but i need it to do this onclick of the javascript.
any help appreciated
thanks
lee
You can consider doing the check with PHP in the vote_up.php and check the response in your ajax. Something like this:
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(result) {
if (result.error) {
alert(result.msg);
} else {
$("#votethanks").html(result.msg);
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
}
});
in your vote_up.php:
<?php
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
// User is not logged in!
$result = array(
'error' => true,
'msg' => 'Please login first!'
);
} else {
// write the needed code to save the vote to db here
$result = array(
'error' => false,
'msg' => 'Thanks!'
);
}
// Return JSON to ajax call
header('Content-type: application/json');
echo json_encode($result);
Why not use your PHP to insert into a authenticated variable, just as you do with vote and ID?
For example:
var authenticated = <?php !(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '') ?>
Note: Completely untested. I just copied and pasted the php code from your "I have tried..."
Does this help?
Add a boolean. Every time the user clicks on the voting, send an ajax call to check if the user is logged in.
$(document).ready(function()
{
$(".voteup a").click(function()
{
var the_user_is_logged_in;
the_user_is_logged_in = checkLoggedIn();
if the_user_is_logged_in{
// do ajax call
}
else{
alert('Please log in!')
}
}
}
function checkLoggedIn(){
$.get('getsession.php', function (data) {
return data;
});
And in getsession.php you should write
<?php
session_start();
print json_encode($_SESSION);
I didn't try the code, but it should work.
This is what worked for me in the end. I am only sharing this to help someone who my encounter the same problem and end up with a migraine.
The ajax script:
<script type="text/javascript">
function review_likes ( addresscommentid )
{ $.ajax( { type : "POST",
async : false,
data : { "txt_sessionid" : addresscommentid },
url : "functions/review_likes.php",
beforeSend: function() {
// checking if user is logged in with beforeSend
<?php if (!(isset($_SESSION['signed_in_uid']) &&
$_SESSION['signed_in_uid']
!= '')) { ?>
$(window.location.href = 'admin/index-signin.php');
<?php } ?>
},
success : function ( sessionid )
{
$('#reviewlikes').removeClass('like-action');
$('#reviewlikes').load(document.URL + ' #reviewlikes');
},
error : function ( xhr )
{
alert( "You are not Logged in" );
}
});
return false;
}
</script>
On the review_likes.php page header:
<?php
$kj_authorizedUsers = "";
$kj_restrictGoTo = "../admin/index.php";
if (!((isset($_SESSION['kj_username'])) &&
(isAuthorized("",$kj_authorizedUsers,
$_SESSION['kj_username'], $_SESSION['kj_authorized'])))) {
$kj_qsChar = "?";
$kj_referrer = $_SERVER['PHP_SELF'];
if (strpos($kj_restrictGoTo, "?")) $kj_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$kj_referrer .= "?" . $_SERVER['QUERY_STRING'];
$kj_restrictGoTo = $kj_restrictGoTo. $kj_qsChar . "accesscheck=" .
urlencode($MM_referrer);
header("Location: ". $kj_restrictGoTo);
exit;
}
?>
The above code is a bit overkill, but it helps to get the current URL and redirect the user to the requesting page after successful login.
I'm trying to create a simple chat application that posts people's messages, and that gives the user an option to "reset" the chat which will delete all messages from the database so the user can start over. The messages post okay, but the reset button just sends an empty post (instead of deleting all current posts). I'm wondering what I'm doing wrong:
if ( isset($_POST['reset']) ) {
$sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':CHA' => $_POST['message']));
header( 'Location: '.sessionize('index.php') ) ;
return;
}
Per a comment below, I've updated my client side code to be:
<html>
<script type="text/javascript" src="<?php echo($CFG->staticroot); ?>/static/js/jquery-1.10.2.min.js"></script>
<body>
<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
<a style="color:grey" href="chatlist.php" target="_blank">Launch chatlist.php</a>
</form>
<p id="messages" >
<script type="text/javascript">
function htmlentities(str) {
return $('<div/>').text(str).html();
}
function updateMsg() {
window.console && console.log("Requesting JSON");
$.ajax({
url: '<?php echo(sessionize('chatlist.php')); ?>',
cache: false,
success: function(data){
window.console && console.log("JSON Received");
window.console && console.log(data);
$("#chatcontent").empty();
for (var i = 0; i < data.length; i++) {
entry = data[i];
$("#chatcontent").append("<p>"+entry[0] +
"<br/> "+entry[1]+"</p>\n");
window.console && console.log("entry " + entry[0]);
}
setTimeout('updateMsg()', 4000);
}
});
}
window.console && console.log("Startup complete");
updateMsg();
</script>
</p>
</body>
The code in its entirety, in case I've missed something/context is helpful:
<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";
require_once $CFG->dirroot."/lib/lms_lib.php";
// This is a very minimal index.php - just enough to launch
// chatlist.php with the PHPSESSIONID parameter
session_start();
// Retrieve the launch data if present
$LTI = requireData(array('user_id', 'result_id', 'role','link_id'));
$instructor = isset($LTI['role']) && $LTI['role'] == 1 ;
$p = $CFG->dbprefix;
if ( isset($_POST['message']) ) {
$sql = "INSERT INTO {$p}sample_chat
(link_id, user_id, chat, created_at)
VALUES (:LI, :UID, :CHA, NOW() )
ON DUPLICATE KEY
UPDATE chat = :CHA, created_at = NOW()";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':LI' => $LTI['link_id'],
':UID' => $LTI['user_id'],
':CHA' => $_POST['message']));
$messages = array();
header( 'Location: '.sessionize('index.php') ) ;
return;
}
if ( isset($_POST['reset']) ) {
$sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':CHA' => $_POST['message']));
header( 'Location: '.sessionize('index.php') ) ;
return;
}
?>
<html>
<script type="text/javascript" src="<?php echo($CFG->staticroot); ?>/static/js/jquery-1.10.2.min.js"></script>
<body>
<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
<a style="color:grey" href="chatlist.php" target="_blank">Launch chatlist.php</a>
</form>
<p id="messages" >
<script type="text/javascript">
function htmlentities(str) {
return $('<div/>').text(str).html();
}
function updateMsg() {
window.console && console.log("Requesting JSON");
$.ajax({
url: '<?php echo(sessionize('chatlist.php')); ?>',
cache: false,
success: function(data){
window.console && console.log("JSON Received");
window.console && console.log(data);
$("#chatcontent").empty();
for (var i = 0; i < data.length; i++) {
entry = data[i];
$("#chatcontent").append("<p>"+entry[0] +
"<br/> "+entry[1]+"</p>\n");
window.console && console.log("entry " + entry[0]);
}
setTimeout('updateMsg()', 4000);
}
});
}
window.console && console.log("Startup complete");
updateMsg();
</script>
</p>
</body>
Major issue:
$.getJSON('<?php echo(sessionize('chatlist.php')); ?>', function(data){
^^^--- using http GET
if ( isset($_POST['reset']) ) {
^^^^---expecting HTTP POST
.getJSON() is for GET requests only. If you want to use a POST, you'll have to use $.ajax() instead.
You are doing a GET request using ajax. Make a POST request. Add Type. For Example
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I suggests best thing you can do is: Use PHP REQUEST variable. Using it use can accept either post or get requests. i.e. For example:
if ( isset($_REQUEST['reset']) ) {
/***Code to delete chat **/
}