I have the following Script;
function FetchNews(user_id,api_token){
$.ajax({
type:'GET',
url: 'http://192.168.**.**/mysite/public/index.php/api/v1/news/'+user_id,
headers: {'X-Auth-Token' : api_token},
dataType:'json',
success: function(data)
{
var comment='';
for(var i = 0; i < data.length; i++) {
comment = data[i];
$('headlines').append('<li><h2>'+ comment.news_headline +'</h2><p><strong>'+ comment.news_content +'</strong></p><p class="ui-li-aside"><strong>'+ comment.created_at +'</strong></p></li>');
}
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert("Not connected. Verify Network.");//show error
} else if (jqXHR.status == 404) {
alert("Requested page not found. [404]");//show error
} else if (jqXHR.status == 500) {
alert("Internal Server Error [500].");//show error
} else if (exception === 'parsererror') {
alert("Requested JSON parse failed.");//show error
} else if (exception === 'timeout') {
alert("Time out error.");//show error
} else if (exception === 'abort') {
alert( "Ajax request aborted.");//show error
} else {
alert("Uncaught Error.\n" + jqXHR.responseText);//show error
}
}
});
}
I call this FetchNews function as the page loads, It is at the bottom of the page close to the </body> tag. The function get called but no responds from server at all, and when I checked LogCat, the requestState(status) get stuck at 1
Change this...
dataType:'json',
To this...
dataType:'jsonp',
dataType: jsonp is for cross-domain requests/different domain than the origin. dataType:json is for same domain-same origin request.
But also...this seems wrong..
$('headlines').append('<li><h2>'+ comment.news_headline +'</h2><p><strong>'+ comment.news_content +'</strong></p><p class="ui-li-aside"><strong>'+ comment.created_at +'</strong></p></li>');
Should maybe be
$('.headlines') or $('#headlines')
Related
I'm having a WordPress template file from where I'm getting the user_id and response_id and passing those to javascript written in same file at bottom. All of the ids are passing properly but only for the url I'm getting error. How can I solve this issue? When I am testing it on local environment it works fine but when I upload it on live server Uncaught ReferenceError: url is not defined and here is the javascript code:
<script>
$(document).ready(function() {
$('#vote-' + <?php echo $response->id; ?>).on('click', function() {
var response_id = "<?php echo $response->id; ?>";
var user_id = "<?php echo get_current_user_id(); ?>";
$.ajax({
url: "<?php echo esc_url(get_stylesheet_directory_uri() . '/Votes.php'); ?>",
method: "post",
data: {
response_id: response_id,
user_id: user_id
},
beforeSend: function() {
},
success: function(response) {
alert('Thanks for your response!');
//location.reload(true);
},
error: function(jqXHR, status, err) {
var msg = '';
console.log(url);
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
alert('Please try again to cast your vote');
// window.location.href = '/plan';
// $("#claimajaxresponse1").html(jqXHR.status);
console.log(jqXHR.status);
return false;
}
});
});
});
</script>
the url you are consoling is not a variable, remove it or define first.
If you comment out or remove the following line of code, this specific issue will be solved:
console.log(url)
I'm absolutely new to asp.net and I want to create infinite scrolling using jQuery Ajax and ASP.NET MVC. So here;s what I got so far
<div id="container"></div>
<div id="progress" style="display:none">
<h4>Loading...</h4>
<div class="col-md-12 panel panel-default"></div>
</div>
<script type="text/javascript">
var pageSize = 10;
var pageIndex = 0;
$(document).ready(function () {
GetData();
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetData();
}
});
});
function GetData() {
$.ajax({
type: 'GET',
url: 'http://localhost:64949/api/values/delfi',
dataType: 'json',
success: function(data) {
alert("yra");
//if (data != null) {
// for (var i = 0; i < data.length; i++) {
// $("#container").append("<h2>" +
// data[i].CompanyName + "</h2>");
// }
// pageIndex++;
//}
},
beforeSend: function() {
$("#progress").show();
},
complete: function() {
$("#progress").hide();
},
error: function(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.' + jqXHR.responseText;
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]' + jqXHR.responseText;
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
});
}
</script>
I impemented scroll listener and every time I reach end of page I make new request to my api which simply returns json data. Here's what it returns
[{"Index":1,"List":{"Img":"http://g1.dcdn.lt/images/pix/jonas-udris-72559208.jpg","Title":"J. Udris. Scenarijai dėl Šilutės balsavimo reikalų","Description":"Policijai pradėjo ikiteisminį tyrimą dėl galimo rinkėjų papirkimo Šilutės rajone partijos „Tvarka ir teisingumas naudai. Ketvirtadienį policija pranešė sulaikiusi septynis asmenis, antradienį jų namuose atliktos kratos. Vienas asmuo suimtas 10 parų."}}]
However every time my ajax jumps to error function and jqXHR.status is always 0. I also try to pass url like this url: localhost:64949/api/values/delfi and still get the same response. What's wrong with my code?
You should not hardcode the URL.
If you use a Controller, you could go for:
url: '#Url.Action("Action", "Controller")',
For linking to your api, you should look at Attribute Routing
A quick fix could be:
url: '/api/values/delfi',
Edit: #lmad that is indeed no answer to ops question im sorry for that. Status code 0 means the requested url is not reachable, so what i would do is to edit the url with the code above!
I've been trying to use AJAX to send across a variable from a JS file and trigger a PHP file in Wordpress. The function connects to the PHP file however the variable it sends across stores the value "0" . I've tried many solutions, but I can't quite nail down this problem. The JS code is below:
function data_transfer(){
alert(calc_price);
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
action: 'data_sender',
data:
({result: calc_price}),
dataType: 'json',
cache: false,
success:function(calc_price){
alert(calc_price);
},
error: function(jqXHR,textStatus,errorThrown, exception){
alert('error');
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
//alert(errorThrown);
//alert(textStatus);
}
});
}
The value calc_price is calculated prior in an if statement, but the value shown in the alert in the success function is "0".
The PHP and Wordpress hooks are show below:
add_action('wp_ajax_datasender', 'datasender_callback');
add_action('wp_ajax_nopriv_datasender', 'datasender_callback');
function datasender_callback() {
alert("PHP function successful");
}
Any ideas on how to solve this problem would be great. Thanks in advance, Kate.
alert is JavaScript, try using echo, as in
echo json_encode($_POST['result']);
also action needs to be part of your data parameter
data:({result: calc_price, action: 'data_sender'}),
If you receive 0 as a response with Wordpress, most of the time it means "error", null or something like that.
Try
add_action('wp_ajax_datasender', 'datasender_callback');
add_action('wp_ajax_nopriv_datasender', 'datasender_callback');
function datasender_callback() {
wp_send_json( "PHP function successful" );
wp_die();
}
But I think you should go over a tutorial like this:
https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/
In Wordpress there are a couple of things that make the AJAX call easier, and helps you do it correctly. (E.g. enqueuing and localizing the script.)
I am bad in writting code but still i given my best of write it, Here i am trying to catch an http exception on my html page. So when ever an exception is found i just want to reload/refresh the page.
Please excuse me if this has solved earlier and provide me the right procedure
var get_URL= window.content.location.href;
//console.log(get_URL);
jQuery.ajax({
type: "POST",
url: get_URL,
//I doubt is this right way to call the get_URL variable??
success: function(jqXHR, exception){
alert("Exception Not Found");
},
// Are my Parameters (jqXHR, exception) correct??
error: function(jqXHR, exception) {
alert("Exception Found");
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
location.reload(true);
}
});
Any help will be highly Appreciated.
I want to use javascript / jquery to determine if an xml file exists.
I don't need to process it; I just need to know whether it's available or not,but I can't seem to find a simple check.
Here is what I've tried:
jQuery.noConflict();
jQuery(document).ready(function(){
var photo = '223';
var exists = false;
jQuery.load('/'+photo+'.xml', function (response, status, req) {
if (status == "success") {
exists = true;
}
});
});
Assuming you are talking about an xml file on the server, you could do a ajax request and then write a custom error handler to check the error response message. You'll need to know what the exact error message code is for a missing file (usually 404). You can use Firebug Console to check what the exact error message and code is.
$.ajax({
type: "GET",
url: "text.xml",
dataType: "xml",
success: function(xml) {
alert("great success");
},
error: function(xhr, status, error) {
if(xhr.status == 404)
{
alert("xml file not found");
} else {
//some other error occured, statusText will give you the error message
alert("error: " + xhr.statusText);
}
} //end error
}); //close $.ajax(
Your question isn't clear to me. If I understand, you want to verify whether a file (the XML) is present or not in the HTTP server.
That's correct? If so, you can just do:
$.get('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
}
});
EDITED: As pointed by #lzyy on comments, .get() only calls the callback upon success. However, I'd stick to the .load() using $(document) as selector. See:
$(document).load('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
} else if (status == 'error') {
alert('doesnt exist');
}
});