Ajax post data store with json and jsonData - json

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

Related

How to pass a json file through ajax as Multipart and retrive the file in servlet (jsp)

Please find the code,
json = JSON.parse(e.target.result);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "jsnservlt",
data: json,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function(dataa) {
var resp =JSON.parse(data);
console.log(resp);
alert(dataa);
},
error: function(error) {
console.log(error);
}
});
How to retrieve the json in servlet?

How to send array with json using ajax

How do I send an array with json using ajax? I want to store email and name:
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: 'email=' + $('#txtemail').val() ,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});
Let's suppose you have an array?
var array = [
"student1" : {
"name": "jon",
"email": "test#example.com"
},
"student2" : {
"name": "jon2",
"email": "test2#example.com"
}
]
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array),
datatype : 'application/json',
}, function(success) {
console.log(success)
});
Your question is not clear.please write your question in correct format.then community can be resolve your question easily.
I assume your problem and give solution for that.
var array = {name:'dua',email:'dua#gmail.com'};
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array)
}, function(success) {
console.log(success)
});
var postData = { "email":email,"name":name }
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: postData,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});

How to send array of objects to a controller method?

I need your help, I have this piece of code in the controller side
public bool DraftMessage(message[] draftMessages, HttpPostedFileBase[] files = null)
{
return true;
}
and I use this client side code to send the data
function DraftMessage()
{
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }]
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Activities")",
datatype: "json",
traditional: true,
data: JSON.stringify({ draftMessages: myArray }),
beforeSend: function () { }
}).done(function (data) {});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
but when I debug it I found that the array of messages in the controller is null so could anyone guide me about what I did wrong and help me to fix this issue.
You need to set contentType as "application/json"
function DraftMessage() {
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }];
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Home")",
contentType: "application/json",
data: JSON.stringify({ draftMessages: myArray })
}).done(function (data) {
console.log(data);
});
}
The default value of contentType header is "application/x-www-form-urlencoded" . Since we are sending the json stringified version of a a complex data structure, we should explicitly specify the contentType

Why doesn't Kendo Datasource transmit the "take" parameter?

This is my code:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: getMembersUrl,
dataType: "json",
type: "get"
}
},
serverPaging: true,
pageSize: 2,
schema: {
data: "Data",
total: "Total",
}
});
When I call read on the datasource, it doesn't send the pagesize or take (I tried both) as part of the request. I am really scratching my head on this one.
Your code works fine and it sends take as expected. If you run:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "fake",
dataType: "json",
type: "get"
}
},
serverPaging: true,
pageSize: 2,
schema: {
data: "Data",
total: "Total",
}
});
And define a button and a handler for triggering the read:
<button id="read" class="k-button">Read</button>
$("#read").on("click", function() {
console.log("About to fetch data");
dataSource.fetch();
});
As here : http://jsfiddle.net/OnaBai/34qe4oks/
You will see in the browser console that it actually sends the request:
If you don't see the request is very likely because you are not actually reading from the DataSource (remember that the Grid DataSource is read when the Grid finishes its initialization)

Alchemy sentiments text API json parse error

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