I'm generating JSON response from PHP witch looks like this:
{ done:'1', options: [{ message:'Example message'},{message:'This is the 2nd example message'}]}
I want to grab these results using ExtJS. This is what I have so far:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"}
});
What do I have to write next to get the json results like this:
var mymessages = jsonData.options;
And mymessages should contain Example message and This is the 2nd example message.
Thank you.
The straightforward approach:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"},
success: function(resp) {
// resp is the XmlHttpRequest object
var options = Ext.decode(resp.responseText).options;
Ext.each(options, function(op) {
alert(op.message);
}
}
});
Or you could do it in a more Ext-ish way using Store:
var messages = new Ext.data.JsonStore({
url: 'myfile.php',
root: 'options',
fields: [
{name: 'text', mapping: 'message'}
],
listeners: {
load: messagesLoaded
}
});
messages.load({params: {id: "1"}});
// and when loaded, you can take advantage of
// all the possibilities provided by Store
function messagesLoaded(messages) {
messages.each(function(msg){
alert(msg.get("text"));
});
}
One more example to address the last comment:
var messages = [{title: "1"},{title: "2"},{title: "3"}];
var titles = msg;
Ext.each(messages, function(msg){
titles.push(msg.title);
});
alert(titles.join(", "));
Although I would prefer doing it with a Array.map (which isn't provided by Ext):
var text = messages.map(function(msg){
return msg.title;
}).join(", ");
alert(text);
Use the success and failure properties:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"},
success: function(response, callOptions) {
// Use the response
},
failure: function(response, callOptions) {
// Use the response
}
});
See the Ext API docs for more details
check this sample fiddle which is for Ext JS 4. http://jsfiddle.net/mrigess/e3StR/
Ext 4 onward utilizes Ext.JSON.encode() and Ext.JSON.decode() ; while Ext 3 uses Ext.util.JSON.encode() and Ext.util.JSON.decode()
if you are sure that your input is correct (beware of xss attacks) you can use the eval() function to make your javascript object from your json result, which can then be accessed through your command:
var mymessages = jsonData.options;
But then again, Ext does that nicely for you, as Rene has pointed out through the Ext.decode function
Related
I have to veryfiy the response of the ajax call in my sencha test.
plz advise how to do it.. below is my sample code
beforeEach(()=> {
sim = Ext.ux.ajax.SimManager.init({});
controller = Ext.create('xxxx.controller.Search');
AutoLink = Ext.create('xxxx.model.search.AutoLink', {
objectType: 'myobj'
});
});
it('Should run processResponse when doSearch executes', function() {
const callback = () => {};
sim.register({
'abc.com/myurl.aspx': {
status: 401,
responseText: JSON.stringify({
'success': true,
'data': [{
'autoLink': false, 'status': 'OK', 'objectType': 'Person',
'results': [{ 'ref': 12345, 'managedBy': '01', 'ethnicAppearance': '1', 'gender': '1', 'rules': ['Forename, surname','nickname, DOB']}],
'gridDescriptor': [{'fields': [{'name': 'surname','text': 'Surname','width': 100}],
'sortOrders': ['surname','forename1']
}]
}]
})
}
});
spyOn(controller, 'doSearch'); // internal method which calls the Ext.Ajax
spyOn(controller, 'processResponse'); // internal method which process the response
controller.doSearch(AutoLink, callback, this); // making an ajax call
setTimeout(function () {
expect(controller.processResponse).toHaveBeenCalled();
}, 1000);
});
now when run the test case processResponse gets called, which is fine, but i want to verify the ajax response.
This is how I am doing it:
$.ajax({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('Test%203')/items(" + itemId + ")/FieldValuesAsText",
method: 'GET',
headers: {
'accept': 'application/json;odata=verbose'
}
}).then(function (data) {
console.log(data);
}
I don't know if this will help you to achieve exactly what you are looking for. But I would suggest giving it a shot. Then you can go to your console and save the data object to a variable (just for debugging purposes) or just from the console itself look at the object chain and check the data which was returned by your ajax call. So in my case I would find let's say name of the employee here:- data.d.results[0].PreferredName. Then if I want to use it I can just save it in a variable. Make sure you do it in the 'then' function. Here's a sample for save the name to a var:
.then(function (data) {
empName = data.d.results[0].PreferredName;
}
I come to you today with maybe a noob-ish question. I'm trying to parse a JSON response from the server on my client side but I seem to have hit a wall as I can't actually acces the data inside of it. Here's the JSON content I'm trying to go through. I just need the name as in name:"Topic3"
'{
links: [ ],
content: [
{
links: [ ],
content: {
name: "Topic3",
technology: {
name: "Java",
technology_id: 1
},
topic_id: 3
},
id: null
},
],
id: null
}'
Any help would be greatly appreciated. Also this is my JS code that I tried to work on it with.
$.ajax({
type:'GET',
dataType: 'json',
url: "technologies/"+ option+ "/topics"
}).then(function(data)
{
for(i=0;i<data.content.length;i++)
{
var topic = document.createElement("button");
var content= (Object.keys(data.content[i]));
topic.name= content.content.name;
AddTopic.appendChild(topic);
}
});
To set button text use innerHTML property
var topic = document.createElement("button");
var content = data.content[i];
topic.innerHTML = content.content.name;
AddTopic.appendChild(topic);
So I'm assuming you need to iterate through and find every available topic - in that case I believe this should work
$.ajax({
type:'GET',
dataType: 'json',
url: "technologies/"+ option+ "/topics"
}).then(function(data)
{
for(i of data.content)
{
var topic = document.createElement("button");
topic.name= i.content.name;
AddTopic.appendChild(topic);
}
});
Here is what my Ajax post looks like:
$.ajax({
type: "POST",
url: "/create",
data: {
"question": $('#question').val(),
"options": options
},
success: function() { window.location.href="/view"; }
});
Fairly simple. options is an array of string charachters. The problem is, when I receive on the server end with Hapijs, the request payload shows this object received:
{
question: "..etc..",
"options[]": [..etc...]
}
Why does it add a [] to the options variable name? Normally this wouldn't be a problem for me, but when I do the same thing and simulate a server request in my lab test like this:
var test = [..etc..]
// Simulate POST request
var serverOptions = {
method: 'POST',
url: '/create',
payload: {
question: 'Question',
options: test
}
};
It shows that the variable name received is just "options", not "options[]". How can I get jquery to stop adding the [] to the variable name when POSTing? Thanks
I want to create a multidimensional array from the values I retrieved on an ajax post request.
API response
[{"id":"35","name":"IAMA","code":"24"},{"id":"23","name":"IAMB","code":"08"}]
jQuery code
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr[key]['id'] = value.code;
mulArr[key]['text'] = value.name;
});
}
});
Syntax error
TypeError: mulArr[key] is undefined
I can properly fetch the data from the endpoint, the only error I encounter is the one I stated above. In perspective, all I want to do is simply a multidimensional array/object like this:
mulArr[0]['id'] = '24';
mulArr[0]['text'] = 'IAMA';
mulArr[1]['id'] = '08';
mulArr[1]['text'] = 'IAMB';
or
[Object { id="24", text="IAMA"}, Object { id="08", text="IAMB"}]
It happens because mulArr[0] is not an object, and mulArr[0]['id'] will throw that error. Try this:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr.push({id: parseInt(value.code), text: value.name});
// or try this if select2 requires id to be continuous
// mulArr.push({id: key, text: value.name});
});
}
});
Alternative to using push (which is a cleaner approach) is to define the new object.
mulArr[key] = {
id: value.code,
text:value.name
};
Another way of achieving what you want would be this one:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
mulArr = data.map(value => ({ id: parseInt(value.code), text: value.name }));
}
});
This is cleaner and also uses builtin map instead of jQuery $.each. This way you also learn the benefits of using the map function (which returns a new array) and also learn useful features of ES2015.
If you cannot use ES6 (ES2015) here is another version:
mulArr = data.map(function (value) {
return {
id: parseInt(value.code),
text: value.name
};
});
I guess you can already see the advantages.
I want to get data from server and suggest with typeahead.
I get my data from list to an usl like /foo/q=QUERY and this query return json like ["salam","bye", "khodafez,].
How i can use from bootstrap typeahead to suggestion.
I try this code:
<script type="text/javascript">
$(document).ready(function() {
$("#vahid").typeahead({
// ???
});
});
</script>
According to the documentation, you just provide a function for source in the options:
$("#vahid").typeahead({
source: function(query, process) {
// `query` is the text in the field
// `process` is a function to call back with the array
$.ajax({
// Your URL
url: "/foo",
// Your argument with the query as its value
data: {q: query},
// Success callback -- since it expects the first
// parameter to be the data, and that's what the
// success callback is called with, you can just
// use `process` directly
success: process
});
}
});
The above assumes that the response correctly identifies the response as Content-Type: application/json. If it doesn't, add
dataType: "json"
...to your ajax options.
I'm using the asynchronous mechanism because you're querying a server. If you already had the data client-side, you could simply return it from the source function directly. But they (intelligently) don't require you to retrieve it synchronously from the server, as that would lead to a bad XU.
Accourding to docs https://github.com/tcrosen/twitter-bootstrap-typeahead
you can add ajax attr like :
$('#myElement').typeahead({
ajax: '/path/to/mySource'
});
or
var mySource = [
{ id: 1, name: 'Terry'}, { id: 2, name: 'Mark'}, { id: 3, name: 'Jacob'}
];
$('#myElement').typeahead({
source: mySource
});
for local data