Get json data from php and use it in jquery - php

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",

Related

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;
}

How can I retry an ajax request on empty response

I would like to retry an ajax request when response data is an empty json object.
My ajax code is following.
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
$(this).ajax();//retry ajax request here, if data is empty
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
PHP
echo json_encode(array(
'type'=>$paymentType,
'btn'=>$this->PaymentBtn,
'usd' => round($this->finalUSDAmount,2),)
);
You can put your ajax request in a function and then call that function If the respons is empty.
Like this:
function yourCall(){
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
yourCall();
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
}
this setup will however keep trying the ajax call untill it gets a valid respons. This meaning that it will keep firing if the respons length == 0
Just Simply Do Following:
$.ajax({
url : 'index.php?r=funding/getPaymentButton',
type : 'POST',
data : {email:benfEmail,data:JSON.stringify(data),paymentType:method},
tryCount : 0,
retryLimit : 3,
success : function(json) {
//do something
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
//handle error
} else {
//handle error
}
}
});

How to return an error callback in php?

I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});

AJAX function on permanent error

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.

Categories