I am using JS Engage sdk to call saveEmail API. I am getting an error in API response call back but not able to get the response.
ibmIMCIntegration.oAuthClientId = value["IBMIMC"].oAuthClientId;
ibmIMCIntegration.oAuthClientSecret = value["IBMIMC"].oAuthClientSecret;
ibmIMCIntegration.oAuthRefreshToken = value["IBMIMC"].oAuthRefreshToken;
// var arrOfClickThroughs = [{clickThroughName:"ingagechatbutton",clickThroughType:2,clickThroughURL:$scope.messangerID}];
var parameters = {
header:{
mailingName:$scope.mailingName,
subject: $scope.subject,
listId: 85326,
fromName: $scope.fromName,
fromAddress: $scope.fromAddress,
replyTo: $scope.replyTo,
visibility: 1,
encoding: 6,
trackingLevel: 2,
clickHereMessage: false
},
messageBodies:{
htmlBody:newSource
},
// clickThroughs:{
// clickThrough:arrOfClickThroughs
// },
forwardToFriend:{
forwardType:0
}
};
ibmIMCIntegration.parameters = JSON.stringify(parameters);
var userJson = {
type:"saveMailing",
options:ibmIMCIntegration,
};
console.info("List IBM Template | User JSON:" +
JSON.stringify(userJson));
var url = 'api/db/invokeIBMIMCOperation.php';
$http.post(url, userJson)
.success(function(res) {
if (res) {
if(res.isSuccess === true) {
swal("", "Your template has been created successfully", "success");
document.getElementById("form1").reset();
}
else {
swal("", "Please try again", "error");
}
console.info(res);
}else{
swal("", "Please try again", "error");
}
});
Here is my API funciton call:
function saveMailing(engage,parameters,ctx){
engage.saveMailing(parameters,function(err, result) {
if (err) {
console.log('Failed to load Save aMailing: ' + err);
} else {
console.log(JSON.stringify(result));
}
});
}
where I am now getting result array. If I am sending wrong parameter then it print the error console but if I got success to save template then it just print "{}".
Is there anyway I can get the response. ?
I found the solution for getting response from the Engage node.js sdk.
The reason behind getting the null response is Sdk tries to delete the response. I don't know why they are deleting the response. sdk only sends error message response in call back.
For getting the success response :
Open the file engage-xml-api.js from engage-api/lib folder.
find delete(response.Envelope.Body.RESULT.SUCCESS); line and comment it.
You will get the successful response if your query is correct.
Thanks
Related
I am trying to call a simple php file from my React application which will send an email with the details from a contact form. For some reason when the React code executes the fetch of the PHP file, it returns a 409. However, if I manually post the URL into another tab it works as expected, and subsequent calls from my React application then work as expected!
This is my React code:
var url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg
console.log(url)
console.log('sending')
fetch(url,
{
'headers': {
'Accept': 'text/html',
'Content-Type': 'text/html'
},
'method': 'GET',
})
.then(
(result) => {
console.log(result.status)
if (result.status === 200) {
console.log('success')
this.togglePop();
this.setState({
name: "",
email: "",
phone: "",
message: "",
terms: false,
})
} else {
console.log('failed')
this.setState({ openError: true })
}
},
(error) => {
console.log('ERROR')
console.log(error)
this.setState({ openError: true })
}
)
And this is my PHP file:
<?php
//header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html');
// error handler function
function customError($errno, $errstr) {
error_log($errstr);
http_response_code(500);
}
// set error handler
set_error_handler("customError");
http_response_code(200);
// send email
mail($_GET["to"],$_GET["subject"],$_GET["msg"],"From: donot.reply#site.co.uk","-f donot.reply#site.co.uk");
error_log($_GET["subject"].":\n".$_GET["msg"], 0);
echo 'OK';
?>
I have spent several days trying to figure out why this is happening. My htaccess file seems OK as once I have made one succesful call to the PHP file it works after that!
It's not a CORS issue as the file is on the same domain.
Anyone got any ideas?
You are sending the wrong request to the server, and that's why you get a 409 error. You should encode the URL params before sending a request
const url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg;
const encoded = encodeURI(url);
console.log(encoded)
// expected correct URI: "/backend/sendmail.php?subject=New%20Website%20Enquiry&to=info#site.co.uk&msg="
You can read more about it here
I am at a loss now. I am trying to reach the Azure Billing & Usage API via my php application, but keep getting the following error:
XMLHttpRequest cannot load
https://ea.azure.com/rest/{agreementnumber}/usage-reports. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
I know the link mentions the url is https://consumption.azure.com/v2/enrollments, however this was not working for me and after contact with Azure tech service I needed to use the older ea.azure.com entry point.
I am trying this from my development xampp localhost server as well as the production server (live intranet solution), but to no avail. Using postman the connection succeeds and I receive a valid response from the API.
Basically the API requires only an API key, which i have. no authorization is required next to this.
As Postman is succesful in getting a valid response from the API, I used their code generator to get me:
php script
javascript script
jquery ajax script
All of them return the same error for me; the jquery ajax one is shown because that one is preferred:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://ea.azure.com/rest/<?php echo $agreement_number; ?>/usage-reports",
"method": "GET",
"dataType": 'json',
"headers": {
"authorization": "bearer <?php echo $key; ?>"
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connected.\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);
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
I do not understand why Postman is able to connect to the API and retrieve it's information, whilst exactly the same code generates a CORS error when used in my application.
Could this have something to do with my application being hosted in an internal virtual machine within the company's network, not accessible from the internet?
Edit: Rory mentioned the tight security restrictions of JS - therefore I added the php script also. As I use php 5.6, I do not have the class httpRequest by default, so I used the httpRequest class by twslankard and tweaked it to accept custom headers like this (added public function):
public function setHeaders($headers) {
if(is_array($headers)) {
foreach($headers as $name => $val) {
$this->headers[$name] = $val;
}
}
}
And calling the class like this:
include_once($_SERVER['DOCUMENT_ROOT'].'/functions/class_httprequest.php');
$request = new HttpRequest($url, 'GET');
$request->setHeaders(array(
'api-version' => '2014-09-02',
'authorization' => $key
));
try {
$response = $request->send();
echo $request->getStatus().'<br>';
echo $request->getResponseBody();
} catch (HttpException $ex) {
echo $ex;
}
Using the php version it did work, the trick was adding the api-version header, before that I got an http 400 error back using the php script.
Using the php version it did work, the trick was adding the api-version header, before that I got an http 400 error back using the php script.
I just added x-editable to my current Laravel project. It works perfectly well but I have a problem with returning the error message.
When the controller is able to save the request, I get a 'Success!' json message. That's fine. But when I have an error, I do not get the 'Error!' message. As you can see I fire up the error message when $article->save() was not successful.
What am I doing wrong?
Controller:
$article->$input['name'] = $input['value'];
if( $article->save() ){
// this works
return response()->json(array('status'=>'success', 'msg'=>'Success!.'), 200);
}
else{
// this does not work
return response()->json(array('status'=>'error', 'msg'=>'Error!'), 500);
}
JavaScript in View:
$(".xeditable").editable({
success: function(response) {
console.log(response.msg);
},
error: function(response) {
// console says, that response.msg is undefinded
console.log(response.msg);
}
});
Kind regards.
On error callback, the passed response parameter is jqXHR (jQuery XMLHttpRequest). In order to access the JSON response, you can access the responseJSON property like the code below.
$(".xeditable").editable({
success: function(response) {
console.log(response.msg);
// Must return nothing.
},
error: function(response) {
// The JSON object stored in responseJSON property.
console.log(response.responseJSON.msg);
// Must return a string, represent the error message.
return response.responseJSON.msg;
}
});
As pointed on the X-editable documentation, the error callback must return a string that represents the error message.
Hope this help!
I'm not familiar with x-editable but try to change the response code in case of error from 500 to 200 and then in your javascript
$(".xeditable").editable({
success: function(response) {
if (response.status == 'error') {
console.log('error: ' + response.msg);
}
else {
// do stuff for successful calls
console.log('success: ' + response.msg);
}
},
error: function(xhr, status, error) {
console.log('server error: ' + status + ' ' + error);
}
});
I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.
The client side:
<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();
$.ajax({
url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
});
</script>
The server side:
<?php
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
$query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Additional fix, you should check whether the query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Hope it helps.
Just so you know, you can use this for debugging. It helped me a lot, and still does
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.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.
However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WAS found.
Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.
e.g. in PHP you'd have
$results = array(
'error' => false,
'error_msg' => 'Everything A-OK',
'data' => array(....results of request here ...)
);
echo json_encode($results);
Then in your client-side code you'd have
if (!data.error) {
... got data, do something with it ...
} else {
... invoke error handler ...
}
In order to build an AJAX webservice, you need TWO files :
A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
Server side:
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
Client side:
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
adding to the top answer: here is some sample code from PHP and Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - send custom message / status:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
I had the same issue. My problem was that my header type wasn't set properly.
I just added this before my json echo
header('Content-type: application/json');
...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.
Typically, right mouse->inspect on your html page.
Then look in the error console for errors like
Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
I have the following:
YUI().use("io-form",
function(Y) {
var cfg = {
method: 'POST',
form: {
id: 'subscribe-form',
useDisabled: false
}
};
function login() {
Y.io('process.php', cfg);
Y.on('io:success', onSuccess, this);
Y.on('io:failure', onFailure, this);
};
function onSuccess(id,response,args) {
document.getElementById('myformmsg').innerHTML = response.responseText;
document.forms['myform'].reset();
};
function onFailure(id,response,args) {
document.getElementById('myformmsg').innerHTML = "Error, retry...";
document.forms['myform'].reset();
};
Y.on('click', login, '#myformbutton', this, true);
});
How does yui know whether to go into onSucces of onFailure. What do I have to return from PHP?
It depends on the header returned http status code.
let say status code 200, it will goes to onSuccess.
let say status code 500 (internal server error), it will goes to onFailure.
List of HTTP status code here: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
If you have some fatal error in php, it will still returns status 200 because the request is successful.
If you would like to handle php errors, I would suggest you to have an json return like everytime on success:
{
status: 0, // Let say 0 for OK, -1 for Error, you can define more by yourself
results: <anything you want here>,
errors: <errors message/errors code for your ajax handler to handle>
}
it can be done in php like this:
$response = array(
'status' => 0,
'results' => 'something good ...',
'errors' => 'error message if status is -1'
);
echo json_encode($response);
In your javascript, you will be handling like this:
function onSuccess(id,response,args) {
var responseObj = Y.JSON.parse(response);
if (responseObj.status === 0) {
// Request and process by php successful
}
else {
// Error handling
alert(responseObj.errors);
}
};
Remember, if you wanted to use Y.JSON, you need to include 'json-parse', example:
YUI().use('json-parse', , function (Y) {
// JSON is available and ready for use. Add implementation
// code here.
});