Jquery ajax fail when calling rest webservice - javascript

I have a set of REST URIs that i can access after authenticating on the server. This service takes a JSON input with the login information and retrieve a JSON output with the session ID.
When using a Rest client, like a chrome extension, everything works.
Now I want to implement it using JS but despite of the failure return, I can not see any details of what is wrong (error messages are blank) and neither could found what I am missing in my code.
$.ajax({
// the URL for the request
url: "https://host002:50000/b1s/v1/Login",
// the data to send (will be converted to a query string)
data: {
UserName: "manager",
Password: "1234",
CompanyDB: "CUS_001"
},
// 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 ) {
$( "<h1/>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
},
// 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! " + xhr.responseText);
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!" );
}
});
xhr.responseText is always blank. Status is always error. errorThrown is always blank as well.
I tried also the $post method but got the same behavior.

Your JSON is incorrect. Try using this
data: JSON.stringify({UserName: "manager", Password: "1234", CompanyDB: "CUS_001"});

While navigating from one url to other there is a cross-domain error thing which pops up.
Try doing this.
Call to a function on your same url using ajax and from there use CURL request to your web service url.

Related

How to get JSON data from WP REST API

For a long time I've being working on how to get access to my WordPress posts. I'm using WP REST API plugin with the WP REST API - OAuth 1.0a Server, and I get an "401 - Only authenticated users can access the REST API" error.
I've read all the documentation and I touched the .htaccess, and I'm going crazy. Please someone help I don't know what to do, and I'm about to give up.
I tried add some code in the .htaccess file, and also tried AJAX and JavaScript fetch, and nothing seems to work. I know there are people using it. It'd be nice someone can tell me how to fix this, I really need it.
jQuery.ajax({
url: 'http://laprensainsolita.com/wp-json/wp/v2/posts',
method: 'GET',
crossDomain: true,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'username:password' ) );
},
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
});
Do I need to add any code to the .htaccess file? And if so what and where should I put it? Or what is need to make this work. I'm very desperate.
The error:
{
"code": "rest_cannot_access",
"message": "Only authenticated users can access the REST API.",
"data": {
"status": 401
}
}
Please try to pass fields to store credentials. Add this fragment to your AJAX call
xhrFields: {
withCredentials: true
},
Your call should look something like this:
Query.ajax({
url: 'http://laprensainsolita.com/wp-json/wp/v2/posts',
method: 'GET',
crossDomain: true,
xhrFields: {
withCredentials: true
},
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode(
'username:password' ) );
},
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
});

recpatcha returns 200, still get error with jQuery ajax

All of my other searches yield responses about cross-domain requests. It appears that I'm not having a problem with that. I'm getting a response from the recaptcha server, but it's not being interpreted correctly.
<script>
function verifyCaptcha() {
jQuery.ajax({
method: "POST" ,
url: "https://www.google.com/recaptcha/api/siteverify",
data: { secret: "xxxxxxxxxxxxxxxxxxx" , response: "<% $recaptcha_response %>" },
dataType: 'jsonp' ,
success: function( result ) {
alert( result.success ) ;
},
error: function( xhr ) {
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' Response Text: ' + xhr.responseText);
}
})
}
onload=verifyCaptcha ;
</script>
This function lives in a page that's the target of a submitted form. When I check fireBug for the results, I get this in my alert message:
Request Status: 200 Status Text: success Response Text: undefined
And the response captured by FireBug is
{
"success": true
}
It seems that it gets mad without the parens wrapped around the returned JSON which I thought were supposed to come free with dataType: 'jsonp'
How do I resolve the success of this?
UPDATE
Adding additional return parameters to the error funcion: ( xhr , message , errorThrown ) produced the following:
Request Status: 200
Status Text: success
Response Text: undefined
Message: parsererror
ErrorThrown: Error: jQuery1120043068059910713263_1455115913634 was not called
I'm guessing that the jQuery1120043068059910713263_1455115913634 was not called message is the callback function randomly named by jQuery. Does this mean that I need to add something to my logic, or that the reCaptcha server does not indeed support jsonp ?
Setting the dataType to "json" gives me a request status of 0.
UPDATE 2
I added this to my function:
jsonp: false,
jsonpCallback: 'onJSONPLoad',
and my errorThrown text changed to:
Error: onJSONPLoad was not called which leads me to conclude that reCaptcha does not support jsonp. Can anyone confirm this?
I guess the Answer is:
The POST method is not available for jsonp, only GET
update:
As well as in the comment stated setting the dataType to"json" and it will automatically converted to jsonp, maybe try that
also you can add a third argument to the error function
error: function( xhr, message, errorThrown ) {
and errorThrown maybe is more explicit

How to call an exception with post method (AJAX)?

If the post method is unsuccessful I want to throw an exception and write to an error log? Basically if this method returns no results I want to throw an exception and write to file.
Post method:
$.post("ip.php", function( data ){
$("#ip").val(data.ip);
$("#country").val(data.country);
$('#campaignID').val(data.campaignID);
}, "json");
Just add the fail(); method.
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
For the part of the question:
If the post method is unsuccessful I want to throw an exception (...)
You could chain a .fail() callback method to the $.post() request as mentioned by #Grimbode
Or use $.ajax() instead, where is an error option - function to be called if the request fails.
The $.ajax() equivalent to your $.post() method would be:
$.ajax({
type : "POST",
url : "ip.php",
dataType : 'json',
success : function(data){
$("#ip").val(data.ip);
$("#country").val(data.country);
$('#campaignID').val(data.campaignID);
},
error : function(jqXHR/*object*/, textStatus/*string*/, errorThrown/*object*/){
// throw an error ...
// console.log('Type of error: ' + textStatus);
},
});
As for that part:
(...) write to an error log
It's not possible to write any file with javascript. Since it's a client side scripting language that executes in a client browser, it has no access to the server. Well, that's how it works.

Trouble retrieving data from Pocket API using jquery.post()

I'm attempting to retrieve data from my Pocket account using the Pocket API by accessing it with a jQuery post function. I have obtained the consumer key and access token and when I execute the following code I get a parseerror ...but the data shows up in JSON format in Firebug.
var myPost = $.post("https://getpocket.com/v3/get",
{ "consumer_key": "<<consumer key here>>",
"access_token": "<<access token here>>",
"count": "3",
"detailType": "simple"
},function(data) {
return data
},
"jsonp");
myPost.done(function( msg ) {
console.log(myPost)
alert(msg);
});
myPost.fail(function( jqXHR, textStatus ) {
console.log(jqXHR)
alert( "Request failed: " + textStatus );
});
If I change the dataType on the post call from "jsonp" to "json" I don't get the parse error but instead get a generic error (literally just "error") with nothing returned in teh response tab in Firebug.
Attempts to do this call using jQuery.ajax() have also failed, yielding an error 400.
var something = $.ajax({
"accepts": 'application/json',
"type": 'POST',
"url": "https://getpocket.com/v3/get",
"contentType": 'application/json; charset=UTF8',
"data": {"consumer_key": "<<insert consumer key here>>",
"access_token": "<<insert access token here>>",
"count": "3",
"detailType": "simple"},
"dataType": 'json',
"success": ""
});
Seems like I am close using $.post() but how to I clear that error so I can get the actual response data returned?

FB ui feed get message after posting on wall

I'm using this function to initiate a UI feed to post on my wall a content from my website. :
FB.ui({
method: 'feed',
name: myname,
link: window.location.href,
picture: mypic,
caption: '',
description: desc
},function(response){}
});
I need to execute a callback inside the callback in which I can retrieve the message that the I inserted in the Facebook Dialog, I'm searching but not finding a way to get it, I also tried to delegate a keydown event to the dialog's textarea , but It does not work.
How can I solve this?
In order to extract data from the post that was created from the dialog you can retrieve the post_id from within the callback function that the dialog provides. Within the callback you'll be able to inspect the response object. It will contain the post_id provided that the post was successfully created.
With this post_id you can execute an additional call to the API and provide the post_id` as the endpoint:
https://graph.facebook.com/POST_ID
Or with the JavaScript SDK:
FB.api( '/POST_ID', function( response ) {
console.log( response );
} );
Take a look at the response object from the second call, it'll look something like this :
{
"id": "POST_ID",
"from": {
"name": "Lix",
"id": "XXXYYY"
},
"message": "Checkout this awesome link!",
"picture": "https://fbexternal-a.akamaihd.net/...",
...
}
As you can see, the message is contained in the response, so to enhance my previous example:
FB.api( '/POST_ID', function( response ) {
if ( response ){
console.log( response.message );
}
} );
And now we can put it all together with the FB.ui call:
FB.ui({
method: 'feed',
...
},function( response ){
if ( response && response.post_id ){
FB.api( '/' + response.post_id, function( response ) {
console.log( response );
} );
}
}
});

Categories

Resources