I currently have the following angular script in a page:
var app = angular.module('doorman', []);
app.controller('formCtrl', function($scope, $http) {
$scope.create = function() {
var msg = '{' +
'"id":"id",' +
'"building":"' + $scope.building + '",' +
'"unit":"' + $scope.unit + '",' +
'"firstName":"' + $scope.firstName + '",' +
'"name":"' + $scope.name + '",' +
'"carrier":"' + $scope.carrier + '",' +
'"tracker":"' + $scope.tracker + '"' +
'"delivered":"0",' +
'"added":"NOW()"' +
'}';
$http.put("104.131.166.246:8080/doorman/rest/pilot", msg).
success(function(data, status, headers, config) {
//empty the fields
$scope.building = "";
$scope.unit = "";
$scope.firstName = "";
$scope.name = "";
$scope.carrier = "";
$scope.tracker = "";
}).
error(function(data, status, headers, config) {
//TODO temporary, remove
alert("ERROR " + status + ": " + data);
});
};
$scope.search = function() {
}
});
I have a backend RESTful java servlet handling requests.
When I call the 'create()' function, the output always ends up on the error function, showing the alert 'ERROR undefined: undefined'. While monitoring http requests on chrome, I see no request being made at all. What could the problem be?
From angular side, your code looks ok. Further when you say the call ends up in the error section, it suggest that something is going wrong on the outbound call or on the server side. Can you use browser tools or if you are in windows use a tool like fiddler to see the network traffic to see what’s going on. One
other thing, see whether you have to enable Cross-origin Resource Sharing (CORS) on server side.
Cheers
Found the error. Apparently, appending "http://" to the beginning of the url is necessary. Thanks anyway!
Related
For some reason the script does not run, or return answer.
The console is nothing.
Trying to get an answer to yandex.transtale site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/)
Code: http://jsbin.com/jolijep/edit?html,js,console,output
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function($scope, $http) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate";
keyAPI = "trnsl.1.1.20130922T110455Z.4a9208e68c61a760.f819c1db302ba637c2bea1befa4db9f784e9fbb8";
var vm = this;
$scope.SendData = function() {
// тут данные
var textApi = 'Hello';
var langApi = 'en-ru';
var text1 = 'Hello';
var data = "key=" + keyAPI + "&text=" + textApi + "&lang=" + langApi;
$http.post(url, data)
.success(function(data, status, headers, config) {
vm.data = response.data;
$scope.PostDataResponse = data;
console.log(data);
})
.error(function(data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="weather.js"></script>
</head>
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as vm">
<script src="weather.js"></script>
<button ng-click="SendData()">Send</button>
<br>Data: {{PostDataResponse}}
<br>{{vm.data}} {{vm.PostDataResponse}} Data: {{scope.PostDataResponse}} {{vm.data}}
</div>
</body>
</html>
If you look at the Yandex translate API reference, it has asked you to pass the information for the request you are making in the form of the params(parameter). These parameters are to be appended to the request URL.
Other ways of getting information from an API with a POST request is to pass information in the form of the body of that request.
But the Yandex translate API with the POST request is asking for the information attached to the url.
var data = "key="+keyAPI+"&text="+textApi+"&lang="+langApi
this data variable should be getting appended to the url variable when the POST request is made to the API. But,
$http.post(url, data)
Invoking $http method makes the data interpreted as the body of the post request instead of appending the data variable to url while making the call.
A much cleaner and proper implementation for $http API of the AngularJS would be to put all you parameters inside an object where the keys are the parameter type and values are the parameter values.
var params = {
key: keyAPI,
text:textApi,
lang:langApi
}
Now in the params object, you are hold all the information you wanted to pass while making the request.
Secondly, you need to the modify the $http request so that it knows what params are to be appended to the url. I am using more basic $http method instead of $http.post method,I will clearly mention what should be the base url, type of method for the HTTP request and lastly, the params that are to passed with the request to the API.
$http({
url: url,
method: 'POST',
params: params
})
.success(function(data,headers,status,config){
$scope.PostDataResponse = data;
vm.data = data;
console.log(data);
})
.error(function(data,headers,status,config){
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
Another thing which was wrong in your code was the initialization of $scope.PostDataResponse
$scope.PostDataResponse = response.data; //You are not getting any argument named response by the success function call
Correct way to do it will be
$scope.PostDataResponse = data;
Now if you run the code with the modification it should run pretty fine.
If everything is done correctly, then in the developer console you would find an object logged after the success of the request.
Object with the success of the call
In your webpage also, you would see the same object.
I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")
I'm trying to get all facebook comments with profile pictures of commentators through fb.api() call. Currently all comments gets outputed i just can't get profile pictures to append to appropriate comment.
In for loop which loops through all comments is another FB.api call which gets the profile pic of user who commented on video and than append them into single comment block. With this code i get profile pictures of all users who commented in every single comment.
What am i doing wrong?? Thank you in advance!
var komentarji_length = response.comments.data.length;
for (var i = 0; i < komentarji_length; i++) {
var user_id = response.comments.data[i].from.id;
FB.api("/" + user_id + "/picture", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
var ime = response.comments.data[i].from.name;
var message = response.comments.data[i].message;
$(".fb_comments").append('<div class="single_comment"><div class="comments_profile_pic' + i + '"></div><div class="name">' + name + '  says:</div><div class="single_message">' + message + '</div></div>');
}
Issue 1: comments_profile_pic_link is not defined, the variable is: profile_pic_link.
But then also the problem will not be solved. When you call "/" + user_id + "/picture" it is redirected to the image url automatically. So you can directly use the image url as: https://graph.facebook.com/{user-id}/picture. No need to make the API call unnecessarily.
Example
Still if you wish to get the proper image url (not required though), use redirect=0 with your call-
FB.api("/" + user_id + "/picture?redirect=0", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.
I'm posting ckeditor content via Ajax to php. But getting 4-5 sentence of posted material in my db table. I wonder, Is there any size limitation for ajax post? is there any way to post big text contents via ajax?
My js looks like that
function postViaAjax(autosaveMode) {
var name = $("#name").val();
var title = $("#title").val();
var menu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
var id = $("#id").val();
if (parentcheck == 0) {
var parent = parentcheck;
} else {
var parent = $("#parent").val();
}
var content = CKEDITOR.instances['content'].getData();
var dataString = 'name=' + name + '&title=' + title + '&menu=' + menu + '&parentcheck=' + parentcheck + '&id=' + id + '&parent=' + parent + '&content=' + content;
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
var message = result.msg;
var err = result.err;
var now = new Date();
if (message != null) {
if (autosaveMode) {
$('#submit_btn').attr({
'value': 'Yadda saxlanıldı ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
} else {
$.notifyBar({
cls: "success",
html: message + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
}
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
}
});
};
The HTTP specification doesn't impose a specific size limit for posts. They will usually be limited by either the web server or the programming technology used to process the form submission.
What kind of server do you use?
There isn't any size limitation for POSTs in HTTP.
Maybe you have an & in your content variable. Then everything after that would be stripped after that.
Other than that what type do you use for your data column in the database? Is it, by any chance, something like varchar(1000)? Then anything bigger would also get stripped.
Check what you actually receive on the server end, so you know if you've got a problem with the code or the database.
You have a limitation on the Apache server. Look for LimitRequestBody directive.
This may be helpful:
http://gallery.menalto.com/node/14870
In theory the limits on AJAX requests are the same on all the other requests, so it depends on your web server/app setup. See also Max length of send() data param on XMLHttpRequest Post