All i want is, a data will pass into this php file: check.php and this php file will pass data into that function when the page is ready. this is just an expirement.
ok I have this code:
$(document).ready(function() {
$.post("check.php", {
name: "log"
}, function(data) {
if (data === "yes") {
alert('has been login');
} else {
alert('has not login');
}
});
});
and i have this php code ("check.php") where the jquery post will pass the data into.
<? //check
$chk = $_POST['name'];
if (isset($chk === "log")) {
if (isset($_COOKIE['admin'])) {
if ($_COOKIE['admin'] === "login") {
echo "yes";
}
} else {
echo "no";
}
} else {
echo "no";
}
?>
but nothing happen, even i change the whole code in check.php into: "echo "yes";" theres nothing happen, i guess, its either there is no data receive or there is no data pass. Hope someone could help me into this simple and cute problem that im stuck with. thank you in advance
I think you missed a closing brace. This just works as expected:
$.post('check.php', { name: 'log' }, function(data) {
if (data === "yes")
{
alert ('has been login');
}
else
{
alert ('has not login');
}
});
Run this JSFiddle http://jsfiddle.net/S53k5/
and you will see the call passing by in Fiddler.
I would guess it's because you're using the header "name" and that is a reserved keyword.
Related
I am making an ajax call in a file called level1_1.php that posts to validate1_1.php (attached below). However, what happens is that the user gets redirected to validate1_1.php which simply prints to the screen the string (either "CORRECT", "INCORRECT", or "NOLIVES") that I want to be passed into the callback function that makes up the third parameter of my $.post call. How do I return back to level1_1.php from validate1_1.php??
level1_1.php:
session_start();
<h5>Type answer here: </h5>
<form>
<textarea rows="10" cols="50" name="userinput"></textarea>
<span> <?php echo $msg;?></span>
<br>
<input id="submit" type="submit" name="Submit">
</form>
<script>
$("#submit").click(function(){
$.post("validate1_1.php",
{
userinput: $("#userinput").val;
},
function(data){
if (data == "CORRECT")
{
alert("Good job! Get ready for the next level!");
// take user to next level
window.location.replace("game.php");
}
else if (data == "INCORRECT")
{
alert("Sorry, that is incorrect. You have lost a life.");
}
else
{
// redirect user to game over screen
window.location.replace("gameover.php");
}
});
});
</script>
validate1_1.php:
<?php
session_start();
$msg = "";
$userinput = preg_replace('/\s+/', '', $_POST["userinput"]);
// if incorrect, lose life
if (strcasecmp($userinput, $_SESSION["ptext"]) != 0)
{
$_SESSION["lives"]--;
$msg = "INCORRECT";
// if no more lives, game over!
if ($_SESSION["lives"] == 0)
{
$msg = "NOLIVES";
}
}
// otherwise, move on to next level
else
{
$msg = "CORRECT";
}
echo $msg;
?>
change the below line
userinput: $("#userinput").val;
to
userinput: $("#userinput").val();
Here are some fixes. If you still have problems, use your browser's debugging tools to help.
$("#submit").click(function(e){
// 1. prevent your submit button from submitting the form
e.preventDefault();
$.post("validate1_1.php",
{
// 2. you're using 'name' attribute not 'id' attribute
// 3. val() not val
userinput: $("[name=userinput]").val();
},
function(data){
if (data == "CORRECT")
{
alert("Good job! Get ready for the next level!");
// take user to next level
window.location.replace("game.php");
}
else if (data == "INCORRECT")
{
alert("Sorry, that is incorrect. You have lost a life.");
}
else
{
// redirect user to game over screen
window.location.replace("gameover.php");
}
});
});
I want to return true when the number of rows in a table is more than one and show a div with jquery as shown in the jquery code .In addition return false when the number of rows is zero and hide a div as shown in the code below.The php code is executing and returning a correct value but the jquery code is neither showing or hiding a div.I need to show a div when the value returned is true and hide a div when the value returned is false;
**php code** php code for retrieving the number of rows from a table
<?php
require'php/connection.php';//a file for connecting to the database
$user_name=getUserField('user_name');//function for getting the name of the user in session
$query="select `order_id` from `inbox` where `buyer_name`='$user_name'";
$query_run=mysql_query($query);
$num_rows=mysql_num_rows($query_run);
if($num_rows >= 1) {
return true;
} else if($num_rows == 0) {
return false;
}
?>
jquery code Jquery code for either hiding or showing a div
$(document).ready(function() {
$.post('php/ManNotify.php',{},function(data){
if(true) {
$('#notify').show();
} else if(false) {
$('#notify').hide();
}
});
});
Do you realize your if statement reads,
if(true) ..
else if(false) ...
The hide will never execute. Is this your problem?
When using AJAX calls with PHP, you should echo the value rather than return it. Modify your PHP code like so:
<?php
require'php/connection.php';//a file for connecting to the database
$user_name=getUserField('user_name');//function for getting the name of the user in session
$query="select `order_id` from `inbox` where `buyer_name`='$user_name'";
$query_run=mysql_query($query);
$num_rows=mysql_num_rows($query_run);
if($num_rows >= 1){
echo json_encode(array("status" => true));
} else if($num_rows == 0) {
echo json_encode(array("status" => false));
}
exit;
?>
You'll also need to modify your JavaScript accordingly. Right now, if(true) will always execute on the return. Modify it like so:
// Shorthand for $(document).ready
$(function(){
$.post('php/ManNotify.php',{}, function(data) {
// JavaScript truthy/falsy will take care of the statement
if(data.status) {
$('#notify').show();
} else {
$('#notify').hide();
}
});
});
EDIT:
As #mplungjan points out in the comments below, the JavaScript could be simplified in the callback to be the following: $('#notify').toggle(data.status);. The resulting JavaScript would be:
// Shorthand for $(document).ready
$(function(){
$.post('php/ManNotify.php',{}, function(data) {
$('#notify').toggle(data.status);
});
});
Thanks to #mplungjan for the suggestion.
$(document).ready(function(){
$.post('php/ManNotify.php',{},function(data){
if(data == 'true'){
$('#notify').show();
}else if(data == 'false')
{
$('#notify').hide();
}
});
});
There are two problems with your code:
The server-side code. Returning boolean TRUE or FALSE this way will only render the page blank.
The jQuery code logic is wrong: if(true){ case will always be executed (because the value is, well, always true).
A very simple fix would be (untested):
if($num_rows >= 1){
echo 'true';
} else {
echo 'false';
}
Then, in the JS:
$.post('php/ManNotify.php', function(data){
if(data === 'true'){
$('#notify').show();
} else {
$('#notify').hide();
}
});
Note that this is not optimized.
$(document).ready(function(){
$.post('php/ManNotify.php',{},function(data){
if(data == "true"){
$('#notify').show();
}else if(data == "false")
{
$('#notify').hide();
}
});
});
I have a notification system that works with the following codes
jQuery:
$(document).ready(function(){$.get('/codes/php/nf.php', function(data) {
$('#check').html(data);});
});
setInterval(function(){$.get('/codes/php/nf.php', function(data) {
$('#check').html(data);});
}, 10000);
PHP:
//Database stuff would be here
$na = $num_rows; //Amount of notifications
if($na == "1"){
$nt="Notification";
} else {
$nt="Notifications";
}
if($na != "0"){
echo "<a href='#'>$na $nt</a>";
} else {
exit;
}
HTML: (It's a tipsy -- jQuery plugin -- tooltip)
title="<span id='check'>"
My only problem is when there is 0 notifications ($na = 0) a blank tooltip is displayed, and it looks really bad. So basically I can't have the 'title=' if I want to get rid of this problem, but I don't have any ideas. Anybody know I can fix this?
Ok, so I found out that I can't use this: title="" at all because even when there is no data at all, the tooltip is still being displayed.
try change
function(data) {
$('#check').html(data);
}
with this :
function(data) {
if (data != '') {
$('#check').html(data);
}
}
Hey all, I cannot seem to get a simple ajax working between a php page and jquery. I have followed a few tutorials. but having trouble actually understanding what is actually going on.
Javascript (JQuery)
$(function(){
$('#trigger').click(function(){
askajax;
});
function askajax(){
$.post("ask.php",{ question: "canuseeme" } ,function(data)
{
if(data=='yes')
{
alert("answer is yes");
}
else
{
alert("answer is no");
}
});
}
});
The PHP:
if($_POST['question']){
echo "yes";
} else {
echo "no";
}
Any ideas guys?
EDIT: THANKS TO #Jacob
$('#trigger').click(function(){
alert("doing ajax"); // THIS SHOWS
$.post("ask.php",{ question: "canuseeme" }, function(data)
{
if(data=='yes')
{
alert("answer is yes"); // THIS DOESNT
}
else
{
alert("answer is no"); // THIS DOESNT
}
});
});
This'll work:
$('#trigger').click(askajax);
Or this:
$('#trigger').click(function() {
askajax();
});
But I prefer to do it this way:
$(function(){
$('#trigger').click(function(){
$.post("ask.php",{ question: "canuseeme" } ,function(data)
{
if(data=='yes')
{
alert("answer is yes");
}
else
{
alert("answer is no");
}
});
});
});
Reason being that you don't ever use the askajax function again, and it will only be defined in the ready function's scope, so why even bother with a standalone function definition? Just use an anonymous function and be done with it. :)
On line 3, change askajax; to askajax();
I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.