I'm working on one project with AngularJs(1.5) and Codeigniter rest server. I'm wondering why data idTag isn't passed to php? Let me show you my code and explain further with comments.
I have this factory
factory.get = function(idLocation, idTag){
console.log(idLocation, idTag); //Console log outputs 1 6, so data is here
return $http({
method: 'GET',
url: $location.protocol() + '://' + $location.host() + '/rest/api/locationtag/locationtag/' + idLocation,
data: {
idTag: idTag
}
}).then(function successCallback(response){
console.log(response);
// response is empty, because data isn't sent to PHP
return response.data;
},function errorCallback(response){
console.log('Error getting slide shows: ' + response.data.message);
});
};
And this is my PHP where i try to fetch the code
public function locationtag_get($idLocation)
{
$condition['id_location'] = $idLocation;
$condition['id_tag'] = $this->get('idTag');
var_dump($condition);
die();
$locationTag = $this->locations_tags->get($condition);
if ($locationTag) {
$this->response($locationTag, REST_Controller::HTTP_OK);
}
}
Out put of var_dump is
'id_location' '1'
'id_tag' null
SO the question, why or how to properly send data from GET method to PHP rest controller in Codeigniter?
If you need any additional information's, please let me know and i will provide. Thank you in advance!
For GET requests you should use params instead of data (which is for POST requests). You can confirm this in the AngularJS documentation.
params – {Object.} – Map of strings or objects which
will be serialized with the paramSerializer and appended as GET
parameters.
Of course, nothing stops you from adding them to the URL but you'd have to deal with encoding the information properly instead of just passing the JSON object.
You should be using a params property in your $http config object:
$http({
url: $location.protocol() + '://' + $location.host() + '/rest/api/locationtag/locationtag/' + idLocation,
data: {,
method: "GET",
params: {idTag: idTag}
});
This will append as query string to you url, which you can then inspect in your server side code.
Related
Let me explain: My purpose is to create moodle users from a web app.
I am implementing a web app on Tomcat 8.0.15.0. That is, I use java servlets on the server side. Many JSP files and javascript, with much of it in jQuery, resides on the client side.
On the other hand, on another server, I have a test moodle installation. Via site-administration> plugins> web services> external services, I created a ws that enables the core_user_create_users function. Also created a token to access this ws, and put the admin user as authorized user.
And then, typed the following URL on Chrome:
https://mysyte.com/webservice/rest/server.php?wstoken=780f8b3a1164163d4dc00a757071194e&wsfunction=core_user_create_users&moodlewsrestformat=json&users[0][username]=testuser&usr[ [email] =john#smith.com&users [0] [password] = XXXXXX
And it worked. It returned a blank page, with the text
[{"id": 1, "username": "testuser"}]
Thus creating a user in moodle.
My question is: How can I do this from java?, or from javascript?, or from jQuery even better.
And if not, from PHP, I guess I would have no problem calling it from java, or javascript, or jQuery.
My Wrong Hint: In another part of the application I used, in javascript, the call $.getJSON() successfully. That's why I thought would also serve me in this case. But no success now, when the mozilla debugger reaches the call, it hangs.
Any feedback will be most welcome.
The call looks like
function create_moodle_user(username,firstname,lastname,email,password) {
var url = "https://mysyte.com/webservice/rest/server.php?"
+ "wstoken=780f8b3a1164163d4dc00a757071194e" + "&"
+ "wsfunction=core_user_create_users" + "&"
+ "moodlewsrestformat=json" + "&"
+ "users[0][username]=" + username + "&"
+ "users[0][firstname]=" + firstname + "&"
+ "users[0][lastname]=" + lastname + "&"
+ "users[0][email]=" + email + "&"
+ "users[0][password]=" + password;
$.getJSON(url, function(data) { // should return [{"id":4,"username":"testuser"}]
// this point is never reached
if (data.length < 64) {
}
else {
}
});
}
Finally, it worked by changing the call and the way how parameters were passed.
function create_moodle_user(u,f,l,e,fn) {
var domainname = 'https://my.moodle.site.com';
var data = {
wstoken: '780f8b3a1164163d4dc00a757071194e'
wsfunction: 'core_user_create_users'
moodlewsrestformat: 'json',
users: [
{
username:u,
password:'xxxxxxxx',
email:e,
firstname:f,
lastname:l
}
]
};
var response = $.ajax({
type: 'GET',
data: data,
url: domainname + '/webservice/rest/server.php'
});
// pass the function parameter
response.done(fn);
}
And this worked!
My problem now is to get user info, since I don't know how to get the response from core_user_get_users_by_field.
This is what I have:
function get_moodle_user(u,fn) {
var domainname = 'https://my.moodle.site.com';
var data = {
wstoken: '780f8b3a1164163d4dc00a757071194e'
wsfunction: 'core_user_get_users_by_field'
moodlewsrestformat: 'json',
field: 'username',
username:u
};
var response = $.ajax({
type: 'GET',
data: data,
url: domainname + '/webservice/rest/server.php'
});
console.log(response); // this does not show the result data
// pass the function parameter
response.done(fn);
}
Any ideas, please?
I have ajax connection with controller
function changeEmail() {
$.ajax({
...
contentType: "application/json",
dataType: "json",
...
error: function (error) {
var obj = error.responseText;
console.log('Error: ' + obj);
console.log('Obj length: ' + obj.fieldErrors.length);
}
});
}
Which in case of error returns a list of errors in json.
However, he is not able to refer to this list.
https://zapodaj.net/e6354b8c71f4c.png.html
I do not know, for example, how to refer to the first element of a list to the
message
variable
Depending on the content-type response from your server, the default response type is probably text/html or some other incorrect content-type.
You have two ways to fix this.
First, you can set obj = JSON.parse(error.responseText)
or, you can make sure that the server sets the correct content-type on errors as well.
I'm trying to remove the value of a custom field on an asana task via a PUT request.
Based on the original json data I sent over to create the task with a custom field value and the documentation here this is my best guess for how this should look:
let data = {custom_fields: { ASANA_CUSTOM_FIELD_ID_NUMBER: null }}; //struggling here
updateTask(ASANA_TASK_ID_NUMBER, data);
function updateTask(id, data) {
return put(`https://app.asana.com/api/1.0/tasks/${ASANA_TASK_ID_NUMBER}`, data);
}
function put(url, data) {
return makeRequest({
"url": url,
"headers": {"Authorization": "Bearer " + accessCode()},
"type": "PUT",
"data": data
})
}
But I get the error:
status:400 Bad request
custom_fields: Value cannot be an array: []
Which seems verbose enough to solve except I've tried every format i can come up with and I've had no luck working it out. I know that the put function works fine for updating other fields for a task and I see the same error with an actual number other than null.
You will need to send your content in JSON rather than urlencoded data. This is a bit of a bug in Asana API in my opinion. They say that they support form-encoded content however it doesn't like it when you try to send an object as it thinks it's an array.
I'm not sure why, but setting custom fields seems to be different from the rest of the API requests.
Here is some code that works for setting it, you can probably figure out how to apply this to whatever language you're using:
function SetCustomField(taskId, fieldId, value) {
// not sure why, but to set the custom task you have to tell it your content type is json,
// then send json as a string instead of letting it serialize it for you
var headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer API-KEY'
};
var formData = '{"data": { "custom_fields": { "' + fieldId + '": ' + value + '} } }';
var options = {
'method': 'put',
'headers': headers,
'payload': formData
};
var response = UrlFetchApp.fetch('https://app.asana.com/api/1.0/tasks/' + taskId, options);
//Logger.log(response.getContentText());
}
For my current project Java/Spring project I have to validate a form. The webpage is a freemarker template file.
The <form> has no special attribute to send the data to the controller. The project uses Ajax to send the request. The controller doesn't receive the form at all.
When the user submits the data, a JavaScript function is called to receive all the data by collecting the elementID's. The data is put in a variable, like this (short version);
var userId = document.getElementById('input_id').value.toLowerCase();
var width = document.getElementById("width");
var height = document.getElementById("height");
The function then puts all the data into a JSON. This JSON is put in the Ajax, and then Ajax calls the right controller.
**Ajax code **
$.ajax({
url: url,
type: "POST",
dataType: "json", // expected format for response
contentType: "application/json", // send as JSON
Accept: "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8",
data: data,
success: function (response) {
// we have the response
if (response.status == "SUCCESS") {
console.log("succes");
//Redirect to the right page if the user has been saved successfully
if (type === "setupuser") {
window.location = "/setup/user/" + userId;
} else if (type === "simulatoruser") {
window.location = "/simulator/user/" + userId;
}
} else {
errorInfo = "";
for (i = 0; i < response.result.length; i++) {
errorInfo += "<br>" + (i + 1) + ". " + response.result[i].code;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
}
},
error: function (e) {
alert('Error: ' + e);
}
});
The following controller is called by the Ajax request:
#RequestMapping(method = RequestMethod.POST, value = "/adduser/{userType}")
#ResponseBody
JsonResponse addUserMapping(#ModelAttribute(value="user") User user, BindingResult result, #RequestBody String jsonString, #PathVariable String userType) {
def json = new JsonSlurper().parseText(jsonString)
String userId = json.userId
String userName = json.userName
user.setId(userId)
user.setName(userName)
log.warn("User id..... "+user.getId())
log.warn("User name..... "+user.getName())
JsonResponse res = new JsonResponse();
ValidationUtils.rejectIfEmpty(result, "id", "userId can not be empty.");
ValidationUtils.rejectIfEmpty(result, "name", "userName can not be empty");
if(!result.hasErrors()){
userService.addUser(jsonString)
res.setStatus("SUCCESS");
}else{
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
As you can see, Ajax sends a JSON to the controller. The controller unpacks the JSON and puts the data into the user object. Then the user object is being validated using "rejectIfEmpty()" method...
Now I've been reading about making a userValidator class extending Validator, or simply putting Annotations in the bean class like:
#Size(min=1, max=3)
I prefer these annotations since you don't have to write special code for checking certain simple things (like the field not being empty .. #NotEmpty)
But that doesn't work because the controller doesn't take a user object the second it's called, instead it takes the JSON and then unpacks it (Validating is too late..)
TL:DR
Controller takes a JSON as a parameter instead of an Object. The JSON has to be unpacked and then validated in the controller as a java object using rejectIfEmpty as an example. I don't want a full page reload, but I still want to keep Ajax.
BTW: I want to validate the data against more things like regex etc. But the rejectifEmpty is a simple example.
Does anyone have an idea how to handle this?
I fixed the validation by parsing the JSON in the controller and setting it in the user object. The user object is then put in my UserValidator class and validated.
Link for more info using the validator:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/validation.html
I am stuck on some problems , actually I was in problem solved , the problem was header which is not enableing to get response (like CORS issue) ,overcome by using header and transformRequest as shown in below code. After that I got webservice data but in one controller used $rootscope which render some of id of data of second method (API) to use in another controller to put on third one api to get data and I am getting this for only a minute then it will throw error : Cannot read property 'companies data' of null which is field in third api. when I used $rootScope.Test.companies[0].companyname which is store data, and unique for all api like primary key.
var request = $http({
method: "post",
url: "http://app.xyz/xyzapp/public/user/login",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
str.push(encodeURIComponent('email_id') + "=" + encodeURIComponent('demo#xyz.com'));
str.push(encodeURIComponent('password') + "=" + encodeURIComponent('demo#xyz'));
return str.join("&");
},
});
request.success(function( response ) {
console.log("Hiiiii::::"+JSON.stringify(response,status));
if (response.status=="success"){
$rootScope.Test1=response.user_id;
var request1 = $http({
method: "post",
url: "http://app.xyz/xyzapp/public/company/getUserCompanyList",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
str.push(encodeURIComponent('user_id') + "=" + encodeURIComponent(response.user_id ));
// str.push(encodeURIComponent('password') + "=" + encodeURIComponent('demo#123'));
return str.join("&");
}
});
// getCompany
request1.success(function( response ) {
console.log("Hiiiii::::"+JSON.stringify(response,status)+" "+response.companies.length+":Length");
if (response.status=="success"){
// alert(1);
$state.go('tabdash');
$rootScope.Test = response;
}
});
So please tell me how to use one controller data to another where I am using another api which will get $rootscope date of parent.
Please let me know if anybody know about that or anything
Thanks
Yes you can use variables of one controller inside another controller using two methods
Create Service to communicate between them.
Use $rootScope.$broadcast
sample code
angular.module('myservice', []).service('msgBus', function() {
this.serviceValue= {};
}]);
});
and use it in controller like this:
controller 1
angular.module('myservice', []).controller('ctrl1',function($scope, msgBus) {
$scope.sendmsg = function() {
msgBus.serviceValue='Hello';
}
});
controller 2
angular.module('myservice', []).controller('ctrl2',function($scope, msgBus) {
$scope.checkValue(){
alert( msgBus.serviceValue);
}
});