I'm a bit of a newb with both extJS and json. What is the most painless route to POSTing json data using extJS? I'm not really interested any GUI features, just using the framework to send some sample data.
Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: passFn, // function called on success
failure: failFn,
params: { foo: 'bar' } // your json data
});
The following will identify as 'POST' request
Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: passFn, // function called on success
failure: failFn,
jsonData: { foo: 'bar' } // your json data
});
The following will identify as 'GET' request
Ext.Ajax.request({
url: 'foo.php', // where you wanna make the get request
success: passFn, // function called on success
failure: failFn,
params: { foo: 'bar' } // your json data
});
Just to add my two cents:
//
//Encoding to JSON:
//
var myObj = {
visit: "http://thecodeabode.blogspot.com/"
};
var jsonStr = Ext.encode(myObj);
//
// Decoding from JSON
//
var myObjCopy = Ext.decode(jsonStr);
document.location.href = myObj.visit;
The examples posted here show the basic idea. For complete details on all configurable options see the Ext.Ajax docs.
Code Snippet:
Ext.Ajax.request({
url: "https://reqres.in/api/users",
success: function (response) {
Ext.Msg.alert("success", response.responseText);
},
failure: function () {
Ext.Msg.alert("failure", "failed to load")
},
params: {
"name": "morpheus",
"job": "leader"
}
});
Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/28h1
Related
I have trouble storing a JSON file in my DynamoDB table with the help of my Lambda function and my API Gateway on AWS. I have the following piece of code which gets executed once I press a button on my HTML site:
$('#submit').on('click', function(){
var example = {"number":"121212"};
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify(example),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
When pressed the website reloads, hence I assume function has successfully executed. However my problem is that the data does not arrive in the correct format in the lambda function and hence does not execute properly. When checking in CloudWatch it is shown as { number: '121212' } instead of {"number":"121212"}. Any idea how I can make sure that the value 'arrives' has a valid JSON format in my Lambda function?
Here's my Lambda function:
exports.handler = function index(e, ctx, callback) {
var params = {
Item: { number: e.number },
TableName: 'collectionOfNumbers'
};
docCLient.put(params, function(err, data) {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
});
}
If I'm reading this right, e.number is the value of the JSON parameter 'number' that you are passing in, e.g. '121212'. I'm making the assumption from the usage that docClient is putItem under the hood.
I think your Item param should look like:
Item: {"number": {N: e.number}}
See AWS Docs for info regarding PutItem https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html
I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:
$.post("http://api-adress/controller",
{
email: input_mail,
password: input_pw
},
function(data, status){
alert(data);
alert(status);
}, 'json');
I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.
I would suggest to change a little bit your code like below:
var dataString = {
email: input_mail,
password: input_pw
}
$.post("http://api-adress/controller", dataString, function (result) {
})
.done(function (result) {
//Here is your result. You must parseJSON if it is json format
var data = jQuery.parseJSON(result);
})
.fail(function () {
//use this if you need it
})
Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.
paypal.Button.render({
payment: function() {
var booksPurchaseRequest = {};
booksPurchaseRequest.amount = 20;
return paypal.request
.post(CREATE_PAYMENT_URL, JSON.stringify(booksPurchaseRequest))
.then(function(data) {
return data.paymentId;
});
}
}, '#paypal-button');
In such approach on back-end server I'm receiving data in application/x-www-form-urlencoded format, but I need application/json. How can I achieve that? Can paypal.request.post() be replaced with simple $.ajax()?
return paypal.request({
method: 'post',
url: '/foo/bar',
json: {
foo: 'bar'
}
}).then(function(response) {
})
Or you can just use jQuery, you just need to return a promise
I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)
I am unable to Deserialized my JASON Serialized FormData
Please review my code
///here its my JSON
$("#btn_pro_spc").click(function () {
var formdata = $("#Product_spec_from").serialize();
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: { formdata : formdata },
datatype:'json',
success: function (data) {
}
});
});
///here it controller
public JsonResult UpdateProductSpecification(string formdata)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
LabCheckingModel LCModel = jss.Deserialize<LabCheckingModel>(formdata);
return Json(jss);
}
I Am getting serialized data perfectly but unable to Deserialized :(
Invalid JSON Primitive
It is not necessary to use use JavaScriptSerializer to deserialize your model. The DefaultModelBinder will do all this for you. Change the script to
$("#btn_pro_spc").click(function () {
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: $("#Product_spec_from").serialize(), // change this
datatype:'json',
success: function (data) {
}
});
});
and change the controller method to
public JsonResult UpdateProductSpecification(LabCheckingModel model)
{
// the value of model will be correctly bound
return return Json(??);
}
Side note: not sure what you are trying to return (currently its an instance of JavaScriptSerializer which does not make sense)