How can jQuery .load fail? - php

I am using a simple ajax loader to get content on wordpress.
$("#page_preview").load("ajaxloader/", function(response, status, xhr) {
if (status == "error") {
alert("Sorry but there was an error");
}
else
{
$('#page_preview').fadeIn(300);
}
});
return;
When I load a specific post that has a google map embedded, obviously something goes wrong BUT instead of going inside the if statement, the firebug shows that it goes beyond this code. Neither if or else hit.
Using the eclipse debugger I found that the page load successfully, but when it returns the data to the .load() method, the last breaks.
Any ideas on what might going on?

How
<script>
// as of jQuery 1.5.x ++
var pagePreview = $("#page_preview");
$.get("ajaxloader/").success(
function(response, status, jqXhr) {
alert("Success!");
pagePreview.empty();
pagePreview.append(response);
// i feel you need to parse the response for the google map div, and perform another $.get() of the google url?
}).error(function(response, status, jqXhr) {
alert("These are not the droids you are looking for. move along.");
}).complete(function(response, status, jqXhr) {
alert("Complete!");
});
</script>
#Why
jQuery.load() will get you on the documentation. .load is equivalent to this
It is roughly equivalent to $.get(url, data, success) except that it
is a method rather than global function and it has an implicit
callback function. When a successful response is detected (i.e. when
textStatus is "success" or "notmodified"), .load() sets the HTML
contents of the matched element to the returned data.
You need to register in $.ajax( complete:function(responseText, textStatus, XMLHttpRequest)){}); and check the textStatus value. if ok, then load the data into the destination $('selector') yourself. Or fix the .load() by watching your network xmlHttpRequests in chrome (ctrl + shift +j) or some network tab in firebug and debug the issue with your 'url' value in $('selector').load( 'url', function(response, status, xhr){})

A simple way to debug this is to look at the XHR requests with the firebug console tab. There might be a problem with the request URL and you might not get any data back, or maybe you get an error or something. With firebug you could easily see what the server returns.
Since .load only load on success, you could add a
console.debug("In .load function");
at the begging of the function. Again, checking with firebug you could find out if the .load callback is actually fired.

use $.ajax function
eg
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//when Successfully executed
},
error: function(){
//When Error Fires
}
});

Related

$.ajax not a function in yii

I have the below function that I used in two different pages and worked perfectly in both cases. Suddenly my pages stopped updating and I got the error $.ajax not a function.
function update_report(data) {
var request = $.ajax({
url: "report?poids="+data,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#yw2").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
req ="a";
}
I then changed the $ to jQuery. Then it started sending AJAX requests but it didnt get the relative URL. Like I was generating the request from a page like /index.php/link1 and my code was sending request to /index.php/report rather then /index.php/link1/report
So, then I changed my url: to "link1/report=?"+data then it started sending request to the right page but couldnt update the response as it didnt find the div #id. Got error
TypeError: $(...) is null
What can cause all this issue and how to fix this? And why $.ajax suddenly stopped working, though I didnt make any changes?
JQuery can be not available by $.ajax(). Check if jQuery.ajax() is available or you included jquery twice.
You should not require jquery manually. The best way to include jquery is using Yii::app()->clientScript->registerCoreScript('jquery'). Path for library is set in config/main.php.

Sending and receiving AJAX requests with jQuery and PHP

I'm trying to send an AJAX request to a page to interpret some data, and if it complies with what i'm looking for, send another AJAX request back. Right now I can see the first request is being made, but I'm not getting one back
//message.php
<head>
<script>
function org_name(str){
alert(str); //this alert appears, so I know the data is being received by this function
$.get("common_functions.php", { group_name: str} );
}
</script>
</head>
Then, on common_functions.php I have a similar request back, however, I'm not sure exactly what the issue is. The alert box doesn't even appear so I'm confused as to why the console would say the request was sent
//common_functions.php
if(isset($_GET['group_name'])){
?>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
alert('common_functions'); //this does not appear
$.get("message.php", { name: "test"} );
</script>
<?
}
When I open up the javascript console in chrome I see the request sent form message to common_functions, but apparently the request on common_functions isn't sending one back
//text from javascript console
Request URL:http://localhost/message/common_functions.php?group_name=test
Request Method:GET
Status Code:200 OK
Does anyone see something obvious that I'm doing wrong or missing? If it makes a difference, common_functions is included in message.php because I do use some other functions from that page for my php.
You have to do something with your data. Right now, you're making an AJAX call, and doing nothing with your data.
So something like the following would work:
$.ajax({
url: "common_functions.php",
data: { group_name: str },
type: "GET",
success: function (data) {
$(data).appendTo("head");
}
});
Use $.ajax if you want control over execution states:
$.ajax({
type: "POST",
url: "common_functions.php",
data: { name: "test"},
success: function(r)
{
// user r as output
},
error: function(xhr, ajaxOptions, thrownError)
{
// error report
alert(xhr.responseText);
}
});
In this case you can see if execution was successful or if error occurred.
Also you can use firebug add-on for firefox or chrome to detect if response was sent. There is also an excellent tool called Fidler, which can give you much better overview over request/response states.
Here is an excellent tutorial for ajax debugging.
$.get will strip out <script> tags. You can use another jQuery AJAX method load() that won't, or use $.getScript. If you need content and script you can do both by making an ajax request for the content, and in the success callback of that ajax, call for the script with $.getScript
load() replaces all the content in the specified selector
$('#myDiv').load('common_functions.php', { name: "test"})
Will take all the content of the php output and replace all the contents of #myDiv but will also run the scripts
you may use a library that does that for you automatically, using http://phery-php-ajax.net
in your case, it would be
function messages($data){
$r = new PheryResponse;
// return your messages
return $r->json($messages);
}
function common($data){
$r = new PheryResponse;
switch ($data['group_name']){
case 'messages':
$r
->include_script(array(
'jquery' => 'http://code.jquery.com/jquery-1.8.2.js'
))
->phery_remote('messages'); // load your messages
break;
}
return $r;
}
Phery::instance()->set(array(
'common' => 'common',
'messages' => 'messages'
))->process();
on your page load
$(function(){
phery.remote('common', {'group_name': 'messages'});
});
you don't have to do anything else. btw, if you are including jQuery AFTER you are using $.get(), it won't work, obviously

Ajax request multiple data info

I'm going crazy over this script, i'm trying to het this working by when some one click on a button then with ajax fetch data from another URL then fill form inputs with the fetched data can any one help please
my code look like this:
$(document).ready(function()
{
$("#getmetaData").click(function(){
var element = $(this);
var url = $("#url").val();
var dataString = 'url='+ url ;
//alert(dataString);
if(url=='http://')
{
alert("Please Enter URL to fetch Meta Data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loader.gif" >');
$.ajax({
type: "POST",
url: "fetch-metadata.php",
data: dataString,
cache: false,
success: function(data){
$("#title").val(data);
$("#description").val(data);
$("#keywords").val(data);
$("#flash").hide();
}
});
}
return false;});});
If you see no error, which I am guessing is the case, it means your request is failing. Since you have no error function, when your request fails, your jQuery code will do nothing.
Add something like this to your $.ajax object argument:
error: function(jqXHR, textStatus, errorThrown) {
// now you can set a breakpoint or log textstatus/errorThrown
},
As per HackedByChinese's answer I would add an error callback function.
Also, in your success callback function you are simply using the 'data' variable without doing anything with it. Depending on the format of the response from 'fetch-metadata.php' I think you'll need to do something first. It's either XML in which case you'll need to parse it. If its json you can use object dot notation to reference it's properties.
Lastly, I'd use something like Firebug to look at the request and response for this Ajax request to make sure it's being processed and not returning a 404 or 500. Assuming its returning a valid response, using Firebug you can look at the response to see the raw data that is being returned to your js.
Hope this helps

jQuery Mobile -> Load content from external server

I am working on a seemingly basic mobile app (first). But I want to enable the application to request information from our 'head' server. To make sure it has the latest information.
I'm currently running a jQuery script like this.
$.ajax({
url: 'http://www.domain.com/list.php',
dataType: 'json',
crossDomain: true,
success: function(data) {
// Remove all content first
$(contentId +' li').remove();
// Load Data
$.each(data.items, function(index, list){
$(contentId).append('<li><a href="details.html?id=' + list.homeId + '" >' + list.name + '</a></li>\n');
});
// Reload View
$(contentId).listview('refresh');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error: '+ jqXHR + textStatus + errorThrown);
}
});
And actually on that LIST.PHP file, it does return a JSON string. But what I did for security was by adding this as a header
header("Access-Control-Allow-Origin: *");
Or I could change * to a domain/url to add better security. But if I don't add that header() code in their, my javascript breaks and won't run properly.
I guess what i'm truly wondering is, am I doing this properly? or is there a better way to do this? I have tried JSONP, but I can't seem to get that to work for cross domain.
Is my solution sound? or total crap? Any thoughts or direction would be greatly appreciated!
I think you should look into JSONP. It's not that hard. On the client side, jQuery already handles it out of the box, just append a ?callback=? to the URL. On the server, instead of just responding with JSON, e.g.:
{
"foo": "bar"
}
Look for the query parameter callback, and if it exists, wrap your JSON output in a function call with the name being the value of the callback parameter, so, for callback=foo:
foo({
"foo": "bar"
})
When responding with JSONP, send Content-Type: text/javascript. This should work without setting Access-Control-Allow-Origin or anything like that.

Why isn't this Jquery Ajax working in Opera and Safari?

This code works in FF, Chrome, IE6/8 but not in Safari and Opera.
Any ideas why?
Here is the code:
var name = $('#esm').val();
var email = $('#nam').val();
var message = $('#med').val();
var ad_id = $('#i_d').val();
var data_string = 'esm='+ name + '&nam=' + email + '&med=' + message + '&i_d=' + ad_id;
$.ajax({
type: "POST",
url: "/my_php_file.php",
data: data_string,
success: function(data) {
$('#tip_loader').hide();
if(data==1){alert('success'); }
else {alert('error'); }
}//end success function
}) //end ajax call
I have located the error to exactly the "Ajax" call, because when I put an alertbox just before the $.ajax the alert shows up correctly.
However, if I put the alertbox in the success function, nothing shows up, no alert.
This only happens in Opera and Safari...
EDIT:
FYI: I include this javascript file into a php file, and I also include the jquery.js file into the php file. So this is all in an external file.
EDIT:
/main.php
/bin/jquery.js
/bin/tip.js
/bin/tip.php
I include the above js files into main.php, and the form action in main.php is set to /bin/tip.php
And the path to the ajax url is /bin/tip.php instead of my_php_file.php
In Opera, by default Allow File XMLHttpRequest is false. So you need to change the settings. Open Opera browser, type about:config. It will take you to the Preference screen. Go to User Prefs folder, you can see a settings Allow File XMLHttpRequest. Check that and then Save. It should work.
Opera has a debugging tool built in called Dragonfly. Go to the Tools menu -> Advanced ->Opera Dragonfly
If you don't have the File menu bar, click Menu -> Page -> Developer Tools -> Open Opera Dragonfly
Once you have it open (open it on the page that you're working on), click the Scripts tab (it'll probably ask you to refresh the page, do that) and drop down to your external js file.
Once you've found your code, you can set a breakpoint on the $.ajax() line by clicking on the line number on the left side. Now, trigger your code and you'll see that it will break on that JavaScript line. You can then use the inspection tab (bottom, middle) to ensure that all of your variables are set correctly. You can also step through and debug the JavaScript.
The other thing you'll want to do is add an error function like so:
$.ajax({
type: "POST",
url: "/my_php_file.php",
data: data_string,
success: function(data) {
$('#tip_loader').hide();
if (data == 1) { alert('success'); }
else { alert('error'); }
}, //end success function
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
}
}); //end ajax call
See if that gives you any more information.
Also, check the error console as #Mufasa suggested. It can be found under the Error Console tab in Dragonfly.
There isn't really a way to tell. You didn't post the php file. Without knowing the output, we can't determine how the browser will respond.
Other tips though, #1 you are not using encodeURIComponent for any of the values being passed it. Its much more simple to get jQuery to do it for you,
instead of data: data_string, you should have
data: { esm: name, nam: email, med: message, "i_d": ad_id }
jQuery will create the query string for you and correctly.

Categories