ASP.NET Ajax geting error with code 0 - javascript

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!

Related

WordPress Ajax Uncaught ReferenceError: url is not defined

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)

how to pass ajax response value to another page?

I'm trying to send an AJAX response to a PHP file. Based on the response I would like to redirect to another page. If the response is success I would like to redirect to a 'thank you' page along with the parameter data.
How can I pass this transactionId to another page?
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
if (response == "success") {
window.location.href = 'http://www.google.com';
}
});
});
});
change your php output from
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
to
if ($result->success)
{
echo json_encode(array('status'=>'success','id'=>$result->transaction->id));
}
else if ($result->transaction) {
echo json_encode(array('status'=>'error','code'=>$result->transaction->processorResponseCode, 'text'=> $result->transaction->processorResponseText)));
}
else
{
echo json_encode(array('status'=>'error','text'=>$result->errors->deepAll()));
}
and change your js to the following
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
var data= $.parseJSON(response);
if (data.status == "success") {
window.location.replace('http://www.google.com?id='+data.id)‌​;
}else{
alert('Operation Failed');
if(data.code){
console.log('response code: '+data.code);
}
console.log('response text: '+data.text);
}
});
});
});
looking at your php code - it never returns success, it will return success!: somthing so this condition if (response == "success") is never true
you could use
if(response.indexOf("success") == 0)
or change the response in the php file
You can send the response variables you'd like by incorporating them into a query on the redirect.
For instance if you wanted to pass on foo to your redirected php domain.com/bar.php:
var url = 'domain.com/bar.php?foo=' + foo
window.location.href = url;
And then on the PHP page, you can use this data:
$bits = parse_url($url);
parse_str($bits['query'], $query);
echo $query['foo']

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

Error on recursive method call

I need to fetch data from and external API. Since I have to make the call again and again to check the status until the status is TRUE, I have placed it in a recursive loop. I need to know what's wrong with my logic, because I'm unable to get the desired output. Does the response.status update itself or do i need to make another ajax like how I have done in the code
fetchFunct();
function fetchFunct(){
console.log("entered function");
$.ajax
({
type: "GET",
url: "/content/mosaic/multi/preview/status/"+testId ,
async: false,
dataType : "json",
success : function(response)
{
console.log(response);
if(response.status === false)
{
console.log("Processing details"); //show still in progress
$("#load").show();
$("#heading").hide();
$("#b1").hide();
$("#b2").hide();
$("#b3").hide();
$("#b4").hide();
$("#b5").hide();
}else
{
$("#load").hide();
console.log("Loading 1");
$("#b1").click(function(){
$("#ad22img").attr("src","http://" + response.images.android22);})
console.log("Loading 2");
$("#b2").click(function(){$("#ad4img").attr("src","http://" + response.images.android4);})
console.log("Loading 3");
$("#b3").click(function(){ $("#apm6img").attr("src","http://" + response.images.appmail6);})
console.log("Loading 4");
$("#b4").click(function(){ $("#blbimg").attr("src","http://" + response.images.blackberryhtml);})
console.log("Loading 5");
$("#b5").click(function(){$("#iphnimg").attr("src","http://" + response.images.iphone5s);})
is_loaded = true;
}
}
}).fail(function(data) { console.log("FAIL"); }).done(function(data) { console.log("coming out of ajax");
});
if(!is_loaded)
{
console.log("entered if");
delay=delay*2;
if(delay>60)
{delay=1;}
setTimeout(fetchFunct,delay*1000);
}
//console.log("if not entered");
}
You should call your function again inside the callback function.
if(response.status === false)
{
console.log("Processing details"); //show still in progress
$("#load").show();
$("#heading").hide();
$("#b1").hide();
$("#b2").hide();
$("#b3").hide();
$("#b4").hide();
$("#b5").hide();
//Try again
setTimeout(function(){
fetchFunct();
},1000);
}else
No need for any of the setTimeout logic beneath your AJAX call.

Ajax Request Does not Respond

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')

Categories