How to post Handsontable data into WordPress REST API? - json

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),

Related

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

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

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

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.

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).

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