What is the difference between .ajax() and .getJSON() - json

I am trying to understand what the difference between these two? I have read that .getJSON calls .ajax. But what functionally is different? Which would work?
Imagine that you are trying to write a client-side webapp that interacts with the following RESTFUL API that represents an online car catalog:
GET /cars - Returns a list of all cars in the catalog
Example response:
{"cars": [
{"id": 1, "model": "Alice in Wonderland", "make": "Chevy"},
{"id": 2, "model": "Civic", "make": "Honda"}
]}
POST /cars - Creates a new car based on the given info
Example request:
{"model": "Wrangler", "make": "Jeep"}
Example response:
{"id": 3}
GET /cars/<id> - Returns info about the car with that id
Example response:
{"id": 1, "model": "Alice in Wonderland", "make": "Chevy"}
PUT /cars/<id> - Overrides info about the car with the given id with the new data
Example request:
{"model": "Wrangler", "make": "Jeep"}
DELETE /cars/<id> - Deletes the car at the given id. The id may be recycled for other cars
You have been instructed to write some code that:
Deletes all cars made by Chevy
Modifies the models of all cars written by Jeep to all-caps
$.ajax({ url: "/cars", type: "GET" }, function(data) {
data.cars.forEach(function (car) {
var endpoint = "/car/" + car.id;
if (car.make == "Chevy") {
$.ajax({ url: endpoint, type: "DELETE" });
} else if (car.make == "Toyota") {
var request = {title: car.title.toUpperCase(), make: car.make};
$.ajax({ url: endpoint, type: "PUT", data: JSON.stringify(request) });
}
});
});
$.getJSON("/cars", function(data) {
data.cars.forEach(function (car) {
var endpoint = "/car/" + car.id;
if (car.make == "Chevy") {
$.ajax({ url: endpoint, type: "DELETE" });
} else if (car.make == "Toyota") {
var request = {title: car.title.toUpperCase(), make: car.make};
$.ajax({
url: endpoint,
type: "PUT",
data: JSON.stringify(request),
contentType: "application.json"
});
}
});
});

Related

How to post Handsontable data into WordPress REST API?

I'm trying to post the data from Handsontable into WordPress using WP REST API. This is what I tried :
$('#publish').on('click',function(e){
var data = JSON.stringify(hot.getDataAtRow(0));
$.ajax({
url: 'domain.com/staging/wp-json/wp/v2/posts/',
method: 'POST',
crossDomain: true,
dataType: 'json',
contentType: 'application/json',
data: data,
beforeSend : function(xhr) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
success: function( data ) {
console.log( data );
},
error: function ( error ) {
console.log( error );
}
});
});
I get this response :
{"code":"empty_content","message":"Content, title, and excerpt are
empty.","data":{"status":400}}
However, the output of JSON.stringify(hot.getDataAtRow(0)) is looks like this :
["John Doe","Sample text","publish"]
I tried manual way by set the data like this, it works :
data: {
"title": "John Doe",
"content": "Sample text",
"status": "publish"
}
So my question is :
How to get the data from Handsontable on that format? I need to set which field is the title, content, status, excerpt, etc.
The output of your JSON.stringify(hot.getDataAtRow(0)) gets you an array of strings, whereas API expects an object with 3 fields.
Try:
var data = {
"title": hot.getDataAtCell(0, 0),
"content": hot.getDataAtCell(0, 1),
"status": hot.getDataAtCell(0, 2),
};
And then in your AJAX call:
data: JSON.stringify(data),

how to print id from ajax result

how to print id from ajax data
data.id is undefined
$.ajax({
url: "userdetails",
type: "get",
success: function (data) {
alert(data);
console.log($(this).serialize());
$("#ajaxdata").append(data);
alert(data.id)
}
});
data value is below
[{
"id": 28,
"firstname": "asddsf",
"lastname": "sss",
"email": "terrymol.christian#roarsinc.com",
"role_id": 1,
"status": "Active"
}, {
"id": 87,
"firstname": "df",
"lastname": "dsfsd",
"email": "sdfsdf#dfds.hgj",
"role_id": 1,
"status": "Active"
}]
The response would be not treated as JSON if the data type is not being specified or server is not mentioning it in the response header.
Try this
$.ajax({
url: "userdetails",
type: "get",
dataType: "json",
success: function (data) {
alert(data);
console.log($(this).serialize());
$("#ajaxdata").append(data);
alert(data.id)
}
});
Update:
The response looks like an array of objects. You would need to try alert(data[0].id)

ExtJS 5: how to set up a store to gather remote data when a POST with JSON body is required?

I need a store to gather data from a URL, but the URL needs a POST of JSON data in order to create the correct response (in this example, a set of disclaimer questions the user must answer, based on the products in his shopping cart.)
Here's what I have so far. I want to send the cart and get the question set in response:
QuestionStore: {
autoLoad: false,
model: 'RefCig.model.Question',
proxy: {
type: 'ajax',
url: '/refcig-services/questionsForCart',
actionMethods: {
create: 'POST',
read: 'POST',
update: 'POST',
destroy: 'POST'
},
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
reader: {
type: 'json'
},
writer: {
type: 'json'
}
}
}
On submit:
var cartStore = Ext.getStore('CartStore');
cartItems = Ext.Array.pluck(cartStore.data.items, 'data');
var questionStore = this.getStore('QuestionStore');
questionStore.load({params:cartItems});
A console.log of Ext.encode(cartItems) is exactly what I want to send to the backend:
[{
"id": 19,
"pricePerUnit": 20,
"denominationsPerUnit": 1,
"blahblahblah": 1,
"unitQuantity": 1,
"total_item_count": null,
"subtotal": 20
}]
Yet the request is malformed:
{
"0": {
"id": 19,
"pricePerUnit": 20,
"denominationsPerUnit": 1,
"unitQuantity": 1,
"total_item_count": null,
"subtotal": 20
},
"page": 1,
"start": 0,
"limit": 25
}
How should I be telling my QuestionStore to form its request body the way I want?
Thanks in advance.
Technically your requirement can be met by using a custom proxy. You implement your own buildRequest method in there, which is a stripped down version of the original one:
Ext.define('MyProxy', {
extend: 'Ext.data.proxy.Ajax',
alias: 'proxy.my',
paramsAsJson: true,
buildRequest: function(operation) {
var me = this,
params = operation.getParams(),
request, operationId, idParam;
operationId = operation.getId();
idParam = me.getIdParam();
if (operationId !== undefined && params[idParam] === undefined) {
params[idParam] = operationId;
}
request = new Ext.data.Request({
params: params,
action: operation.getAction(),
records: operation.getRecords(),
url: operation.getUrl(),
operation: operation,
proxy: me
});
request.setUrl(me.buildUrl(request));
operation.setRequest(request);
return request;
}
});
Then, in the store definition, you simply use the proxy:
proxy: {
type: 'my',
// .....
However, I would recommend another way.
Do something like:
questionStore.load({params: {cartItems: cartItems}});
instead of
questionStore.load({params:cartItems});
That will make the request body look like this:
{
"cartItems": [{
"id": 19,
"pricePerUnit": 20,
"denominationsPerUnit": 1,
"blahblahblah": 1,
"unitQuantity": 1,
"total_item_count": null,
"subtotal": 20
}],
"page": 1,
"start": 0,
"limit": 25
}
You would need to adjust your server side to retrieve the cartItems array from the payload.

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

Sencha touch2: How can i parse my nested json data?

i could not able to parse my nested json data and i tried in many ways but i could not succeed. any help is appreciated.
Here is my json output looks like:
[
{
"task": {
"locator": "FGWESD",
"subtask": [
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
},
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
}
],
"connectTime": "0",
"id": "0"
}
}
]
Here is my model:
Ext.define('MyApp.model.MyModel',{
extend:'Ext.data.Model',
xtype:'myModel',
config:{
fields:[
{name:'number',mapping:'work.number'},
{name:'id',mapping:'work.id'},
{name:'locator',mapping:'task.locator'},
{name:'gate',mapping:'work.gate'}
]
}
});
Here is the store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
config:{
model:'MyApp.model.MyModel',
storeId: 'id_Store',
// added the url dynamically inside the controller
proxy:{
type:'ajax',
reader:
{
type:"json",
rootProperty: 'subtask'
},
method: 'POST',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
}
}
}
});
Here is my controller code :
Ext.define('MyApp.controller.LoginController', {
extend: 'Ext.app.Controller',
requires: ['Ext.data.proxy.Rest'],
config: {
// My code is too long to add here so am adding store loading when user taps login button
},
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
var url = 'http://localhost:8080/apps';
segmentStore.getProxy().setUrl(url.trim());
segmentStore.load({
scope:this,
callback: function(records, operation, success){
if(success){
console.log('records: ',records);
console.log('records: '+records.length); // prints here 1
console.log('locator: '+records[0].getData().locator);
// prints FGWESD
console.log('locator: '+records[0].getData().number);
//prints undefined
//
}
}
}
)
},
});
Can any one please help me out. how can i get Values of number, gate, id and status?
What are the necessary changes have to be made in model, store and controller ?
Please help me out in resolving ? Thanks.
As I wrote in a comment, I don't think you can achieve that without manually parsing the data and loading it to the store. So the getDetails function should look like this:
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
Ext.Ajax.request({
url: 'http://localhost:8080/apps',
success: function(response){
var responseObj = Ext.decode(response.responseText);
var task = responseObj[0].task;
var locator = task.locator;
var subtasks = [];
Ext.each(task.subtask, function(subtask) {
subtasks.push({
number: subtask.work.number,
id: subtask.work.id,
gate: subtask.work.gate,
locator: locator
});
});
segmentStore.setData(subtasks);
}
});
}
Also, when using this method you should remove the mapping from your model, and you can get rid of the proxy definition of the store. Also, I'm not sure why you want to create the store in the "getDetails" and not define it in the 'stores' config of the controller, but maybe you have your reasons..
I didn't run the code, so there maybe errors, but I hope you get the idea.
I think the root property of your store should be:
rootProperty: 'task.subtask'