AJAX function on permanent error - php

Something is wrong with this AJAX function but I do not see what.
AJAX
$('.review').click(function() {
var idatas = $(this).attr('rel');
var idata = 'idata=' + idatas;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?review',
data: idata,
beforeSend: function() {
$(this).addClass('ractive');
},
dataType:'json',
success: function(data) {
$('#dbody').html(data.ioutput);
$('.cright').height($('#dropout').height());
$('#dropout').addClass('dropopen');
},
error: function(data) {
$('#dbody').html('arse biscuity');
$('.cright').height($('#dropout').height());
$('#dropout').addClass('dropopen');
}
});
PHP
<?php
$rid = $_POST['idata'];
$ireviews = get_posts('post_type=reviews&p='.$rid.'&numberposts=-1');
foreach ($ireviews as $ireview) :
setup_postdata($post);
$ioutput = '<div class="iavatar"></div>
<div class="ititle">'.get_the_title($ireview).'<br />
<div class="iauthor">'.get_the_author($ireview).'</div></div>
<div class="icontent">'.get_the_content($ireview).'</div>';
endforeach;
echo json_encode(array('ioutput'=> $ioutput));
?>
According to Firebug the response is this
{"ioutput":"<div class=\"iavatar\"><\/div>\n<div class=\"ititle\">What a lovely course<br \/>\n<div class=\"iauthor\">pm master<\/div><\/div>\n<div class=\"icontent\">This intimate layout, with its undulating and springy fairways that zigzag in amongst the woodland setting, calls for accurate driving and precision shot-making into the well-bunkered greens; another classic Colt trademark. Position, not power, is the name of the game here.<\/div>"}
But it is going to error function and not putting the content in #dbody
Any ideas?

Try using the $.ajaxSetup() to get the correct error like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
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);
}
}
});
});
In case of any error in the Ajax call, you will get proper alert.

Related

Ajax Error status giving error 0 while I using Laravel API in Localhost

I'm doing this totally in localhost. And Creating Laravel API and called them via AJAX. This is my AJAX code:
function checkLogin() {
var objectData = {
caller_id: document.getElementById('caller_id').value,
password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
console.log(objectDataString);
$.ajax({
type: "POST",
url: "http://localhost:8000/api/caller/check",
dataType: "json",
data: objectDataString,
success: function (data) {
console.log(data);
},
error: function (jqXHR, exception) {
var msg = '';
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;
}
console.log(msg);
}
});
}
And CORS job which is also caused for this Error. But I figured it out. Here is the code in Laravel Framework.
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
}
This is located at Middleware folder. I cleared the cache as well. Does anyone know how this is caused?

Ajax post not working on localhost using xampp

I'm using XAMPP as my server. I am able to make queries using PHP and I have tried other Ajax code and it does work but when I try posting to a different php file using ajax I keep getting the error returning 0 or null.
if (!e.isDefaultPrevented()) {
e.preventDefault();
$.ajax({
type: "POST",
url: "https://localhost/validate.php",
data: {'email': $('#email').val(), 'username': $('#username').val()},
dataType: "json",
success : function(text){
$('#signup_form').unbind('submit').submit();
},
error: function(jqXHR, exception) {
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);
}
}
});
}
This is my error "Not connect. Verify Network." I have tried passing the following urls and they all give me a 404 file not found error:
validate.php, ../validate.php, localhost/validate.php, MusicApp/validate, localhost/MusicApp/validate, and etc. The only things that seem to work is https://localhost/MusicApp/validate.php, https://localhost:63342/localhost/MusicApp/validate.php but I keep getting the Not connect. Verify Network error.
I also can't do a post within a form without getting a 404 page not found error so I believe it might have something to do with the path?

Ajax zend framework 2

I'm using ajax in my ZF2 Application and I have a problem with Ajax. My code is this:
Ajax:
$('.checkbox-published').on('click', function () {
var id_entity = "";
var ischecked = $(this).is(":checked");
var path = $(this).attr('url');
id_entity = $(this).val();
alert(path);
$.ajax({
url: path,
type: 'POST',
datatype: 'json',
data: {'id_entity': $(this).val(), 'ischecked': ischecked},
success: function (data, status) {
alert("Succes + info: " + data.message);
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (xhr.status == 404) {
alert('Requested page not found. [404]');
} else if (xhr.status == 500) {
alert('Server Error [500].');
} else if (errorThrown === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (errorThrown === 'timeout') {
alert('Time out error.');
} else if (errorThrown === 'abort') {
alert('Ajax request aborted.');
} else {
alert('There was some error. Try again.');
}
},
});
});
And my controller:
public function publishAjaxAction()
{
$result = array('status' => 'error', 'message' => 'There was some error. Try again.');
$request = $this->getRequest();
if ($request->isXmlHttpRequest()) {
$locale = $this->locale();
$data['id_entity'] = $request->getPost('id_entity');
$data['ischecked'] = $request->getPost('ischecked');
$result['message'] = "Animo que funciona!" . $data['id_entity'] . "->" . $data['ischecked'];
$dataToTable = array(
'id' => $data['id_entity'],
'locale' => $locale,
'ischecked' => $data['ischecked'],
);
$this->getCenterTable()->publishEntity($dataToTable);
}
return new JsonModel($result);
}
It don't retunrs any data. If it works it will return a message with there was some error. But what I have in my response is undefined. I don't know how to solve it.
Any help would be perfect.

Ajax success function cant returns value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am using jQuery ajax function to get database values code and subcode.Whenever I get the code and subcode I have to get the name stored in another table corresponding to code and subcode.
First function i am using is
function loadSecretaries()
{
var items = "";
$.getJSON("Tac_members_GetTacSecretaries.php", function(data) {
$.each(data, function(index, item) {
var name = getSecretariesName(item.ECODE, item.ECODE_S);
items += "<option value='" + item.ECODE + "'>" + item.ECODE_S + </option>";
});
$("#select_reviewer_secretary").html(items);
});
}
The second function is
function getSecretariesName(code, subcode)
{
var items = "";
$.ajax({
async: false,
url: '../PhpProject1/Tac_Members_GetReviewerNames.php',
dataType: 'json',
type: 'POST',
data: {"code": code, "subcode": subcode},
success: function(response) {
alert(response.ename) ;
var name =response.ename;
//here i want to return ename to first function
},
error: function(x, e) {
if (x.status === 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status === 404) {
alert('Requested URL not found.');
} else if (x.status === 500) {
alert('Internel Server Error - Please try after relogin to the application');
} else if (e === 'parsererror') {
alert('Parsing JSON Request failed.');
} else if (e === 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
return name;
}
I am getting undefined when alert 'name' in first function. How to solve this. Thanks in advance.
try this
function getSecretariesName(code, subcode)
{
var items = "";
var name = "";
$.ajax({
async: false,
url: '../PhpProject1/Tac_Members_GetReviewerNames.php',
dataType: 'json',
type: 'POST',
data: {"code": code, "subcode": subcode},
success: function(response) {
alert(response.ename) ;
name = response.ename;
//here i want to return ename to first function
},
error: function(x, e) {
if (x.status === 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status === 404) {
alert('Requested URL not found.');
} else if (x.status === 500) {
alert('Internel Server Error - Please try after relogin to the application');
} else if (e === 'parsererror') {
alert('Parsing JSON Request failed.');
} else if (e === 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
return name;
}

Get json data from php and use it in jquery

It is my first time using JSON. I am trying to get JSON data from a php script using ajax.But i am getting this error "Error.Parsing JSON Request failed" "undefined".Help me this is my php script test.php
$data='{
"one": "One",
"two": "Two",
"three": "Three"
}';
header('Content-type: application/json');
echo json_encode($data);
and here i am getting the data getdata.php
var sURL = 'http://www.example.com/test.php';
$.ajax({
type: "GET",
url:sURL,
dataType:"jsonp",
crossDomain:true,
data: {transid:trans_id , bookingdate: dateVal, bookingtime: timeVal, People: peopleVal,affiliateid: affiliate },
async: false,
contentType:"application/json; charset=utf-8",
success: function (data){
var result = JSON.parse(data);
alert(result);
},
error: function (x, e) {
if (x.status == 0) {
alert(x.response);
alert(x + " " + e);
alert('You are offline!!\n Please Check Your Network.');
}
else if (x.status == 404) {
alert('Requested URL not found.');
}
else if (x.status == 500) {
alert('Internel Server Error.');
}
else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.' + e.statusText);
alert(x.response);
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
This is my first question so excuse any mistakes
As you are using jsonp, add callback function as below
var sURL = 'http://www.example.com/test.php';
$.ajax({
type: "GET",
url:sURL,
dataType:"jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
crossDomain:true,
data: {transid:trans_id , bookingdate: dateVal, bookingtime: timeVal, People: peopleVal,affiliateid: affiliate },
async: false,
contentType:"application/json; charset=utf-8",
success: function (data){
var result = JSON.parse(data);
alert(result);
},
error: function (x, e) {
if (x.status == 0) {
alert(x.response);
alert(x + " " + e);
alert('You are offline!!\n Please Check Your Network.');
}
else if (x.status == 404) {
alert('Requested URL not found.');
}
else if (x.status == 500) {
alert('Internel Server Error.');
}
else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.' + e.statusText);
alert(x.response);
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
function jsonpcallback(rtndata) {
alert(rtndata.one);
}
In PHP make $data as array and then use json_encode() with return callback.
$data=array(
"one"=>"One",
"two"=>"Two",
"three"=>"Three"
);
header('Content-type: application/json');
echo $_GET['callback']. '('. json_encode($data) . ')';
Change your
dataType:"jsonp",
to
dataType:"json",

Categories