How to make ajax call in extjs and display the json value inside div? - extjs3

I am new in extjs. I need to know how to make ajax call in extjs and display the json values in inside div. I don't need to use grid..

In ExtJS, you will have to use the Ext.Ajax class to make ajax calls to a remote server. Following is a typical code showing how to do it:
Ext.Ajax.request({
url: 'ajax_demo/sample.json',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
In case of HTTP success (200 OK), the control will go inside the success callback and the first things that we have to do is decode the response.responseText which will give you the JSON response coming from the back-end data source.
Once you have code the JSON, you are free to format it and add it to any element (say to a div in your case). In case you want to format the JSON data nicely before adding, you may do that using Template/XTemplate.

I have used something like this.
$.getJSON('somepathtoserver/somefile.php?callback?', variable,function(res){
});
In the somefile.php, I have a callback function that processes and return the value to the js function.
like this:
{
echo $_GET['callback']. '(' . "{'someValue' : $calculatedVariable}" . ')';
}
This is tricky, but very useful when trying to ajax from one server to a different server, which is the reason I would use JSON here and not just a straight AJAX request.

Related

Axios's response, what's in it??.....const response = await axios

I'm using Axios in WP e.g.
const response = await axios.delete(universityData.siteURL + "/wp-json/wp/v2/note/" + thisNote.getAttribute("data-noteID"))
All works fine but what I don't understand is the structure / content of 'response'. How do I interrogate 'response'? I had assumed for instance if I did console.log('Axios response: ' + response.data) I'd get a nicely laid out JSON like OO output in the Chrome console panel. But all I see is: Axios response: [object Object]
I can do this response.data.userNoteCount and I get something sensible back. BTW 'userNoteCount' is a field I added to my JSON for my custom post type. But how else do I see all the content of response without specifically having to target it?
Thanks to another contributor elsewhere this is the answer:
When you do the console.log you're adding the JSON object to the
string of Axios Response, so the JSON object is being converted to a
string, hence the object Object.
If you do it as two seperate lines, like
console.log('Axios Response');
console.log(response.data);
Then it will be outputted as the actual object.
With it being an HTTP Request though, rather than outputting it into
the console, what I'd do is open the Network tab of the browser
development tools, and select the XHR tab, and then the request will
appear in there and you can inspect the full response body there
without having to log it.

Empty MultipartFile[] when sending files from Vue to SpringBoot controller

I'm doing a program that will help me to make monthly reports and I stuck at uploading photos which I need for one kind of the reports. For some reason, it doesn't get an array in the controller.
I use Springboot RestController at the backend and Vue with BootstrapVue and vue-resource on the other side.
index.html (BootstrapVue):
<b-form-file
v-model="photos"
accept="image/*"
multiple
placeholder="..."
></b-form-file>
<b-button #click="uploadPhotos">Upload</b-button>
inside vuemain.js:
data: {
photos: null,
},
methods: {
uploadPhotos(){
var formData = new FormData();
formData.append("photos", this.photos);
this.$http.post('reports/photo', formData).then(result => {
...
})
}, ...
inside Controller:
#PostMapping("/photo")
public void addPhoto(#RequestParam("photos") MultipartFile[] photo) {
System.out.println(photo.length); // shows 0
}
what I see inside Params at browser:
XHRPOSThttp://localhost:8080/reports-maker/reports/photo
[HTTP/1.1 500 326ms]
Request payload
-----------------------------4469196632041005505545240657
Content-Disposition: form-data; name="photos"
[object File],[object File],[object File],[object File]
-----------------------------4469196632041005505545240657--
​
So for some reason at this point #RequestParam("photos") MultipartFile[] photo it's empty array. But if I change it to just one photo like this: #RequestParam("photos") MultipartFile photo and send one from js: formData.append("photos", this.photos[0]); everything works nicely and photo gets uploaded to the server.
It's my first experience with Vue and to be honest I don't want to go deep into JS learning, so probably there is some silly mistake somewhere. Any way I can use a loop in JS method to upload them one by one, but that would be so ugly. I hope there is a better way to do it (without any additional JS libraries of course).
If you use axios then you should add header
var headers = {
'Content-Type': 'multipart/form-data',
};
axios.post(
'reports/photo',
formData,
{
headers: headers,
}
)
...
to be able send files to the server.
I agree, sending files in separate requests one by one is very "ugly", but I also don't like the idea of not using the mapping resources of Spring Boot, having to send all files with different names (seems disorganized) and having to work with MultipartHttpServletRequest, but there is a simple solution for this: Ian's answer to this question (not realy related to Vue.js, but useful) worked for me:
In order for Spring to map items in a request to a list, you need to provide the same name (in the FormData.append calls) for each item when appending to the form data. This allows Spring to effectively see the request as name=value1&name=value2&name=value3 (but obviously in the form of form data). When Spring sees the same key ("name") multiple times, it can map the values into a collection.
In your .vue file, append the photos with the same name:
for (let i = 0; i < this.photos.length; i++) {
formData.append("photos", this.photos[i]);
}
And in your Controller:
#PostMapping("/photo")
public void addPhoto(#RequestParam("photos") MultipartFile[] photo) {
System.out.println(photo.length); // Should be greater than 0 now
}
Note:
I used Vue Axios to consume my API and manually added the Content-Type: multipart/form-data header. Make sure its in your request header list.
I found an acceptable solution here https://stackoverflow.com/a/33921749/11508625 Rossi Robinsion's code works nicely. At least it looks better than sending files in separate requests one by one.
The answer is based on using getFileNames() which helps to iterate on files inside a request even if they are not in the array.

Getting a specific data from HTTP body response

I am sending some data to my api by post and when it successfully submitted, it will return some data and I want to access the response data.
This is what I've got from my component :
this.http.post(this.restProvider.restApiUrl+'saveDraft', draftData, options)
.subscribe(data => {
console.log(data["_body"]);
}, error => {
console.log("Oooops!");
});
The console.log(data["_body"]); will resulting this data :
{"status":"ok","data_id":"2","statusMsg":"Saved as draft"}
What I'm trying to do now is to access the value of data_id but I'm not really sure how to get it inside my component. I thought it can be accessed by something like data["_body"]["data_id"]
I think data is an object. Try this:
console.log(data._body.data_id);
console.log(data["_body"].data_id);
Finally, I solved the issue by changing the console.log(data["_body"]); to console.log(data.json().data_id);
I refer to this discussion Angular 2: How to access an HTTP response body? and tried to apply the JSON and it works.

Ember js RESTAdapter PUT request adds .json to the end

I've been trying to learn Ember and I have a question.
In my store I'am getting data from .json like below. I have tried without buildUrl function but cant load the json file, then found this solution on SO.
CocktailApp.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.extend({
bulkCommit: false,
url: "http://localhost:8888",
buildURL: function(record, suffix) {
var s = this._super(record, suffix);
return s + ".json";
}
})
});
Now comes my question: When I commit the chances (by pressing add to favs or remove from favs) RESTAdapter adds ".json" at the end of to PUT request. See the below code and screenshot
CocktailApp.CocktailController = Ember.ObjectController.extend({
addToFav: function () {
this.set('fav',true);
this.get('store').commit();
},
removeFromFav: function () {
this.set('fav',false);
this.get('store').commit();
}
});
I think thats why my PUT request can not be handled. But If I remove the builtURL function no json loaded at all. How can I resolve this problem?
Thanks
If the API endpoint url does not require .json at the end of it, then remove that line from your buildURL function. My guess is that the example code you got was consuming a ruby on rails api, or something similar.
remember, when you send a GET, PUT, POST, or DELETE to a url, that url needs to actually be a real endpoint. You can't just add extraneous stuff to it and have it still work.

Can we add Json object to RequestHeader of HTTP GET method

I am developing a new REST-full webservice for our application,I wanted to send the reqest data in requestHeader instead of sending as query param, as my request data is large.
I have My jquery code like below to add json to the request header and call the REST service GET method.
$.ajax({
beforeSend: function(req) {
req.setRequestHeader("test", "{name:mouli, id:918}");},
type : "GET",
data :'',
dataType : "jsonp",
url : 'http://localhost:29801/RestFulJSONExample/rest/jobdesc?callback=?',
success : function(data) {
alert("invoked");
}
});
});
And my GET method in my REST service is like
#GET
#Produces("application/javascript")
public JSONWithPadding getJobDescription(#Context HttpHeaders headers) {
List<String> requestHeader = headers.getRequestHeader("test");
//some logic here.
}
i could able to get the JSON object from the request header which i have added in the jquery request.
My question is ..
Can i follow this approach? is it secure and safe?
If not please tell me the other way?
What appears at the right side of the ":" in a header is mostly free. You have to take into account character set restriction in HTTP, and possible carriage returns in the JSON value (you know, headers of more than one line have a specific syntax). If your JSON examples are relatively simple, then I see no problem in that. It is just another way of organizing the actual value of a header line.