Error on xmlrpcresp Object - php

I'm working on a project that I write a Firefox addon to communicate with a service on my client server. My add send a POST request and then the server encounter an error with xmlrpcresp Object that is:
Error: xmlrpcresp Object
(
[val] => 0
[valtyp] =>
[errno] => 6
[errstr] => No data received from server.
[payload] =>
[hdrs] => Array
(
)
[_cookies] => Array
(
)
[content_type] => text/xml
[raw_data] =>
)
and my addon request (it intend to recieve json data from the server):
Request({
contentType: "application/x-www-form-urlencoded",
headers: {
"Keep-Alive": (model.get("interval1") || 30) - 10
},
content: content,
url: url,
onComplete: function(res){
var response = res || this.response;
logger.logFile("collect steps status " + helper.getStatusData(response.json))
if (response.status == "200"){
var json = response.json;
logger.object(json, "track download id");
if(json.results && json.results.status == "0")
callback(json);
else{
if(fallback) fallback(json);
}
}
else{
if(fallback) fallback(json);
}
}
}).post()
The client's IT team said that it might be a header error and this not always happen, just sometime.
Can my above request cause the error? Or, it's just some server side process's error?

"No data received from server" is not an error message that the browser gave you, it is the response from the xmlrpc library on the server. In other words, your add-on successfully sent a request to the server and received a response. In the response the server indicates that its RPC call failed. How could this be a client problem? It is quite obviously a problem with the server that the RPC call went to - instead of giving a response back it returned 200 OK without any data which is what the error message is saying.

Related

Don't get text back from HTTP fetch request with status 200

I'm new to react and try to send a request to my local apache server (run via xampp).
fetch('http://localhost:80', {
method: 'POST',
headers: {'Accept': 'text/*'}
}).then(
(response) => {response.text();}
).then(
(msg) => {console.log(msg)}
).then(
(error) => {console.log(error)}
);
The response returns the status code 200. The php script writes to a text file and echos Hello World.
<?php
header('Access-Control-Allow-Origin: http://localhost:3000');
$FILE = fopen("test.txt", "w");
fwrite($FILE, "Hello World");
?>
Hello World!
After executing the fetch, the console contains [undefined] twice. I previously logged the response, which contains an empty text attribute (and an empty json attribute), as well as status code 200 (Success). Also, the text-file is created, so the php-script definitely runs.
How can I see Hello World?
you have to return response from the response.text() section..
}).then(
(response) => { return response.text();}
).
or simply
}).then(
(response) => response.text();
).
and also in error section use .catch instead of .then

Angular httpClient - not catching PHP error object [duplicate]

This question already has answers here:
PHP: How to send HTTP response code?
(8 answers)
Closed 1 year ago.
I am tasked with connecting to an old php login api which simply returns a success or error message response object.
When I connect with the correct credentials I receive the success object and when do not I receive the error. Great!
However, httpClient does not seem to be recognizing the error object. Therefore, the object is accepted as a successful response object regardless of whether it is or it isn't.
The two relevant lines of php code:
$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 500, "message" => "Error");
echo $json_response = safe_json_encode($response);
I then added a couple more properties to the error response in the hope of it being recognized:
$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 403, "message" => "Error");
No luck...
I have then converted the observable into a promise so as to make the process as close as possible to the code used on an AngularJS app which uses the same login api:
let httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }),
};
let params = new HttpParams({
fromObject: { action: "login", username: credentials.username, password: credentials.password },
});
this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => console.log(data),
err => console.log(err) );
Still no luck...
The $http.error handler is triggered by server errors like 500 or 401;
If you wish to trigger a 401 error (unauthorized) for a bad login, do this:
if ($loginFailed) {
header("HTTP/1.1 401 Unauthorized");
exit;
}
Your angular code will pick that up as an error.
If you want to go on sending errors back the way you are currently, pick them up in the success callback, since the call was actually successful according to the server.
this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => {
console.log(data);
if (JSON.parse(data).error) this.triggerErrorResponse(data.error);
}, err => console.log(err) );

JSONP Ajax Error Jquery(Number String) Not Called

Since moving my site to https, the mailchimp api no longer works with the standard json ajax calls. These calls now render a same origin policy error. I don't know why this is the case though, because I'm calling a url on my own server. After some investigating, I've surmised that JSONP is my only option. The following script posts correctly to mailchimp but Im unable to get a successful response.
$.ajax({
type:"GET",
url:"https://mysite/book_subscription_process.php?jsonp=?",
data:{fname: $('#fNBookId').val(), lname: $('#lNBookId').val(), email: $('#eBookId').val()},//only input
dataType: "jsonp",
cache: false,
async: false,
jsonp: false,
success: function(data){
console.log('success');
if(data.message == 'failure')
{
alert('Error','There was an error processing your subscription. Please try again.');
}else if(data.message == 'success')
{
alert('success');
}else{
console.log(data.message);
}
},
error: function (xhr, ajaxOptions, thrownError, data) {
// console.log(data.message);
console.log('failure');
alert(xhr.status);
alert(thrownError);
}
});
Server side:
<?php
header("content-type: text/javascript");
if(isset($_GET['jsonp']))
{
$obj->fname = $_GET['fname'];
$obj->lname = $_GET['lname'];
$obj->email = $_GET['email'];
$obj->success = 'success';
$obj->failure = 'failure';
}
header("Content-type: application/json");
$MailChimp = new \Drewm\MailChimp($api_key);
$book = array('id' => $group_id, 'groups' => array('Book'));
$merge_vars = array('FNAME'=> $obj->fname,
'LNAME'=>$obj->lname,
'GROUPINGS'=>array($book)
);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $list_id,
'email' => array('email'=>$obj->email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => false,
));
if ( ! empty( $result['leid'] ) ) {
echo json_encode($obj->success);
}
else{
echo json_encode($obj->failure);
}
?>
As I said above the info is correctly posted to mailchimp. Each time however, the ajax call errors. I get a 200 OK but get a Jquery[bunch of numbers] not called. The json_encode success statement is executed on the server. Is there a special way that I'm supposed to handle the server side response? Or am I supposed to do something differently on the client side? Thanks in advance.
Same Origin means that the page making the request and the destination server need to have identical protocol, server, and port. For this particular situation, MailChimp isn't either of those -- the page making the request is your HTML page and the server is https://mysite/book_subscription_process.php.
Since you said this corresponds to your move to HTTPS, my guess is that you've moved one end but not the other. Since the code above looks like the front-end page is calling https://mysite, I'd triple check to make sure that the HTML and all scripts are also being served from https://mysite.
I don't think you should need JSONP in this scenario -- it sounds like you are attempting to work from the same origin, you just need to be sure you're doing that properly.

Need help formulating a correct JSON response

I am a novice using Jquery ajax calls and json responses and have hit a bump that I need help to overcome.
I am using cleeng open API and I am wondering about the response from one of the api calls I am using – getRentalOffer().
I am using jquery $ajax() request and I want to make the getRentalOffer() api call and return the result in JSON format. My efforts so far is this (assume a POST request with id as parameter.)
Request:
<script type="text/javascript">
$(document).ready(function() {
$( "#getOfferButton" ).click(function() {
var offerId = document.frm.offerID.value;
$.ajax({
// the URL for the request
url: "ajax-get-offer.php",
// the data to send (will be converted to a query string)
data: {
id: offerId
},
// whether this is a POST or GET request
type: "POST",
// the type of data we expect back
dataType : "json",
// code to run if the request succeeds;
// the response is passed to the function
success: function(json) {
// $("#title").val = json.title;
/*
$.each(json, function(i, item){
$("#"+item.field).val(item.value);
});
*/
console.log(json);
},
// code to run if the request fails; the raw request and
// status codes are passed to the function
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
// code to run regardless of success or failure
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
});
</script>
ajax-get-offer.php:
<?php
include_once('Cleeng-cleeng-php-sdk-fe2a543/cleeng_api.php');
/*
Using FirePHP to log variables
*/
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
$offerID = $_POST['id'];
$firephp->log($offerID, 'offerID');//For debugging
$publisherToken = 'My super secret token goes here!';
$cleengApi = new Cleeng_Api();
$cleengApi->setPublisherToken($publisherToken);
$offerDetails = $cleengApi->getRentalOffer($offerID);
$firephp->log($offerDetails, 'offerDetails');//For debugging
echo $offerDetails;
?>
When I try this I get Internal server error. I tried to use echo json_encode($offerDetails); on that last echo statement and then I do not get the server error. However the response only seem to contain the last element of the JSON object.
I need help to understand what I need to do with the API response from getRentalOffer() in order to pass it as a proper JSON response to the $ajax() request.
I hope my question make sense. :-)
Edit: Using print_r insead of echo I do get a response text but sadly with an error. This is the text and it looks to me as if it need to be formatted correctly before using print_r.
"Cleeng_Entity_RentalOffer Object ( [id:protected] => R875937249_SE [publisherEmail:protected] => martin.xxxxxxxx#xxxxxxx.se [url:protected] => http://xxx.xxxxxx.xx/cleeng_tool [title:protected] => Tjohooo! [description:protected] => En skön rulle om Afrika. [price:protected] => 55 [applicableTaxRate:protected] => 0.21 [period:protected] => 48 [currency:protected] => EUR [socialCommissionRate:protected] => 0 [contentType:protected] => video [contentExternalId:protected] => xxxxxxxxxxx [contentExternalData:protected] => {"platform":"vimeo","dimWidth":"500","dimHeight":"369","hasPreview":false,"previewVideoId":"","backgroundImage":"https://i.vimeocdn.com/video/xxxxxxxxx_960.jpg"} [contentAgeRestriction:protected] => [tags:protected] => Array ( [0] => abo ) [active:protected] => 1 [createdAt:protected] => 1400588711 [updatedAt:protected] => 1400606512 [pending:protected] => [averageRating] => 4 ) "
You cannot echo arrays or object, try using
print_r($offerDetails);
or
var_dump($offerDetails);
Solved.
The object returned by getRentalOffer() contains protected members which will not be encoded by json_encode because it respects the access parameters in the object vars. I found a nice solution in this post: http://smorgasbork.com/component/content/article/34-web/65-json-encoding-private-class-members
It is not a robust solution as it relies on a loophole that one day might be shut so beware of that. But for my needs it will suffice.

CodeIgniter REST API Library Ajax PUT throwing 403 Forbidden

I got the rest of the library working fully, just trying to generate api keys and its throwing a 403 forbidden when executed via ajax.
({"status":false,"error":"Invalid API Key."})
I traced it to _remap function under REST_Controller.. almost as if im calling the url incorrectly?
workflow: user visits site1.com -> registers for account -> generates api key for their domain -> key recorded in db -> key displayed
The following form would be on site1.com after they register for an account they would click "generate key".
ajax call:
/**
* Generate an API Key for Us to use
*/
$("#submitGetApiKey").click(function(){
$.ajax({
url: "http://dev.site1.com/api/key",
crossDomain: true,
type: "PUT",
dataType: "jsonp",
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
},
success: function(data){
for (var i = keys.length - 1; i >= 0; i--) {
console.log(keys[i]);
};
}
});
});
REST-SERVER on GitHub: https://github.com/philsturgeon/codeigniter-restserver
look specifically at key.php under application/controllers/api/key.php
Snippet of the key.php file that should relate to this process:
/**
* Key Create
*
* Insert a key into the database.
*
* #access public
* #return void
*/
public function index_put()
{
// Build a new key
$key = self::_generate_key();
// If no key level provided, give them a rubbish one
$level = $this->put('level') ? $this->put('level') : 1;
$ignore_limits = $this->put('ignore_limits') ? $this->put('ignore_limits') : 1;
// Insert the new key
if (self::_insert_key($key, array('level' => $level, 'ignore_limits' => $ignore_limits)))
{
$this->response(array('status' => 1, 'key' => $key), 201); // 201 = Created
}
else
{
$this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error
}
}
Response/Request Headers
Request URL:http://dev.mapitusa.com/api/key
Request Method:PUT
Status Code:403 Forbidden
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:0
Cookie:ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22e165df34aa4fda5936e940658030f83d%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A9%3A%22127.0.0.1%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A118%3A%22Mozilla%2F5.0+%28Macintosh%3B+Intel+Mac+OS+X+10_7_3%29+AppleWebKit%2F535.19+%28KHTML%2C+like+Gecko%29+Chrome%2F18.0.1025.3+Safari%2F535.19%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1328291821%3B%7Dac0f163b112dbd3769e67f4bb7122db2
Host:dev.mapitusa.com
Origin:http://dev.mapitusa.com
Referer:http://dev.mapitusa.com/api_test.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.3 Safari/535.19
Response Headersview source
Cache-Control:max-age=0, public
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:69
Content-Type:application/json
Date:Fri, 03 Feb 2012 18:03:54 GMT
Expires:Fri, 03 Feb 2012 18:03:54 GMT
Keep-Alive:timeout=5, max=98
Server:Apache
Set-Cookie:ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22f2f466f7b97b89f2a9b557d2d9a0dbcc%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A9%3A%22127.0.0.1%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A118%3A%22Mozilla%2F5.0+%28Macintosh%3B+Intel+Mac+OS+X+10_7_3%29+AppleWebKit%2F535.19+%28KHTML%2C+like+Gecko%29+Chrome%2F18.0.1025.3+Safari%2F535.19%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1328292234%3B%7D6821b96c7e58b55f1767eb265ffdb79e; expires=Fri, 03-Feb-2012 20:03:54 GMT; path=/
Status:403
Vary:Accept-Encoding,User-Agent
X-Powered-By:PHP/5.3.6
X-UA-Compatible:IE=Edge,chrome=1
i ended up finding out the 403 forbidden was because i was not providing an api key to generate keys..
Kind of abiguous as Phil's documentation doesn't state that an existing api key is required before you can generate keys..
I simply created a bogus key in the table in the db and referenced that when calling /key/index?X-API-KEY=boguskey
I have solved the problem of generating the api key.
I'm using Phil Sturgeon's REST API server.
Call the key controller using ajax call as such :
$("#submitGetApiKey").click(function(){
$.ajax({
url: "http://sitename.com/api/key/index?X-API-KEY=your_key_here",
crossDomain: true, /* remove this if using the same domain*/
type: "PUT",
dataType: "jsonp",
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
},
success: function(data){
for (var i = keys.length - 1; i >= 0; i--) {
console.log(keys[i]);
};
}
});
});
Inside key controller:
Search for function _generate_key() and check for $this->load->helper('security');. the security helper must be loaded for working of do_hash otherwise you will get 500 internal server error.
public function index_put()
{
// Build a new key
$key = self::_generate_key();
// If no key level provided, give them a rubbish one
$level = $this->put('level') ? $this->put('level') : 1;
$ignore_limits = $this->put('ignore_limits') ? $this->put('ignore_limits') : 1;
// Insert the new key
if (self::_insert_key($key, array('level' => $level, 'ignore_limits' => $ignore_limits)))
{
$this->response(array('status' => 1, 'key' => $key), 201); // 201 = Created
}
else
{
$this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error
}
}
Also, you may call http://sitename.com/api/keyindex?X-API-KEY=your_key_here in your browser's address bar by making a small change in your key controller
you can replace the function name index_put with index_get.
Thanks
If you are calling this from a different domain, you may be running into some XSS issues. You might have to run it from your own server and call the function from it's own domain or possibly use the JSONP capability.
UPDATE: Are you able to see the transaction in Firebug using the NET Tab?
Do you get JSON Back?
Sometimes you have to add callback=? to the url request:
http://dev.site1.com/api/key?callback=?
Update2: Are you able to bring the page up in the browser: (http://dev.mapitusa.com/api/key)
If you get the same error, you should try giving 777 (full read/write) permissions to the site.
This sounds like it might be a browser issue. Maybe an incorrect implementation of PUT in the XMLHttpRequest stack.
I would try converting it quickly to POST just to see if it works. It might be better off leaving it as POST anyway just for compatibility purposes.

Categories