Load data from ajax request (json) on startup in AngularJs - ajax

I have this simple page that just needs to show contents that is loaded from an external url (ajax request, response in json format)
I should say I'm a AngularJS newbie.
I've googled a bunch and found different ways of doing this and couldn't manage to determine which is the correct/simple/up-to-date way to achieve this.
My 2 challenges -
Making the AJAX request run on startup (I can load the page before that happens and just load the contents one the ajax request finishes. Maybe show a 'Loading..' indicator)
Doing a ajax request correctly.
Here is my attempt. I know that the ajax request is never made because its not setup correctly.

You are getting into .error function:
http://jsbin.com/oDUsuVA/3/edit
For jsonp your response should be something like:
callback([
{
"title":"License Title 1",
"licenseUrl":"http://cnn.com",
"licenseText": " test"
}]);
Edit:
You can simply do .get() request too, but if you had to use jsonp request interface, you would have to correct response.
A Jsonp request always wraps the logic into a json callback wrapper function.

I just did $http.get instead of your $http.jsonp and it did work for me.

Related

Cypress: Test non-XHR request caused by submitting POST form

I am testing Vue application. In some cases my application have to submit(not just after click submit button but programmatically) POST form and redirect to 3rd party server with some body parameters. Like in best practice written I am trying to avoid of using redirect to real server.
For my certain test it will be sufficient to just make sure that request was sent with certain parameters, but I don't now how to catch this body request parameters for assertion, because cypress does not allow to stub non-XHR requests and I can't do like this:
cy.route('POST', '/posts').as('post')
cy.get("#post").should(req => {
// check body params
});
I also thought about stub vue component method to intercept form submitting, but it only seems to work with global objects like Math.
I truly appreciate any new ideas how to test functionality like this.
Since Cypress 5.1 you can stub other requests type using cy.route2()(https://docs.cypress.io/guides/references/changelog.html#5-1-0).

Retrieving JSON from an external API with backbone

I'm new to backbone.js and I've read other solutions to similar problems but still can't get my example to work. I have a basic rails api that is returning some JSON from the url below and I am trying to access in through a backbone.js front end. Since they are one different servers I think I need to use a 'jsonp' request. I'm currently doing this by overriding the sync function in my backbone collection.
Api url:
http://guarded-wave-4073.herokuapp.com/api/v1/plans.json
sync: function(method, model, options) {
options.timeout = 10000;
options.dataType = 'jsonp';
options.url = 'http://guarded-wave-4073.herokuapp.com/api/v1/plans.json'
return Backbone.sync(method, model, options);
}
To test this I create a new 'plans' collection in my chrome console using "plans = new Plans()" and then "plans.fetch()" to try and get the JSON.
When I call plans.models afterwards I still have an empty array and the object that returns from plans.fetch() doesn't seem to have any json data included.
Any ideas where I'm going wrong?
I have had the same problem before. You should not have to override your sync method.
Taken from Stackoverflow Answer
"The JSONP technique uses a completely different mechanism for issuing HTTP requests to a server and acting on the response. It requires cooperating code in the client page and on the server. The server must have a URL that responds to HTTP "GET" requests with a block of JSON wrapped in a function call. Thus, you can't just do JSONP transactions to any old server; it must be a server that explicitly provides the functionality."
Are you sure your server abides to the above? Test with another compatible jsonp service (Twitter) to see if you receive results?
Have you tried overriding the fetch method as well?
You should add ?callback=? to your api url in order to enable jsonp

AJAX callback in Inter Explorer

I have a question about AJAX.. I am using AJAX for my javascript in calling php file,
how ever I noticed that when I run the program in IE callback comes in twice which
gives me more results than expected while callback comes in in firefox only once..
I want to have just the one reply from callback..
this.doPost = function(param) {
/// make a HTTP POST request to the URL synchronously
req.open("POST",url, true);
...
this is the call..
Do you know what is wrong?
Thanks.
Depending on how you actually perform the AJAX call and what you do in the callback, you can run into issues - see for example this thread for similar issues:
How to execute a page ,that contains JS ,in AJAX ,using innerHTML?
I suggest you try some proven library instead of using AJAX on the low level. For example, using jQuery you can use $.ajax, see e.g. the examples in jQuery documentation:
http://api.jquery.com/jQuery.ajax/
or some of many other examples you can find on the Net, such as this:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

How do I collect data from a website that uses AJAX, with Perl?

This might seem a bit backwards, but I want to use Perl (and Curl if possible) to get data from a site that is using Ajax to fill an HTML shell with information. How do I make these Javascript calls to get the data I need?
The website is here: http://www.jigsaw.com/showContactUpdateTab.xhtml?companyId=224230
Remember that AJAX calls are ordinary HTTP requests, so you always should be able to perform them.
Open Firebug or Web Inspector on the website you're talking about, you'll see some XHR calls:
XHR finished loading: "http://www.jigsaw.com/dwr/interface/UserActionAPI.js".
"http://www.jigsaw.com/dwr/call/plaincall/UserActionAPI.getMostPurchasedContacts.dwr".
"http://www.jigsaw.com/dwr/call/plaincall/UserActionAPI.getRecentlyGraveyardedContacts.dwr
"http://www.jigsaw.com/dwr/call/plaincall/UserActionAPI.getRecentlyAddedContacts.dwr".
"http://www.jigsaw.com/dwr/call/plaincall/UserActionAPI.getRecentlyTitleChangedContacts.dwr"
Yay! Now you know where to get that data. Their scripts use POST HTTP request to the URLs above, so if you open them in your browser, you'll see various engine errors.
When you sniff (via Web Inspector debugger, for example) their AJAX POST requests, you'll see the next body:
"callCount=1
page=/showContactUpdateTab.xhtml?companyId=224230
httpSessionId=F5E7EC4A45DFCE87B969A9F4FA06C361
scriptSessionId=D020EFF4333283B907402687182D03E034
c0-scriptName=UserActionAPI
c0-methodName=getRecentlyGraveyardedContacts
c0-id=0
c0-param0=number:224230
c0-param1=boolean:false
c0-param2=boolean:false
batchId=1
"
I'm pretty sure, they're generating a bunch of security session IDs to avoid data miners. You may need to dive into their JavaScript codes to learn more about those generators.
Some applications have code in place to check that the client is a real AJAX client. They simply the check for the presence of the header X-Requested-With: XMLHttpRequest. So it's easy to circumvent:
curl -H 'X-Requested-With: XMLHttpRequest' ...
use HTTP::Request::Common;
GET $url, 'X-Requested-With' => 'XMLHttpRequest', ...
Of course, you might have to deal with the usual stuff, like required cookies (for the session), nonce parameters, the occasional complexity. Firebug or the like for other browsers will help you reverse-engineer the required headers and parameters.

Cross domain javascript ajax request - status 200 OK but no response

Here is my situation:
Im creating a widget that site admins can embed in their site and the data are stored in my server. So the script basically has to make an ajax request to a php file in my server to update the database. Right? Right :)
The ajax request works excellent when i run it in my local server but it does not work when the php file is on my ONLINE server.
This is the code im using:
var url = "http://www.mydomain.net/ajax_php.php";
var params = "com=ins&id=1&mail=mymail#site.net";
http.async = true;
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//do my things here
alert( http.responseText );
}
}
http.send(params);
In firebug it shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.
When i check the ajax responnseText I always get a Status:0
Now my question is: "Can i do cross-domain ajax requests by default? Might this be a cross-domain ajax problem? Since it works when the requested file resides in my local server but DOESN'T work when the requested file is in another server, im thinking ajax requests to another remote server might be denied? Can you help me clear on this?
Thanks..
Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:
function receiveData(data) {
// ...
}
And then your server wraps JSON data in a function call, like this:
receiveData({"the": "data"});
And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.
Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.
You're going to need to have your response sent back to your client via a JSONP call.
What you'll need to do is to have your request for data wrapped in a script tag. Your server will respond with your data wrapped in a function call. By downloading the script as an external resource, your browser will execute the script (just like adding a reference to an external JS file like jQuery) and pass the data to a known JS method. Your JS method will then take the data and do whatever you need to do with it.
Lots of steps involved. Using a library like jQuery provides a lot of support for this.
Hope this helps.

Resources