simple question, how would I write this in javascript/AngularJS.. this pythonscript works:
xml = <data><user>blabla</user> ..... etc
url = 'http://localhost:3080'
response = urllib2.urlopen(url, xml)
print response
Long story:
I'm playing around with an old, legacy XML service and thought it could be fun to get something working with AngularJS. I might confess that I'm not that familiar with either Angular or Javascript, please bear with me.
The XMLservice expects files with data and instructions on what functions to run etc. It will then respond with another xml file with the answer. However, I can't get the simplest function (login) to work at all.
If I try a "GET" and play with params, the service is triggered but logs "invalid" since it's either missing the XML data or the Xmldata is messed up (when added as param)
angular.module('myApp.loginServices', []).
factory('LoginSource', ['$http',function($http){
return {
get: function(url, callback, transform){
$http.get(
url,
{transformResponse:transform}).
success(function(data, status) {
console.log("success!!!!!!" + status+ " data");
callback(data);
}).error(function(data, status) {
console.log("FAILED!!!! " + status);
});
So I try a POST, like this, and this one gives me "status 0" and XmlService logs "501", maybe my xml is messed up or something, but it looks like it's not even reaching the service according to the logs?
factory('LoginSource', ['$http',function($http){
return {
get: function(url, callback, transform, xmlData){
console.log('xmlData: ' +xmlData);
$http({
url: url,
method: "POST",
data: xmlData,
headers: {'Content-Type': 'application/x-www-rform-urlencoded'}
}).success(function (data, status, headers, config) {
callback(data);
}).error(function (data, status, headers, config) {
console.log('status: ' +status);
});
}
};
I guess it's me being too much of a rookie with javascript and angularJs.. any help appreciated
Related
I'm doing a $http.get request to a https service which has an XML file and it need the headers('Content-length') to know it size.
This's my code:
$http({
method : "GET",
url : "https://url.com/xml_file.xml"
}).then(
function sCallback(data, status, headers, config, statusText) {
console.log( headers('Content-Length') );
}, function eCallback(data, status, headers, config, statusText) {
$log.warn(data, status, headers, config, statusText);
});
The result of the request is: "headers is not a function".
Is there another way to get it?
console.log( data.headers('Content-Length'));
console.log( data.headers('Content-type'));
I have this request:
$http({
method: 'get',
url: '/api/items/',
params: {a: 1, b: 2, c: 3}
}).success(function (response) {
console.log(response);
}).error(function (err) {
console.log(err);
});
Is there a way, to fetch the url it used to make the request after the request has been made(in the callback or otherwise)?
I would want the output:
http://www.example.org/api/items?a=1&b=2&c=3
Here the same thing is done with jquery.
The success handler gets 4 parameters passed into it:
$http
.get({ url: '/someUrl', params: { q: 3 } })
.success(function(data, status, headers, config) {});
The fourth parameter config has the following properties:
{
method: "GET",
url: {
url: '/someUrl',
params: {
q: 3
}
}
}
You can use window.location.origin to get the base url and build a simple function to concat it all together.
This function should yield the expected response:
var baseUrl = window.location.origin;
var query = [];
Object.keys(config.url.params || {}).forEach(function (key) {
var val = config.url.params[key];
query.push([key, val].join('=')); // maybe url encode
});
var queryStr = query.join('&');
var fullPath = baseUrl + config.url.url + '?' + queryStr;
Unfortunately, this function will only work as long as the parameters are passed in the format described above. If you pass them in a different format, you'll have to modify this function a bit. You can use this as a playground.
Afaik, there is no simpler way. At least a feature request exists.
See the docs of $http for reference
This config parameter of the callback has the url as a property:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
console.log(config.url);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Based on: https://docs.angularjs.org/api/ng/service/$http
You can use http request Interceptor.
Configure the Interceptor in config function using $httpProvider
Whrein for request Interceptor you can able to see the URL and params that you passed with URL prior to making the request
try just looking at the XHR Request urls in your browser dev tools
How do you use, or correctly use, javascript in dynamically embedded pages/content?
When an event occurrs I am loading a PHP/HTML page into an HTML element. The javascript works fine on the outter page, or the page that the content gets loaded into, but it does not work on the page that is being loaded.
Here is my request function:
function sendServiceRequest(file, nvpSendData, successCallback, failCallback) {
$.ajax({
type: "POST",
url: file,
data: nvpSendData,
dataType: 'html'
}).success(function(data, status) {
console.log(".done");
console.log("Return AJAX status: " + status);
//console.log("success data: " + JSON.stringify(data));
successCallback(data, status);
}).fail(function(data, status, error) {
console.log(".fail");
console.log("Return AJAX status: " + status);
//console.log("Return data: " + JSON.stringify(data));
failCallback(data, status, error);
});
}
Then i have a php page, viewScripts.php, that has this javascript file included, that handles the loading process
view_events.js
document.addEventListener('DOMContentLoaded', function() {
var rx = document.querySelector("#rx-number").value;
sendServiceRequest(
"/comments/get_content.php",
{action:"loadContent", loadType:"comments", rx_number:rx},
function(data, status) {
document.querySelector("#rx-comments-container").innerHTML = data;
},
function(data, status, error) {
console.log("AJAX send service request failed while loading comments!");
}
);
});
Then in the code above, /comments/get_content.php verifies the data being sent, and then loads the page comment.php into a div element, #rx-comments-container. Up until this point everything is fine. It's the javascript in comment.php that does not want to work. I have tried including a '.js' file with the specified functions to handle events into comment.php, but this does not work. I have also tried including the event functions in view_events.js, as listed above, which is included in viewScripts.php, and this does not want to work either. I have also tried embedding the javascript directly into comments.php, but this doesn't work either.
Here is the javascript that is to be included in comments.php:
document.addEventListener('DOMContentLoaded', function() {
document.getElementsByClassName("edit-rx-comment-glyph").addEventListener("click", function () {
var id = this.value;
sendServiceRequest(
"/comments/get_content.php",
{action: "loadContent", loadType: "editComment", comment_id: id},
function (data, status) {
document.querySelector('#' + id).innerHTML = data;
},
function (data, status, error) {
console.log("AJAX send service request failed while loading edit form!");
}
);
});
document.getElementsByClassName("comment-history-glyph").addEventListener("click", function () {
var id = this.value;
sendServiceRequest(
"/comments/get_content.php",
{action: "loadContent", loadType: "viewHistory", comment_id: id},
function (data, status) {
document.querySelector('#comments-body').innerHTML = data;
},
function (data, status, error) {
console.log("AJAX send service request failed while loading edit form!");
}
);
});
});
I managed to figure this out. I guess i was doing something wrong, because my code ended up working. I just used an onclick event with the sendServiceRequest function, and that ended up working. I didn't need to include any other js files.
I am trying to use the WordsAPI and everytime I try to access it using jsnop and Angular I get this error:
The code I am using is the following:
$scope.searchWord = function() {
var url = 'https://www.wordsapi.com/words/'+$scope.word+'/definitions?callback=JSON_CALLBACK&accessToken=ACCESS_TOKEN';
$http.jsonp(url).
success(function(data, status, headers, config) {
$scope.meanings = data;
console.log($scope.meanings)
}).error(function(data, status, headers, config) {
console.log(data);
});
}
So it should be getting something like:
https://www.wordsapi.com/words/word/definitions?callback=JSON_CALLBACK&accessToken=ACCESS_TOKEN
I tested this link on JSON validators and everything is fine with the JSON it gets from the server.
I am using Chrome on a Mac.
Does Anyone have any idea ?
I used this function
jQuery.ajax({
type: 'POST',
url: urlSubmit,
timeout: 5000,
dataType: 'text',
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
"success": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX success :) - statut " + textStatus);
$timeout(successMailZR_alerte, 3000);
},
"error": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX fail :/ - statut " + textStatus);
$timeout(errorMailZR_alerte, 3000);
}
});
Whats the code is doing : code POST to a php script who send an email.
but, since i rewrited my code in a complete angularjs app, i do it like this :
$http({
method: 'POST',
url: urlSubmit,
timeout: 5000,
cache: false,
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
responseType: 'text',
}).
success(function(data, status, headers, config) {
console.log("AJAX success :) - statut " + status);
$timeout(successMailZR_alerte, 3000);
}).
error(function(data, status, headers, config) {
console.log("AJAX fail :/ - statut " + status);
$timeout(errorMailZR_alerte, 3000);
});
Problem is : with $http, i have a success 200 but nothing is posted and i have no return in my email. What's the problem ?
The problem is that jQuery's POST does send your data as form data (e.g. key-value pairs) (https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data) whereas AngularJS sends your data in the request payload. For a difference between the two see the following SO question: What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab
In order to make your angular script works with your server you have to convert your data to a URL encoded string as described here: How can I post data as form data instead of a request payload?. Simply setting headers: {'Content-Type': 'application/x-www-form-urlencoded'} is not enough.
A different approach would be to adapt the back-end of your application to parse the message payload instead of the form data parameters.
To understand this one need to understand the request headers set by angular and jquery, There are differences with the headers like when request is post by jQuery then header might look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded // default header set by jQuery
foo=bar&name=John
You can see this in form data in the request made in the browser, if you use chrome then you can see this in chrome inspector at network tab, if you click the request then you can see the form data and content headers set by the jQuery.
On the other side with angular js $http service, when a request is made then you can find these:
POST /some-path HTTP/1.1
Content-Type: application/json // default header set by angular
{ "foo" : "bar", "name" : "John" }
The real difference is this you have a request payload not usual form data which is used by jQuery. so you need to do something extra at the server side like below.
Use this:
$data = json_decode(file_get_contents("php://input"));
echo $data->date;
// and all other params you have sent
This is due to its default headers
Accept: application/json, text/plain, * / *
Content-Type: application/json
and jQuery unlikely have something else:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8