Alchemy sentiments text API json parse error - json

Hi I am making the call for alchemy sentiments API as given below:
function getAnalysis(sentence)
{
$.ajax({
url:alchemy.baseUrl,//http://access.alchemyapi.com/calls/text/TextGetTextSentiment`enter code here`
type: 'POST',
dataType:'jsonp',
contentType:'json',
data:{
apikey:alchemy.acessKey,
text:sentence,
showSourceText:1,
outputMode:'json'
//outputMode:'xml'
},
context: this
}).done(function(data){
console.log('Sentiments Analysis sucessfull..');
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Sentiments Analysis error:', textStatus, errorThrown);
});
I am getting status 200 OK. But error in parsing : is returned from ajax call. I have validated JSON it is correct.The json is below:
{
"status": "OK",
"usage": "By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html",
"url": "",
"language": "english",
"text": "sachin is a good batsman.",
"docSentiment": {
"type": "positive",
"score": "0.50098"
}
}
Please help me.

I have solved the question just by modifying the ajax request and adding the callback as given below:
function getAnalysis(sentence)
{
$.ajax({
url: alchemy.baseUrl,
type: 'POST',
dataType:'jsonp',
contentType:'json',
jsonpCallback:'callback',
data:{
apikey:alchemy.acessKey,
text:sentence,
showSourceText:1,
jsonp:'callback',
outputMode:'json'
},
context: this
}).done(function(data){
console.log('Sentiments Analysis sucessfull..');
console.log(data);
var text=data.text;
if(data.docSentiment.type==="negative")
{
displayNegetiveAnalysis(text);
}
else if(data.docSentiment.type==="positive"){
displayPositiveAnalysis(text);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Sentiments Analysis error:', textStatus, errorThrown);
});
}
/*
* Function:Callback
* Description:passing callback to URL Call
*
*/
function callback(json){
console.log(json);
}

Related

Update item in another site collection in sharepoint 2013

I need to update item in another site collection according to this article I make my code like this
<script type="text/javascript">
$(document).ready(function () {
var otherSiteUrl = "<sitecollectionurl>";
var listName = "TestList";
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {
"type": itemType
},
"Title": "updated title"
};
$.ajax({
url: otherSiteUrl + "/_api/contextinfo",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (contextData) {
alert(contextData.d.GetContextWebInformation.FormDigestValue);
$.ajax({
url: otherSiteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?#target='" + otherSiteUrl + "'",
method: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue
},
success: function (data) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
I used
"X-RequestDigest":
contextData.d.GetContextWebInformation.FormDigestValue
after that I chenge ajax header like
"X-RequestDigest":
$("#__REQUESTDIGEST").val(contextData.d.GetContextWebInformation.FormDigestValue)
for both RequestDigest I got this error:
Invalid JSON. A token was not recognized in the JSON content
after that I chenge ajax header as
How can I update item successfully in another site collection with api?
eventually, I can edit item in another site collection.I just little change in my code.
first, most important part is library full name dose not contain List I use this url to find out library full name .
[Site url]/_api/web/lists/GetByTitle('List Name')/ListItemEntityTypeFullName
then I change metadate as
"__metadata": { "type": 'SP.Data.DocumentsItem' },
second I added
"X-HTTP-Method": "MERGE" , "If-Match": "*"
to header like:
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},

Ajax post data store with json and jsonData

i want to write a data store, that gets its data by an ajax call. The ajax call has to be a http post message and has to contain some data in json format.
Thats what I have so far:
Ext.define("MyApp.store.FileContent", {
extend: "Ext.data.Store",
model:'MyApp.model.FileContent',
autoLoad: true,
proxy: {
actionMethods : {
read : 'POST'
},
type: 'ajax',
defaultHeaders:{
'Content-Type': 'application/json; charset=utf-8',
},
url : apiUrl + 'Files/GetFileInfo',
jsonData : '{"file": "myfile"}'
}
});
The call to the webservice works, but the variable "file" is always empty. What is wrong here?
Got it by writing a custom proxy
store:
Ext.define("MyApp.store.FileContent", {
extend: "Ext.data.Store",
model:'MyApp.model.FileContent',
autoLoad: true,
requires: ['MyApp.proxy.FileContent'],
proxy: {
type: 'FileContent'
}
});
proxy:
Ext.define('MyApp.proxy.FileContent', {
extend: 'Ext.data.proxy.Proxy',
alias: 'proxy.FileContent',
create: function (operation, callback, scope) {
//Here goes your create logic
},
read: function (operation, callback, scope) {
Ext.Ajax.request({
url: apiUrl + 'Files/GetFileInfo',
method: "POST",
defaultHeaders:{
'Content-Type': 'application/json; charset=utf-8',
},
jsonData: '{"file": "myfile"}',
success: function(response){
var json = JSON.parse(response.responseText);
},
failure: function(){
alert("fail");
}
});
},
update: function (operation, callback, scope) {
//Here goes your update logic
},
destroy: function (operation, callback, scope) {
//Here goes your delete logic
}
});

Ajax call throws parse error

I am getting a parse error when trying to perform the following call:
$.ajax({
cache: true,
url: "http://localhost:3000/app/test/result1",
data: "{}",
type: "GET",
jsonpCallback: "testCall",
contentType: "application/jsonp; charset=utf-8",
dataType: "jsonp",
error: function (xhr, status, error) {
alert(error);
},
success: function (result) {
alert(result);
},
complete: function (request, textStatus) {
alert(request.responseText);
alert(textStatus);
}
});
If I paste the request url in the browser address bar directly, the result returned is seems to be valid JSON:
{
"name": "The Name",
"description": "The Description"
}
I am using IISnode, NodeJs & Express JS. I have tested both scenarios:
// NODE JS CODE
var app = express();
app.get('/app/test/result1', function (req, res) {
res.send({ name: "The Name", description: "The Description" });
});
app.get('/app/test/result2', function (req, res) {
res.send(JSON.stringify({ name: "The Name", description: "the Description" }));
});
Any advice is appreciated, thanks in advance.
Your dataType is listed as jsonp. However, your response from node.js is not a properly formatted JSON-P response. JSON-P responses need to be wrapped in a callback, like so:
testCall({ name: "The Name", description: "The Description" });
The node.js code would look something like this:
res.send(
'testCall(' +
JSON.stringify({ name: "The Name", description: "the Description" }) +
');'
);
(Also note that you don't need the data: "{}" line since the request is a GET request and doesn't include any data. It shouldn't hurt anything, but might be nice to remove to avoid confusion).

Jquery Validate then .onsubmit function

I am using Jquery validation in a form and also an Ajax function in a .on(submit) code.
The problem is even when the validation is wrong the .on(submit) function still runs.
Is there any type of "if validation success" code to add to the validation code to put the .on(submit) code in so it will only run when the form is correct and validated?
this is the .on(submit) function
$('#valform').on('submit', function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo MAXINBOUND_PLUGIN_URL ?>/php/localProxy.php",
data: $('#valform').serialize(),
success: function (response) {
alert('Great!');
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
});
and this is the validation code
$("#valform").validate({
invalidHandler: function(form, validator) {
success: function (response) {
var errors = validator.numberOfInvalids();
if (errors) {
$("#error-message").show().text("Please correct the required field(s)");
} else {
$("#error-message").hide();
}
},
messages: {
agree: {
required: ""
},
phone1: {
required: ""
},
address1: {
required: ""
},
},
rules: {
agree: {
required: true,
},
phone1: {
required: true,
phoneUS: true
},
Address1: {
required: true,
addr: true,
},
},
});
You can use submitHandler to do ajax calls. So it will call only after passing all validations.
$("#valform").validate({
submitHandler: function(form) {
//do ajax call
}
})
You can use the jquery valid() method to check if the submitted form is valid. Something like this...
if ($("#valform").valid()) {
// do your ajax stuff
}
Please note that valid() will work only when the validate() is called on the form prior to it.
Hope this helps!

how connect with web service

I am trying to get some data from a web service:
$.ajax({
type: 'POST',
url: "http://192.******.asmx?op=GetJSONString",
method: "serverCallback",
data: "Select con.cod as codigo, con.res as descripcion from con where ide>0",
success: function(data){alert(data)},
});
How can I get the returned JSON data?
Here is what my calls look like. Can you be more specific of the issue you are having?
$.ajax({
type: "POST",
data: "SOME DATA",
dataType: "json",
url : "/myapp/service.json",
cache: false,
error: function() {
alert("There was an issue");
}
,
success: function(data)
{
processJson(data);
}
});
I will also post what has worked with me for asmx services.
In the example below, for "url": "/service/Details.asmx/Reject", the "/Reject" is the method name in the web service (asmx) file.
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": "/service/Details.asmx/Reject",
"data": "{\"itemId\":\"" + id + "\",\"comment\":\"" + comms + "\"}",
"success":
function (msg) {
alert("Yea it worked!");
});
}
});