Sencha touch2: make Ajax post request for Json data - ajax

hi am new to Sencha touch2, am facing problem while fetching data from a remote url. When i use the url in simple rest client am able get data and with status: 200 ok. Here is input of simple rest client for your reference.
---------------
url: http://190.40.2.14:9030/work
Method: post
Headers:Accept: application/json
Data:<workTO><platform>ALL</platform></workTO>
---------------
how can i use post request, headers and data how can i do this in Sencha touch2.
here is the model with proxy:
Ext.define('TestApp.model.myModel', {
extend: 'Ext.data.Model',
xtype:'modelList',
config: {
fields:['work'],
proxy:{
type:'rest',
// url:'http://localhost:9090/TestApp/app/store/sample.json',// this works
url:'http://10.30.2.141:9030/work',
reader:
{
type:'json'
}
}
}
});

Ext.define('TestApp.model.ModelList', {
extend: 'Ext.data.Model',
xtype:'modelList',
config: {
fields:['task'],
proxy:{
type: 'ajax',
url:'http://localhost:9090/TestApp/app/store/sample.json',
callbackKey: 'theCallbackFunction'
},
reader: 'json'
}
});
you json should have relative path, not absolute for ajax to work, cross domain can be achived via JSONP but you need to setup api with callback feature else it wont work

Related

Cypress: Should new cy.intercept() method mock responses for requests sent not from browser, but using cy.request() method?

I am creating an end to end test, where some specific data should be retrieved via API using
cy.request({
method: "POST",
url: ...,
headers: {
"X-Auth-Token": ...,
},
body: {
target_url: ...,
},
});
For now my API can't send me the data, so while it is being fixed I had an idea to mock this request using
cy.intercept(
{
method: "POST",
url: ...,
},
{
body: {
target_url:
...,
},
}
So I can set all necessary data into the body to stub response
But it just does not work for me now, I read carefully all the docs, but still I can't understand - cy.intercept does not work for cy.request or I just made an error somewhere?
Thank you for any information =)

How can I get content type from response when there is a proxy ajax call in extjs?

In the below code, I make a proxy ajax call to the server. When the session is active, I receive the expected json format but when the session is inactive, I receive a html file as response.
Ext.define('ExtDashboard.model.data', {
extend: 'Ext.data.Model',
fields: [],
proxy: {
type: 'ajax',
url : 'users.json',
reader: {
type: 'json',
rootProperty: 'root',
success : 'success',
transform: function(data) {
//perform operations on data
return data;
}
}
}
});
The response html will have some text that shows the session as inactive. So I read the string from html and do further actions like redirecting to login page. But I am not sure how to get response here and extract content type especially when the response received is html instead of json
IMHO it is better to check the http response status code in the proxy's exception event handler. Something like this:
proxy: {
type: 'ajax',
url: '/data.json',
reader: {
type: 'json',
rootProperty: 'data'
},
listeners: {
exception: function (proxy, response, operation) {
// 401 - Unauthorized
// 440 - Login Time-out
if([401, 440].indexOf(response.status) > -1) {
// Do something i.e. redirect to login page.
};
}
}
}

DataTables Editor In MVC

I want to use DataTables Editor but I want full control over the post back rather than letting Editor-Server handle it. Is there a way to do this? I am able to specifiy the url in Ajax on the client side and it does post back to the Controller, the only problem is I cannot figure how to get the data out of the call.
This is the Ajax portion:
$(document).ready(function () {
editor = new $.fn.dataTable.Editor({
ajax: ({
url: "/../AnyController/Update",
dataType: "json",
contentType: "application/json",
type: 'POST'
}),
formOptions: {
inline: {
onBlur: true,
submit: 'all'
}
},
table: "#timetracker",
fields: [
{
label: "Date1:",
name: "Date1"
},
{
label: "Comment 1:",
name: "Comment1",
type: "textarea"
}
]
});
And this is the Contoller method:
[HttpPost]
public JsonResult Update(EditorReturnData wtd)
{
return Json(wtd);
}
I have tried using a variety of other method signatures but the value of wtd is always null. I have no problem loading the table just by passing Json data, but how to takeover the update process from datatables editor is eluding me.
I have one update. I could not figure out how the Get, Post and Put could all use the same Controller Method and the method takes no parameters, even for the Post and Put. Finally I figured out that Editor is passing the data in the Header and it could be accessed with Request.Body. From there it must be the Datatables dll that is doing the actual updates.
enter code hereI have found the best way to do this is to post back from ajax to a different Controller for Post and Put and you can get access to the return data from the HttpRequest body in the following manner.
public ActionResult Rest(HttpRequest request)
{
var stream = request.Body;
string url = new StreamReader(stream).ReadToEnd();
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
I added this code to the RestController from the Datatables Dot Net Core Demo Rest example which can be downloaded from https://editor.datatables.net/
The Ajax looks like this
editor = new $.fn.dataTable.Editor( {
ajax: {
create: {
type: 'POST',
url: '/api/rest/create'
},
edit: {
type: 'PUT',
url: '/api/rest/edit'
},
remove: {
type: 'DELETE',
url: '/api/rest/remove'
}
},

Call Asp.Net MVC action to load store in sencha touch

I am calling asp.net action from proxy to fill the store data.
I am specifying the url correctly but on make get request to Action it is appending query string params to the call. This is resulting in 404 error.
I am posting my code below,
Asp.net mvc Action
public JsonResult SongsList()
{
List<MusicFileModel> musicFileModels = MusicFileModel.GetAllMusicFiles();
return Json(musicFileModels, JsonRequestBehavior.AllowGet);
}
Store definition in Sencha Touch 2
Ext.define('CloudPlayerUI.store.Songs', {
extend: 'Ext.data.Store',
config: {
model:'CloudPlayerUI.model.song',
proxy: {
type: 'ajax',
url: '/Home/SongsList',
param:'',
reader: {
type: 'json'
}
},
autoLoad:true
}
});
This is the ajax call that is made.
GET http://localhost/Home/SongsList?_dc=1333338051329&page=1&start=0&limit=25
I am assuming that because, Action doesn't have any params which is being made my ajax call
it is resulting in an 404 error.
I am not sure the correct way of calling mvc action. Please let me know if I am going wrong.
Any help is appreciated.
update:
I tried adding the same query string params to asp.net mvc action. Still it is causing 404 error. When I open the same url without any query string params in new tab it is returning me Json result.
I figured out the issue.
The 404 error was due to incorrect URL config param defined in the store. Also I added a rootProperty to reader.
This is how the proxy code looks like.
Ext.define('CloudPlayerUI.store.Songs', {
extend: 'Ext.data.Store',
config: {
model:'CloudPlayerUI.model.song',
proxy: {
url: 'Home/SongsList', //Changes to url
type:'ajax',
reader: {
type: 'json',
rootProperty: 'ResponseData' //Addeed reader property.
}
},
autoLoad:true }
});
Constructing return object in Asp.MVC action.
var results = new
{
Success = true,
ResponseData = musicFileModels
};
return Json(results, JsonRequestBehavior.AllowGet);

ajax problem with sencha touch

I am trying to submit a form using ajax in the sencha touch framework. It's a simple form that asks for a user's name, email address, and a brief message. I then want to post the data to a php script that simply emails the data to me.
The problem I have is when I try to submit the form I get the following error:
"SyntaxError: Unable to parse JSON string"
The code to send the request is as follows:
var userName = name.getValue();
var userEmail = email.getValue();
var userMessage = message.getValue();
Ext.Ajax.request({
url:'path/to/phpfile.php',
jsonData:{"name":userName, "email":userEmail, "message":userMessage},
method:"POST",
success:function(){
alert("Success!");
},
failure:function(){
alert("Error");
}
});
The error occurs in the sencha touch framework on line 14583, which is
Ext.util.JSON = {
encode: function(o){
return JSON.stringify(0);
},
decode: function(s){
return JSON.parse(s); //this is line 14583
}
};
I'm just starting to learn Ext and sencha touch so could someone please point in the right direction here? Any threads/tutorials/examples would be greatly appreciated.
Thanks in advance
Maybe your Server uses Content Negotioation. In this case it respects the Request-Header-Parameter Accept, which is Accept: */* in your case. So the Server sends your Script HTML or XML which can't be read as JSON.
Change your Code to the following:
Ext.Ajax.setDefaultHeaders({
'Accept': 'application/json'
});
Ext.Ajax.request({
url:'path/to/phpfile.php',
params:{"name":userName, "email":userEmail, "message":userMessage},
method:"POST",
success:function(){
alert("Success!");
},
failure:function(){
alert("Error");
}
});
Source: http://www.sencha.com/learn/legacy/Manual:RESTful_Web_Services
What happens if you change the Ajax Request to the following.
Ext.Ajax.request({
url: 'php/file.php',
method: 'post',
params: { id: idvar, data1: Ext.encode(schouw), data2: Ext.encode(opmerkingen) },
success: function(response) {
//Reponse
}
});
In my own application this, direct, encoding of the data to JSON works great.
Are you sure the var's you are sending are filled with data? Within my application I use the below code to substract data from the input values (slightly different);
formID.getValues().inputFieldID

Resources