I am building a simple antibot for my email form.
This is a code which makes a problem:
<?php
session_start();
$a = rand(1, 10);
$b = rand(1, 10);
$antibot = $a + $b;
$_SESSION["antibot"] = $antibot;
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#sendEmail").click(function(){
var antibot = $("#antibot").val();
$.post(
"test.php",
{antibot: antibot},
function(data){
alert(data.info);
},
"json"
);
);
);
);
</script>
</head>
<body>
<table>
<tr><td>AntiBot: <?php echo $a . ' + ' . $b;?> = </td><td><input type='text' id='antibot' /></td></tr>
<tr><td colspan='2'><input type='button' id='sendEmail' value='Send'/></td></tr>
</table>
</body>
</html>
And my test.php
<?php
session_start();
$antibot = $_POST["antibot"];
$data = array();
if(isset($_SESSION["antibot"])){
if($_SESSION["antibot"] == $antibot){
$data["info"] = "Session is isset and answer is right!";
}
else{
$data["info"] = "Session is isset but answer is NOT right!";
}
}
else{
$data["info"] = "Session is NOT isset!";
}
echo json_encode($data);
?>
I constantly get this info: "Session is isset but answer is NOT right!"
If you can see $_SESSION["antibot"] in test.php is setted but value is "" no matter what I type in input field #antibot!
I do not understand why this is happening, please can someone tell me where the problem is and how can I fix it?
I tested this code here:
http://onlinephpfunctions.com/stackoverflow/11981309/
And it seems completely valid.
I had to make some modifications to your javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#sendEmail").click(function(){
var antibot = $("#antibot").val();
$.post(
"test.php",
{antibot: antibot},
function(data){
alert(data.info);
},
"json"
)
})
})
</script>
After that it was working fine. It may just be some problems with cookies in your browser, or an error in your PHP config so sessions wont be stored right. Please check this, your code works OK, as you can see in the demo.
Related
The following is a sample PHP code. I am expecting the session variable 't' to increment its value when update function is called. However, when I run the code I keep getting the output as Value: 1. What should I do so that the value is stored into the session variable?
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
Put session_start() at the very top of your script, before any output
<?php
session_start();
// if you automatically set SESSION['t'] to 0 when the page loads, it will never increment
// check if the SESSION exists, and if it doesn't, then we create it
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<!-- it's recommended to load scripts at the end of the page -->
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
// you had some formatting issues in here...
// shortcut: using +=1 will take the current value of $_SESSION['t'] and add 1
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
UPDATE:
This is an example that will do what I think you're looking for. It will display the value of $_SESSION['t'] when the page is loaded, and then increment the value of $_SESSION['t'] every time the update button is clicked. There is no error checking, this is just a very simple example to show you how this works.
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<button type="button" id="update">Update</button>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function() {
// create the ct varaible
var ct = <?php echo $_SESSION['t']; ?>;
// display the value in the #test div
$("#test").text(ct);
// when the update button is clicked, we call ajax.php
$("#update").click(function(){
$.post("ajax.php", function(response){
// display the returned value from ajax.php
$("#test").text(response);
});
});
});
</script>
ajax.php
<?php
session_start();
// increment the session by 1
$_SESSION['t'] += 1;
// return the result
echo $_SESSION['t'];
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 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
I have this PHP code:
JSON.php
<?php
$array = array('items' => 38);
$JSONItems = json_encode($array);
return $JSONItems;
?>
Items.html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$.getJSON("http://domain.com/JSON.php?callback=?",
function(data){ alert(data.items) }
);
</script>
When Items.html is displayed no alert is fired, and nothing happens. (No Console Errors Or Anything)
Any idea what I'm doing wrong?
You're calling return in your PHP script. That doesn't do what you think it does.
you need to use echo
i just tried this and it works fine
<script type="text/javascript">
</script>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/json.php",
function(data){ alert(data.items) }
);
});
</script>
PHP
<?php
$array = array('items' => 38);
$JSONItems = json_encode($array);
print_r( $JSONItems ) ;
?>
Within my index.php file I have an AJAX function that will call a function within another php file which should increment a number and return it whenever i call the AJAX function.
The problem is that the number never changes. I have tried lots of different things. Too many to list them all unfortunately.
My index.php file.
<?php
session_start();
$_SESSION['views'] = 0;
?>
<?php include 'blogFunction.php';?>
<script type="text/javascript">
function doSomething()
{
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
}
</script>
<div class ="blog" id = "blog"></div>
my blogFunction.php
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Right now the output is always '1' whenever i hit the button that calls the AJAX function.
Any help appreciated.
Live Code:here
Thank you all for the help so far. One problem down, a new problem appears.
Extended Functionality:
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$request_url = "http://retrovate.tumblr.com/api/read?type=posts";
$xml = simplexml_load_file($request_url);
$a = $_SESSION['views'];
$b = $_SESSION['views'] +4;
echo "A = ".$a;
echo "B = ".$b;
$_SESSION['views'] = $_SESSION['views']+ 1;
for ($i = $a; $i <= $b; $i=$i+1) {
echo '<h2>'.$xml->posts->post[$i]->{'regular-title'}.'</h2>';
echo '<br>';
echo $xml->posts->post[$i]->{'regular-body'};
echo '<br>';
echo '<br>';
}
}
The problem that lies here, is, I click my button once at my site
and it increments and shows the new content. I click again and it reverts back to 0. If I click the button numerous times fast, it seems to work. It seems that chrome is having this problem whereas Firefox is not.
Add session_start(); to blogFunction.php
Here's the properly working code...
index.php
<?php
session_start();
$_SESSION['views'] = 0;
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js" />
<body>
<div class ="blog" id = "blog"></div>
<input type="button" value="Add to the count!" id="call_ajax"/>
<script type="text/javascript">
$('#call_ajax').click(function () {
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
});
</script>
</body>
blogFunction.php
<?php
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Notice that I'm not including blogFunction.php in the index.php file! That's important.
The other way you had it, you were setting the variable to 0 each time the page loaded, which was how the function was called (if you used the console to call it).
I added a button for you to click to call the function via Ajax (per your conditions in the original question).
Hope that helps!
You need to call session_start () in your blogFunction.php file. It has to be called before any output to the brower. Probably best case would be to call it first in the script.
I think that you should first unset $_SESSION['views'] and than write again.
function blogreturn(){
$temp = $_SESSION['views'];
unset($_SESSION['views']);
$_SESSION['views'] = $temp + 1;
echo "THIS number is:" .$_SESSION['views'];
}