When you use Jquery or Ajax to call a page or script, which loads into a div,
or example
$.post('pagename.php', $(#cpay'.$id.'").serialize(), function(data) { $('#conSupp".$id."').html(data);
is there a way to display an error message in the div if the page fails to load
Many thanks
If you are using jquery 1.5 or above, the post will return a jqXhr object. If so, you could do something like this:
$.post('pagename.php', data, function(data) {
//success, do stuff with the data object
}).fail(function(jqXhr, ajaxOptions, thrownError){
//something went wrong
alert('Error: ' + thrownError);
});
Yes, bind an error handler, by calling the .fail() function on the jqXhr object returned by the call to $.post():
$.post(url, data, function(data) {
...
}).fail(function(jqXhr, textStatus, errorThrown) {
// an error occurred - do something here
});
I prefer just doing:
$.ajax({
type: 'POST',
url : 'pagename.php',
data: $(#cpay'.$id.').serialize()
}).done(function(data {
$('#conSupp".$id."').html(data);
}).fail(function() {
$('#conSupp".$id."').html('An error occured');
});
It's a little longer, but I find it much easier to read an change to whatever I need, and it's exactly what $.post does internally anyway, so saves me a function call?
Related
Every one am new to php and ajax.
Am writing a code to fetch data from mysql database
and display them in textboxes but is not working.
Here is my code.
I need your help please.
Thanks in advance
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
}
});
});
<input type="text" id="input-box1">
<input type="text" id="input-box2">
<button type="button" id="btn_get">Click</button>
//get data from db here
$textbox1 = 'foo';
$textbox2 = 'deen';
echo $textbox1;
echo $textbox2;
Here are some approaches, maybe them can help you:
The first approach would be to check your console to make sure that the jQuery version allows you to use the $.ajax() resource. Some jQuery versions like the "slim" doesn't provide ajax calls.
Once you have checked that put the property error within your ajax call:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});
If you have a error response you will be able to identify it checking your browser's console tool (F12).
Check your /path/to/php/file to make sure that your file really exists.
Remember that the success callback gets your echo command as a string. So probably your return will be something like this:
foodeen
A good approach would be to return a json response:
$textbox1 = 'foo';
$textbox2 = 'deen';
echo json_encode(array($textbox1 ,"textBox1"));
Finally when your response is executed in the success callback you'll be able to convert it from plain string to a json format:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
var response = JSON.stringify(data);
$('#input-box1').val(response[0]);
$('#input-box2').val(response[1]);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});
Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.
So I am adding a list of stores to a web page via a jQuery AJAX request. This little utility is not dynamic, just database driven. I have decided to use jQuery/AJAX to transfer the data because when I try to embed PHP in our current PHP CMS, I get a bunch of conflicting errors.
The problem I am having is that I am getting a jQuery AJAX error when trying to make the request to the PHP script, and I am not sure why.
Here is my AJAX request
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(data) {
console.log(data.error);
}
});
});
The cryptic console error i am getting is this
function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
Here is my PHP code if it will be helpful:
//database connection
$return_arr = array();
$sql = mysql_query("SELECT * FROM where_to_buy");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$row_array['store_name'] = $row['store_name'];
$row_array['store_url'] = $row['store_url'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I think the problem might be because I wrapping my JSON in an array?
EDIT:: JSON output from php script as requested
[{"store_name":"Example 1","store_url":"http:\/\/www.example1.com"},{"store_name":"Example 2","store_url":"http:\/\/www.example2.com"}]
Thanks for any help!
The reason you are getting that weird error message is that the error callback for the jQuery ajax function takes 3 arguments instead of 1, as described in the docs here: http://api.jquery.com/jQuery.ajax/
The first argument is a jQuery-special XMLHttpRequest object, which has a property called error that contains the function you are seeing logged to your console. The actual error that occurred during execution of your ajax call is the passed in to the error callback as the 3rd argument.
To see it, you should do something like:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
That will get you closer to the real problem.
UPDATE:
Please show the output from your php script. It may be that it is not returning valid json. As noted in the php docs ( http://php.net/manual/en/function.json-encode.php ), [json_encode] only works with UTF-8 encoded data.
You might also check in to json_last_error ( http://php.net/manual/en/function.json-last-error.php ) to see if the encoding failed for some reason.
UPDATE 3:
It seems like your problem may be the path to the php script.
try it with:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php", // <-- notice the leading slash!!!
//dataType: "json",
success:function(data){
//results(data);
console.log(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
or, putting it all back together if the above logs the correct json output to the console...
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
I'm trying to implement the Jquery .ajax method to simplify the ajax in my website.
Here is the function I'm working with:
function autoComplete(q, succ)
{
$.ajax({type:"GET",
url: "search.php",
data: "q="+q,
success: succ
});
}
$('input#auto_results').live('keyup', function() {
var text = $('input#auto_results').val();
autoComplete(text,
function(data)
{
alert(data);
});
});
The response on the PHP page is simply:
echo "response";
So I figure that it should alert the response when the function is called, on 'keyup'.
Sadly, nothing occurs. I must be doing something wrong, I am just not sure what it is.
is "keyup" event firing?
do following.
$('input#auto_results').live('keyup', function() {
var text = $('input#auto_results').val();
alert("Keyup event is firing");
autoComplete(text,
function(data)
{
alert(data);
});
});
if event is firing. then see firebug console tab
or put error function callback on your code:
function autoComplete(q, succ)
{
$.ajax({type:"GET",
url: "search.php",
data: "q="+q,
error:function(request, textStatus, err){
alert(request.statusText);
},
success: succ
});
}
you may get near to error.
I have a PHP script that breaks if a variable is not populated and it isn't added to the database, but jQuery handles this as a success and I get this error:
TypeError: Result of expression 'data' [null] is not an object.
Here's the jQuery script:
$.ajax({
type: "POST",
url: "/clase/do-add",
data: $("#adauga").serialize(),
dataType: "json",
error: function (xhr, textStatus, errorThrown) {
alert('Try again.');
},
success: function(data) {
var dlHTML = '<dl id="' + data.id + '"> [too long] </dl>';
$('form#adauga').after(dlHTML);
$('#main dl:first').hide().fadeIn();
adaugaClasaSubmit.removeAttr('disabled');
adaugaClasa.removeAttr('readonly');
adaugaClasa.val("").focus();
}
});
The problem is that jQuery's concept of "error" is an HTTP error, not an error that you have noted yourself. If the HTTP response code is <400, jQuery will use your success callback. Your options are (a) to use PHP to give an error in your HTTP response
header("HTTP/1.0 500 Internal Server Error");
or (b) to do your error handling in the success handler:
success: function(data) {
if (!data) {
// do your error code here
} else {
// do your success code here
}
}
I prefer the first option, with HTTP response codes, to allow your code to make the best logical sense to a future editor (which may be you!).
success: function(data) {
if(data!=null){
...
}
}
try this