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.
Related
I have problem with a log in form. When I try to log in the javascript always returns the false value even when I am typing correct username and password.
Here is my code in the jQuery file:
$(document).ready(function(){
var teamname = $("#teamname");
var teampassword = $("#teampassword");
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
var result = false;
$.post('../php/validations/validatePassword.php', {tname: name, tpassword: password}, function(data){
if(data == 1){
result = true;
}else{
result = false;
}
});
return result;
}
$("#join").click(function(){
if(isPasswordCorrect()){
alert("You have joined");
}else{
alert("You have not joined");
}
});
});
Here is my code in the PHPfile:
<?php
$teamname = $_POST['tname'];
$teampassword = $_POST['tpassword'];
if($teamname != "" || $teampassword !=""){
include('../connection.php'); // Here is the log in to the phpmyadmin
$queryCheckPassword = mysqli_query($con, "SELECT password FROM
teams WHERE name = '$teamname'");
$row = mysqli_fetch_row($queryCheckPassword);
$teamPassword = $row[0];
if($teamPassword == $teampassword)
{
echo 1;
}else{
echo 0;
}
}
?>
And here is my code in HTML file:
<form id="joinform"> <!-- action="teams.php" method="post"> -->
<ul>
<div>
<label>Team name <font color='red'>*</font></label>
<input type='team' name='teamname' id='teamname' placeholder='Team name' readonly='readonly'/>
<span id='teamnameinfo'>Select an existing team</span>
</div>
<div>
<label for="teampassword">Team password <font color='red'>*</font></label>
<input type='password' name='teampassword' id="teampassword" placeholder='Team password'/>
<span id='teampasswordinfo'>Write team password</span>
</div>
<div>
<button name='join' id='join'>Join</button>
</div>
</ul>
</form>
The problem lies in your use of Javascript. Look at your isPasswordCorrect function (which I have reformatted slightly to make the issue a little clearer):
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
var result = false;
$.post(
'../php/validations/validatePassword.php',
{tname: name, tpassword: password},
function (data) {
if(data == 1){
result = true;
}else{
result = false;
}
}
);
return result;
}
See that function (data) {} in there? That's a callback. The way the $.post method works is this:
your JS code sends a request to the server using $.post
your JS code continues, moving on to whatever comes next
Some time later (could be 10 milliseconds later, could be 30 seconds later), the server responds to the request. At that point your callback is called.
What does this mean? When your code hits the return result; line, your code has just submitted the request to the server and the server has probably not responded yet. Thus, result is still false.
A quick solution to this problem is to move the alert statements into the callback, like this:
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
$.post(
'../php/validations/validatePassword.php',
{tname: name, tpassword: password},
function (data) {
if(data == 1){
alert("You have joined");
}else{
alert("You have not joined");
}
}
);
}
$("#join").click(function(){ isPasswordCorrect(); });
However, I imagine you're going to want to do more than just alert something. You're going to need to research the asynchronous nature of Javascript and understand it before you can extend this fragment to do much.
PeterKA is correct about the async. The default value (false) is probably be returning before your async call comes back. Try adding a callback instead (untested):
function isPasswordCorrect(callback)
{
var password = teampassword.val();
var name = teamname.val();
$.post('../php/validations/validatePassword.php', {tname: name, tpassword: password},
function(data) { callback(data == 1); });
}
$("#join").click(function(){
isPasswordCorrect(function(result) {
if (result)
alert("You have joined");
else
alert("You have not joined");
});
});
Because AJAX does not return the result immediately - ASYNCHRONOUS - you want to do the check only and only when you have the result - in the AJAX callback like so:
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
$.post(
'../php/validations/validatePassword.php',
{ tname: name, tpassword: password },
function(data) {
if(data == 1) {
alert("You have joined");
} else {
alert("You have not joined");
}
}
);
}
$("#join").click(isPasswordCorrect);
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();
}
});
});
When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.
I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.
Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:
HTML:
<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery:
jQuery('form#basicform').submit(function() {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;
});
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return true;
}
To be very specific to the question:
How can I get the server response back in the jQuery (to check if
there was any server error or not). Here's what I'm trying:
Sound like you're talking about Server-Side validation via jQuery-Ajax.
Well, then you need:
Send JavaScript values of the variables to PHP
Check if there any error occurred
Send result back to JavaScript
So you're saying,
However, I am trying to use a basic jQuery (without any plugin) to
check if any field was blank, I want to post the form content only if
there's no any blank field.
JavaScript/jQuery code:
Take a look at this example:
<script>
$(function()) {
$("#submit").click(function() {
$.post('your_php_script.php', {
//JS Var //These are is going to be pushed into $_POST
"name" : $("#your_name_field").val(),
"email" : $("#your_email_f").val()
}, function(respond) {
try {
//If this falls, then respond isn't JSON
var result = JSON.parse(respond);
if ( result.success ) { alert('No errors. OK') }
} catch(e) {
//So we got simple plain text (or even HTML) from server
//This will be your error "message"
$("#some_div").html(respond);
}
});
});
}
</script>
Well, not it's time to look at php one:
<?php
/**
* Since you're talking about error handling
* we would keep error messages in some array
*/
$errors = array();
function add_error($msg){
//#another readers
//s, please don't tell me that "global" keyword makes code hard to maintain
global $errors;
array_push($errors, $msg);
}
/**
* Show errors if we have any
*
*/
function show_errs(){
global $errors;
if ( !empty($errors) ){
foreach($errors as $error){
print "<p><li>{$error}</li></p>";
}
//indicate that we do have some errors:
return false;
}
//indicate somehow that we don't have errors
return true;
}
function validate_name($name){
if ( empty($name) ){
add_error('Name is empty');
}
//And so on... you can also check the length, regex and so on
return true;
}
//Now we are going to send back to JavaScript via JSON
if ( show_errs() ){
//means no error occured
$respond = array();
$respond['success'] = true;
//Now it's going to evaluate as valid JSON object in javaScript
die( json_encode($respond) );
} //otherwise some errors will be displayed (as html)
You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). This makes the check easier since you have something in data.
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return json_encode(array("error" => 0));
} else {
return json_encode(array("error" => 1));
}
JavaScript:
jQuery('input#frmSubmit').submit(function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
var myData = data;
if(myDate.error == 1) {//or "1"
//do something here
} else {
//do something else here when error = 0
}
});
}
$("form#basicform").submit();
return false;
});
There are two ways of doing that
Way 1:
As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. So if you want to do your validation prior to form submission, you must preventDefault() its behaviour
jQuery('form#basicform').submit(function(e) {
//code
e.preventDefault();
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$(this).submit();
return false;
});
Way 2:
Or simply replace your submit button with simple button, and submit your form manually.
With $("yourFormSelector").submit();
Change your submit button to simple button
i.e
Change
<input type="submit" name="submit" value="Submit"/>
To
<input id="frmSubmit" type="button" name="submit" value="Submit"/>
And your jQuery code will be
jQuery('input#frmSubmit').on('click',function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$("form#basicform").submit();
return false;
});
To get the response from the server, you have to echo your response.
Suppose, if all the variables are set, then echo 1; else echo 0.
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
echo 1;
} else {
echo 0;
}
And in your success callback function of $.post() handle it like
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
if(e.data.err==1){
alert("no error");
} else {
alert("error are there");
});
});
I'm trying to make simple script using jquery $post function to pass data to my check.php file and then just get some result back so I can figure out the way data is manipulated b/w jQuery and PHP.
I have this script:
<script type="text/javascript">
$(document).ready(function(){
var Status = true;
$('.isLogged').click(function(){
if(Status!=false){
var Check = prompt('Enter Password', '');
$.post('check.php', Check, function(data) {
if(data == 'Y'){
alert('Y');
return false;
}
else
{
alert('N');
return false;
}
});
}
});
});
</script>
and this is all from my check.php file:
<?php
$data = $_POST['Check'];
if ($data == 'Ivan')
{
echo 'Y';
}
else
{
echo 'N';
}
?>
but it's not working and when I make var_dump($_POST) I get array(0). How can I fix this?
Thanks
Leron
"data" in $.post function must be a object
$.post('check.php', {Check: Check}, function(data) {
you should add json in your process.
:)
Your syntax is not correct for ajax request. Check is the value, you must set key for it. Should be like this
var Check = prompt('Enter Password', '');
$.post('check.php', Check:Check, function(data) {
I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});