Ajax in codeigniter always returns false - php

I need to compare two datetime objects but the ajax ain't working.
javascript
<script>
$(document).ready(function(){
$('.datepicker').change(function(){
var date=$(this).data('datepicker').getFormattedDate('yyyy-mm-dd');
$(this).attr('value',date);
});
$('#collectDate').change(function(){
var collectDate=$('#collectDate').val();
var expiryDate=$('#expiryDate').val();
$.post("index.php?ajaxController/fine",{collectDate:collectDate,expiryDate:expiryDate},
function(data){
if(data){
$('#fine').hide();
$('#collectFine').removeAttr('required');
}
else if(!data){
$('#fine').show();
$('#collectFine').attr('required');
}
});
});
$('#fine').hide();
});
</script>
Controller
<?php
class ajaxController extends CI_Controller{
public function fine() {
$data['collectDate']= $this->input->post('collectDate');
$data['expiryDate']= $this->input->post('expiryDate');
$this->load->view("backend/admin/fine",$data);
}
}
View
<?php
$collectDate=$collectDate;
$date= explode('/',$expiryDate);
$expiryDate1=new DateTime($date[2]."-".$date[0]."-".$date[1]);
$diff=$collectDate->diff($expiryDate);
if($diff>=0){
echo true;
}
else {
echo false;
}
I've also tried simple comparison operators but all in vain. It always executes the else part in success function.

It always returns false because you cannot really catch true/false in php code with ajax. What that code in your view does, is make some calculations, return true or false AND THEN RENDER AN HTML PAGE, an empty one in your case.
Calling that page with ajax, means you read the HTML, which if an empty page, means no data returned, so FALSE.
What you need to do is something like this:
In your view:
if($diff>=0){
echo 'true';
}
else {
echo 'false';
}
And in your jQuery:
$('#collectDate').change(function(){
var collectDate=$('#collectDate').val();
var expiryDate=$('#expiryDate').val();
$.post("index.php?ajaxController/fine",{collectDate:collectDate,expiryDate:expiryDate},
function(data){
if(data.indexOf('true') > -1){
$('#fine').hide();
$('#collectFine').removeAttr('required');
}
else if(data.indexOf('false') > -1){
$('#fine').show();
$('#collectFine').attr('required');
}
});
});
This should be fine.

Related

hiding a div from users view

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();
}
});
});

Extracting data passed with jQuery post Ajax

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) {

jquery $("#form").submit() not getting called

I have a form on a page that requires a captcha if the user has a blocked attribute set in a database.
$("#expressform").submit(function() {
if($("#op").val() == "")
return false;
if($("#tagbar").val() == "")
return false;
$.post("getallowed.php", function(data) {
if(data == "true")
submitNormal();
else if(data == "false"){
displayCaptcha();
}
});
return false;
});
If the user is not allowed, the displayCaptcha function is called instead of just submitting the form.
function displayCaptcha(){
$.post("expresscaptcha.php", function(data) {
var string = data;
$("#expressformdiv").html(string);
Recaptcha.create("xxxxxxxxxxx", "captcha",
{
theme: "red",
callback: Recaptcha.focus_response_field
}
);
});
}
This function posts to a php script that returns a new type of form that returns the html for a new form with the id expressformcaptcha. Here is the php script.
<?php
echo <<<_END
<form id="expressformcaptcha">
//other form elements
<div id="captchadiv"><div id="captcha"></div></div>
</form>
_END;
?>
All of this works fine, the captcha displays, etc. However, the alert in the following never gets called. Why?
$("#expressformcaptcha").submit(function() {
alert("FORM SUBMITTED");
});
Does it have something to do with the captcha being there that screws with jquery? When submit the form, instead of the alert, the page just refreshes.
You need to use live or delegate as expressformcaptcha is injected into the DOM at a later time.
$("#expressformcaptcha").live('submit', function() {
alert("FORM SUBMITTED");
});

Posting not working via JS (Jquery) but is with form

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.

how to use jquery $.post posting on the same page rather than another?

here is my jquery $.post
$(document).ready(function() {
$("form[name=frmedit]").submit(function() {
$.post('index.php',
{
dealname: $("[name=dealname]").val(),
startdate: $("[name=startdate]").val()
},
function(data)
{
if(data.success)
{
location.href = data.redirect;
}
else
{
$("#colright #error").html(data.message);
}
}, 'json');
return false;
});
});
the php part is on the same page
if(isset($_POST['btnNext']) && ($_FILES['image']['size'] > 0))
{ //run query to save data }
so my question is can i have all this on one page?
i also have another question
where i have
$("form[name=frmedit]").submit
how can i put the name of the button btnNext in that rather than just .submit?
the reason why i want to use all this on one page is because when a submit is done i want to check
if a thumbnail uploaded is greather than 0 being that it exists, like i was normally doing.
thanks
if your ajax succeeds , then return true so that it will do form submit otherwise do a false, it won't do a form submit
function(data)
{
if(data.success)
{
return true
}
else
{
$("#colright #error").html(data.message);
return false
}
}, 'json');
return false;

Categories