I am working with .load function in jQuery to load a html page into a div with ajax but I have problem since server always doesn't send a html, sometimes it send a json and I want to get that json with .load.
I thought it would be a response in callback function in .load but it return undefined and just put that json into the div so how can I get that json with .load.
The server send this json :
{ok : false}
Here is my jQuery code:
$( "#div").load( "url", function( response, status, xhr ) {
////how can I get the false result here response.ok return nothing!!!
console.log(response.ok);
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#div" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
i think you have to do something like this:
$("#div").load( "url", function( response, status, xhr ) {
var responseAsObject = $.parseJSON(response);
console.log(responseAsObject.ok);
});
Using response to replace #div html content :
$("#div").load("url", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success") {
var responseAsObject = $.parseJSON(response);
$(this).html( responseAsObject.response );
}
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
Related
I'm trying to read a remote file ; I'm using the example on the jquery.get() documentation page :
var jqxhr = $.get( 'http://stackoverflow.com/feeds/question/10943544', function() {
alert( 'success' );
})
.done(function() {
alert( 'second success' );
})
.fail(function(jqXHR, textStatus, errorThrown) {
// alert( 'error' );
console.log('Error: (' + errorThrown + ')');
})
.always(function() {
alert( 'finished' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But it only triggers "fail" and "always" and I'd like to understand why ; My question is : How can I obtain a readable error? Currently, the console.log("Error: (" + errorThrown + ')'); only yields Error: ().
Bonus question: Why does it fail? How can I read a remote (RSS) file using JS/JQuery?
Your problem is one of the Same Origin Policy, which is present on most AJAX requests, and put in place as a security measure. If you look at jqXHR() you can see that readyState is 0, indicating this. Note that readyState will always be 0 when the request has failed, be it for policy restriction or a malformed request. The error message is blank because the restrictions are preventing the error message itself from triggering.
var jqxhr = $.get("http://stackoverflow.com/feeds/question/10943544", function(res) {
alert("success");
})
.done(function() {
alert("second success");
})
.fail(function(jqXHR, textStatus, errorThrown) {
// alert( "error" );
console.log("Error: (" + errorThrown + ')');
})
.always(function(jqXHR) {
console.log(jqXHR);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To get around this, there are a number of plugins, which are listed in this answer. It also states:
The best way to overcome this problem, is by creating your own proxy in the back-end, so that your proxy will point to the services in other domains, because in the back-end not exists the same origin policy restriction.
However, assuming you can't do that, the easiest way is to make use of CORS Anywhere proxy, as is shown in the following snippet (note that the result takes a while to come through):
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://stackoverflow.com/feeds/question/10943544',
function(response) {
console.log("> ", response);
$("#viewer").html(response);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this helps! :)
This is my code at www.domain-a.de/external.search.js. I call it from www.domain-b.de/test.php:
(function ($) {
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
var frm = $('#embedded_search form');
// click on submit button
frm.submit(function (ev) {
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
});
})(jQuery);
After running this code I don't get any message in console. What is wrong with that code?
frm.submit(function (ev) {
ev.preventDefault();
.....rest of code.
Your code is not calling the submit handler on the item, it is simply binding it. You should do the frm.submit(function binding outside of your $.getJSON callback; then inside the callback add
frm.submit()
Which triggers the event.
Also, when the submit happens, your actions will take place but then the form will submit to the back end as normal, causing a page reload.
After the line
frm.submit(function (ev) {
Add
ev.preventDefault();
So your overall code should be
(function ($) {
var frm = $('#embedded_search form');
var myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
frm.submit(function (ev) {
ev.preventDefault();
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
// click on submit button
frm.submit();
});
})(jQuery);
I am performing an ajax request cross domain. I have been trying to use functions that return the headers in an array only to find that I get Undefined Index even though I can return their values in my ajax request and print them the screen.
I have found some posts on SO that said I should be using $_SERVER globals. So I switched to that method only to get the same results.
Here is my jQuery:
setTimeout(function() {
jQuery.ajax({
url: 'http://something.com',
type:"POST",
dataType:"json",
crossDomain:true,
contentType:"application/json",
data: jsonData,
processData:false,
cache:false,
beforeSend: function( xhr ) {
xhr.setRequestHeader("Authorization",api_key[index]);
xhr.setRequestHeader("Action","PUSH");
},
success: function(data) {
alert(data.action);
alert(data.platform + ' : ' + data.message + ' : ' + data.app_name );
if(data.message == 'success')
{
jQuery('#hollmanPNs_send_push div#hollmanPNs_progressbar' + index).progressbar("value",100);
//add message to the paragraph for app name
jQuery('#hollmanPNs_send_push p#hollmanPNs_paragraph' + index).append(': Complete');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert( 'We had an error: ' + textStatus + errorThrown );
}
}).fail(function() {
alert( 'We had a failed AJAX call.');
});//end ajax
}, index * 5000);//end timeout function
And here is what I am using for PHP:
if($_SERVER['HTTP_ACTION'] != '')
{
//Do Something
}
I have tried switching to:
xhr.setRequestHeader("X-Action","PUSH");
and
$_SERVER['HTTP_X_ACTION']
with the same results. Only I was not able to return them to my ajax request.
I am using PHP 5.3.3.
I am also using this function which I change depending on the different headers I am trying at the time:
header('Access-Control-Allow-Headers: Action, Authorization, Content-Type');
You'll want to get the headers a different way like so:
$headers = getallheaders();
if(array_key_exists('Action', $headers) && $headers['Action'] != '')
{
//Do Something
}
The question I am asking is a basic question because I am new in json and ajax.
so I have a json data of name , task , date and status I am getting data through ajax but it is not showing in on my page.
my ajax code is this:
$(document).ready(function(e) {
// Using the core $.ajax() method
$.ajax({
url: "getdata.php",
type: "GET",
dataType : "json",
success: function( json ) {
$( "<h1/>" ).text( json.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.task ).appendTo( "body" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
this is my json data:
[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
I don't know why It is not appending html data but it is showing complete alert.
I have added fiddle even if it is not working.
Fiddle
Ok, i see you actually getting results so i guess you do have a success. You do have a flaw though. You are trying to access properties directly, but your json is an array of objects and not an object.
You need to do a foreach itteration.
json.forEach(function (entry) {
$( "<h1/>" ).text( entry.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( entry.task ).appendTo( "body" );
});
Edit Your Json like
{
"jsontext":[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
}
and the ajax code should be as
$.ajax({
url: '/getdata.txt',
complete: function (data) {
if (data.responseText != "") {
var NewTxt = data.responseText;
NewTxt = NewTxt.replace(/\n/g, "");
NewTxt = NewTxt.replace(/\s/g, "");
obj = JSON.parse(NewTxt);
var NewStr = "";
for (var i = 0; i < obj.jsontext.length; i++) {
NewStr += obj.jsontext[i].name + "<br/>" + obj.jsontext[i].task + "<br/>" + obj.jsontext[i].date + "<br/>" + obj.jsontext[i].status + "<br/><br/>";
}
document.getElementById("demo").innerHTML = NewStr;
}
}
});
and the HTML as:
<div id="demo"></div>
I would like to load content of external url into a div using JQUERY, I found that I should use the next command:
function loadMyContent(url){
$("#result").load('registration.html');
}
Now I would like to check if the load was successful print alert message ("success") and if the action was fails from some reason alert ("fails").
how can I add the success and fails triggers to the function?
does the solution will cover also 404 errors?
Thanks alot
Shai
Try this
var page = $("#result");
$.get("registration.html").success(
function(response, status, jqXhr){
alert("Success!");
page.empty().append(response);
}).error(function (response, status, jqXhr){
alert("Error.");
}).complete(function (response, status, jqXhr){
alert("Complete!");
});
He tried for get method but i saw you need use load if you wan't use load method try this (tested):
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});