jQuery .post gets null data - php

This is my first post here, so I hope I'm doing it appropriately.
I have several jQuery $.post calls that work just fine. They send data to a PHP script that modifies a database and returns some data. No problem.
But this one doesn't work. The returned data is just NULL.
$.post("act_addTaskLog.php",
{description: $("#logFormDescription").val(), complete: $("#logFormComplete").is(':checked'), taskId: $("#logFormTaskId").val(), user: <?php echo $_SESSION['user']; ?>},
function(data) {
alert("data: " + data);
}
);
I've tried everything I can think of, to no avail. I've even tried just one line in my PHP script:
die("true");
Firebug shows that the script is being executed, but it's not completing. The alert message displays just with the label "data:" in it, no actual data.
Thanks in advance for your help!

I feel like an idiot now. The problem was outside the code I posted here.
The $.post call is being made as the button action on a Dialog. I added a keydown listener for the Dialog (in the "open" method), so it would submit when Enter is pressed.
For some reason, pressing Enter reloaded the entire page. So I added this line to my keydown listener code:
window.stop();
That line was causing my problems with the callback data. Removing it fixed this issue. My actual $.post code was just fine.

Related

AJAX/PHP – callback after finished loading data

(Not sure if I missed an already similar answered question…)
On click of a button, I'm loading various images from a database via PHP/MySQL and appending it to the body (the actual images are of course not stored in the database, the correct selection of the images is based on a posted variable).
My goal is to display a loading indicator after pressing the button and hiding the indicator after all the image data has completely loaded and displayed. This may be an easy to solve callback issue but I'm just getting started with AJAX. :)
The following is the code I currently managed to come up with. I'm guessing the load() function is not really the right one here?
Thanks for your help!
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$(window).load(function(){
alert("finished loading…");
});
});
});
The function you have with the finished loading... alert is a success callback, so it gets executed once the AJAX call has finished. This means you don't need to use $(window).load.
Also, you can use the html method on an element to change its contents and display a message.
Something like this would work fine:
$("#somebutton").click(function(){
$('#divID').html('Loading...');
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$('#divID').html('');
});
});
Read the docs http://api.jquery.com/jQuery.ajax/
Use the success callback to append the body and then the complete and error callbacks to clear things up correctly.
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
})
.success(function(data){$("body").append(data)})
.error(function(){alert("oh dear")})
.complete(function(){alert("finished loading…")});
});
Remember to always have a fallback for removing the loader - nothing worse than just having a loader and no way to remove it from the page and continue using the application / web site.
I managed to solve my problem by reading and tweaking the code in the following article.
The function load() with the equation containing the self-explanatory variables [imagesLoaded >= imageCount] did the trick.
Know when images are done loading in AJAX response

JQuery.Post() purpose and difference

While working on a website I had a content area division whose content I wanted to update according to the image I click on. Now, I had a customized scrollbar which I used in the content area. Now at first I wrote the following snippet for onclick script function :
function xyz(){
$("#content-area").load("abc.php");
$("#content-area").mCustomScrollbar({scrollButtons:{enable:true}});
}
But the second line of the script wasn't responding i.e, I wasnt getting the scrollbar. Instead when I used this piece of code snippet it worked :
$.post("abc.php", function(data){
$("#content-area").html(data);
$("#content-area").mCustomScrollbar({scrollButtons:{enable:true}});
});
I am wondering the function of the $.post() and why the first snippet didnt work while the second snippet worked?
In the first case that mCustomScrollbar will be executed right after the AJAX request is sent: remember, first A in AJAX is for asynchronous. But it obviously has nothing to work on yet, as response from server is not here yet.
In the second snippet mCustomScrollbar widget creation happens right after the AJAX request's response is received (as this line is part of $.post success handler now) and that #content-area is filled with necessary structure (with .html()) call. So now it works correctly.
You can use the fact that $.load method can be supplied with custom callback function that will be executed when the request completes, as described here. For example:
$("#content-area").load("abc.php", function() {
$(this).mCustomScrollbar({scrollButtons:{enable:true}});
});
Note $(this) usage: as this is set to each DOM element in turn inside that callback function, you don't need to walk over the DOM looking for that content-area yet again; it's enough just to wrap that element into jQuery object.
You need to use callback function which is executed when request is complete:
$("#content-area").load("abc.php", function(){
$(this).mCustomScrollbar({scrollButtons:{enable:true}});
});
I suppose that in the first example the second statement was being executed before the completion of the .load() function. In the second you are correctly using the success function, which is only executed after the completion of the POST request.

JS not working on echoed PHP

So I have a form that is submitted via an Ajax POST request. After the send button is clicked, the form is removed and a processing graphic is put in its place. The form data is sent to my PHP script, validated, and a thank you message returns to replace the processing graphic if everything checks out. But if there is a validation error, I have a copy of the entire form echoed back to the div where the original form was at showing where the errors are in the form. This all works fine except when the copy of the form is echoed back, the JS for the form doesn't work? Neither the JS for the send button or for my focus/blur functions on the inputs. Thank you for any help.
When you remove the form from the DOM, the events are cancelled as well. You can have a function that sets these events and call it when there are errors in the response.
Did you try to just hide your form and display the processing graphic instead of removing the form ? And when you have an error, hide the graphic and display the form again.
With this solution, error handling will be a little more difficult, but you will not have your form at 2 places in your project !
When you insert HTML mixed Javascript into some node, eg a div, it isn't the same as serving it the first time as part of the whole document. It isn't considered a script when inserted as innerHTML or some textnode.
You have a few options:
** Switch visibility and encode the errorresponse (in JSON for example)
Create 2 divs, one holding the form, the other the PROCESSING image.
Switch display to none for the form when processing, and the image to block.
When you have processed the form and you have an error, encode it somehow (JSON, eg) and send that back, and let an EXISTING script on the page interpret the response.
You can for example create some structure that holds each formelementname, and the error associated with it, so you can easily highlight them in your form if you create an empty span next to each formelement where you can display the error.
When the answer arrives from the server, you can display the form again, and display:none the PROCESSING div.
** Interpret your response (WITH JAVASCRIPT)
This is more difficult, but also more elegant.
I once needed this (Javascript that returned from an XHR request), and Randy Webb helped me out with a smart approach.
It is too much to explain here.
Read this thread for a more detailed approach, and links to the script of Randy:
http://tinyurl.com/6pakdu
$.ajax({
url: 'mypage.html',
success: function(){
alert('success');
**<ADD YOUR CUSTOM CODE AFTER AJAX SUCCESS - JS CODE>**
},
error: function(){
alert('failure');
}
});
You can also ref.
http://docs.jquery.com/Ajax_Events
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});

returning data from a remote php script

I am using php/ajax to submit a form without page refresh. Here are my files-
coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
$.ajax({
url : "sms.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
e.preventDefault();
});
});
sms.php
<?php
//process form
$res = "Message successfully delivered";
$arr = array( 'mess' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
and here is code for my html page -
<form id="smsform" class="appnitro" action="sms.php" method="post">
...
</form>
<div id="mess" style="background:green;"></div>
Now instead of submitting form through ajax without page refreshing what is happening is that page gets redirected to
baseurl/sms.php and the only thing visible on page is
{"mess":"Message successfully delivered"}
My guess is that php script is not returning back successfully to the jquery and hence the echo in last part of sms.php is getting displayed. How should i make the php script return successfully?
ANY IDEAS HOW TO DEBUG THIS.I HAVE TRIED USING return false at the end of coupon.js but no results.
When i click on submit firebug gives following results -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response
Firebug needs to POST to the server to get this information for url:
http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
This second POST can interfere with some sites. If you want to send the POST again, open a new tab in Firefox, use URL 'about:config', set boolean value 'extensions.firebug.allowDoublePost' to true
This value is reset every time you restart Firefox This problem will disappear when https://bugzilla.mozilla.org/show_bug.cgi?id=430155 is shipped
#Fanis It's irrelevant whether he uses '$' or 'jQuery', they are synonyms.
#Ayush
As Fanis says, you should try Firebug if you don't use it already.
I've checked the example at my server, works OK, and I don't know
what's the problem at Your side.
You can use onsubmit="return false" to disable form submission:
<form id="..." class="..." ... onsubmit="return false">
Also check if javascript is enabled, for example do "alert('something')"
at $(document).ready
Edit:
// instead of
url: "sms.php"
// try
url: "/~kunal17/devbuzzr/wp-content/themes/street/sms.php"
// although I don't really know if it will help
If you're being redirected to sms.php instead of doing an ajax call, it probably means that there's something wrong with your jQuery code, probably the event binding itself.
I'm not sure without testing it, but shouldn't that code be:
$(document).ready(function(){
$(".appnitro").submit( function(e) {
$.ajax({
...
?
Check the javascript console, either in Firefox/Firebug or Chrome-IE/Developer Tools. Does it show any errors in those lines?
Fanis and Michal Kluczka are probably right about the issue with event binding , I tried your code myself as well, and it works for me.
Put an alert('X') as the first statements in your jQuery(document).ready() and jQuery(".appnitro").submit() functions and see if both are displayed (first one upon document load, second one upon form submission).
One more thing: I suggest you include a
header('Content-Type: application/json');
into your sms.php file before printing your JSON data to protect against cross-site-scripting (XSS) attacks. See also Don’t serve JSON as text/html for details.

Jquery Ajax + PHP

I am having problems with jQuery Ajax and PHP
I have my php file set up to echo the data I am gathering from a mysql database. I have verified that the database is returning something and that the string at the end of the function actually contains data.
What is happening though, is that it looks like the php echo is happening before the ajax call, causing the php data to be displayed at the top of the page, and not below in proper div.
I think it might have something to do with timing of the ajax and the php call, but I am not sure.
So, why is the data not getting caught by the .ajax and thrown into the div?
Thanks for the help!
jQuery
$(document).ready(function() {
$.ajax({
url: "../database_functions.php",
type: "GET",
data: "cat=jw&sub=pi&sort=no",
cache: false,
success: function (html) {
alert("Success!");
$('#product-list').html(html);
}
});
});
PHP
echo "Hello World";
Are you sure you didn't use an include or require in your page? Try doing the same
on a new empty dummy page. Also, try adding a thick red border to the div, so you are sure it is on the right position on the page, as there might be something wrong with your lay-out. Your code doesn't look wrong though.
If your JQuery code is in the same file as PHP code, it is given that PHP will be executed before JQuery code,.. since JavaScript is Client side, PHP is Server side, PHP file first get executed on the server, rendering static HTML from the dynamic PHP, and than when client browser render the page JavaScript get executed.
.ajax will be executed only once when whole page is loaded since you stated in JavaScript that you want that it get executed when document return event ready.
Why .ajax doesn't return value,.. It is not quite clear for the code you provided, problem could be in the file or path to the file ajax call trying to run.

Categories