AngularJS JQuery Ajax form submission Equivalent - javascript

Lately I have jumped into angularjs and its wonderful so far. I have been sending AJAX requests through $http service. Today I was shocked to find that there is no simple way to do it (to the best of my knowledge). Seaching through google and SO took me nowhere with convoluted complex solution.
Though I ended up using JQuery for now, am curious if something like JQuery ajax, capable of sending form is really available. Here is simple JQuery code to illustrate what am talking about
$.ajax({
type: "POST",
url: formUrl,
data: formData,
success: function(data)
{
$scope.form = $sce.trustAsHtml('<div class="alert alert-success">Succesfully Registred. You will be taken home in 5 seconds!</div>');
$timeout(function(){
$window.location.href= "#home";
}, 10000);
}
});

There is an equivalent in angular, here is a link to a jsfiddle with an example implementation: http://jsfiddle.net/dmcquillan314/boo5tn62/
The function on line 11 is an example of how to send a request to a rest api:
$scope.sendToResource = function() {}
To enable this feature just change the function in the directive to point to this factory and it will send a request to the api url configured in the factory.
In order to test this with an api you'll have to change the factory to match your server
here are some links to relevant documentation:
https://docs.angularjs.org/api/ngResource/service/$resource
https://docs.angularjs.org/api/ng/directive/ngSubmit
https://docs.angularjs.org/api/auto/service/$provide
Let me know if anything is unclear or you require any further explanation. Hopefully this should help you get started.

Related

Use Javascript to receive variable from remote php file?

I need to retrieve a variable from a remote php file using javascript. I'm doing this using phonegap so same origin policy doesn't apply. I guess I need to use json / ajax but I can't find any tutorials that show me how to do this.
Is it as simple as having this in a php file:
<?php
$var = 'stuff';
echo json_encode( $var );
?>
And something like this in my application:
$.getJSON('mysite.com/test.php', function( data ) {
$.each( data, function( i, entry ) {
alert( entry );
});
Or is this totally the wrong approach? Any help would be great, thanks.
so for starters here are the docs on JQuery's ajax & the docs for JQuery's getJSON; and finally a slightly dated but decent tutorial explaining the basics on how to get started with raw .JSON files.
typically when I am dealing with JSON i am interacting with a web API; and most of the time they are RESTful api's at that... creating one is slightly more complex than what you have there but your thought process is on track.
here is a working access point to the google finance stock quotes api running a query on microsoft:
http://finance.google.com/finance/info?client=ig&q=MSFT
and an example of a json call (using jsonp for accessing an external url):
$.ajax({
url: 'http://finance.google.com/finance/info?client=ig&q=MSFT',
dataType: 'jsonp',
success: function(data){
console.log( data );
}
});
to make things easier i would try and break the work into two steps... first get a handle on accepting data from a api you know is functioning (ie google finance above)... and then move on to the next step of trying to write your own WebAPI in php (eg say you wanted to build your "variable" into a database or something a bit more useful than a flat php file). this way you can debug a bit easier with less hair loss
I'm using jquery and
I used to do like this in my PHP (if using json):
<?php
$var = 'stuff';
echo '{"var":"'.$var.'"}';
?>
it would return to a json.
and the ajax :
$.ajax({
url : "mysite.com/test.php",
dataType : "json",
data :"",
type : "POST",
success :
function (data){
alert(data.var);
}
});
(data and type in the ajax are not needed if you just want to get json from "mysite.com/test.php");

Using JSONP API from forecast.io with WinJS

First off, apologies if this is a silly question, I'm new to WinJS and relatively new to Javascript, but I've been going great til I hit this roadblock.
I'm currently working on a weather app for Windows 8 using WinJS, and I'm trying to pull the data from the forecast.io API, which in my case is provided in JSONP format.
I easily got it working in-browser using jQuery and .getJSON, but since I have to use WinJS.xhr to request the data instead I'm having some difficulty.
I can pull the data just fine using the following code:
function getWeather() {
WinJS.xhr({
type: "GET",
url: "https://api.forecast.io/forecast/*ommited API key*/-36.044394,146.953718?callback=?&units=si",
headers: { "Content-type": "application/json" }
}).then(function complete(data) {
var weatherData = data.responseText;
(new Windows.UI.Popups.MessageDialog(weatherData, "Success!")).showAsync().done();
}, function error(data) {
(new Windows.UI.Popups.MessageDialog("Failed.", "Error")).showAsync().done();
});
}
This shows me the data in a popup window, so I'm sure that I've accessed it. The problem is, I can't do anything with it. In jQuery I simply used "data.currently.temperature" to get the current temperature data, but I can't get something similar working in this situation.
Any help or pointers would be greatly appreciated!
P.S sorry if I butchered any terminology, I'm doing my best.
Here's what data.responseText returns, there's quite a lot so I put it in a text file.
http://justadddesign.net/data.responseText.txt
It's because data.responseText is string not object. Try:
var forecastInfo = JSON.parse(data.responseText);
and then access forecastInfo object properties.

Using PARSE REST API

I am currently stuck on a task in which I have to use jQuery ajax to retrieve messages from PARSE HERE API to create something like this:
http://chatbuilder.hackreactor.com/?example=1&username=aa
I was wondering if anyone could explain to me how to use REST api to retrieve messages.
I have looked at other people's coding examples:
https://github.com/stevernator/Chatbuilder/blob/master/draft11
and
https://gist.github.com/guymorita/5726564
They seem to use ajax code like below:
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: function(data) {
var stuff = [];
for(i=0; i < 10; i++) {
stuff[i] = data.results[i].text
}
My question is: from where are the messages being generated from in this app? Do I have to create an account at Parse or would I just use ajax to retrieve this url link:"https://api.parse.com/1/classes/chats"?
Also, where would I find info on this specific class (chats)?
Any input would be greatly appreciated. Thanks!
The parse quick start guide is a very good place to start. The documentation is really good but the tutorials for the JS API are far more complex (backbone) than the documentation. I would download the Todos tutorial as there is some good stuff in it but if you dont know how backbone works its harder to read. I would have made this a comment but I don't have enough rep :(.

How do I assign a JSON response from this API I'm using to elements on my page?

I'm trying to use the API from https://developer.forecast.io and I'm getting a JSON response, this is the first time I'm using an API and all I really need to know is, how do I assign the JSON response I get back from their API to elements on my page. Thanks!
This is done with a script-tag in my header:
script(src='https://api.forecast.io/forecast/APIKEY/LAT,LON')
http://api.jquery.com/jQuery.ajax/ you need to add a success callback, at the bottom of that page are examples you can look at.
EDIT
ok i saw that you are using a script tag with the request, since the api is outside your current domain you need to make a JSONP request
$(document).ready(function(){
$.ajax({
url: 'https://api.forecast.io/forecast/APIKEY/LAT,LON',
dataType: 'jsonp',
success: function(data){
//do whatever you want with the data here
$("body").append(JSON.stringify(data));
}
});
});
off course you need to make some tweaks to that piece of block but you get the idea
What you're looking for is DOM manipulation. DOM is the HTML Document Object Model, an object representation of the HTML comprising a document. There are a lot of ways to go about this, but one of the more popular Javascript libraries for performing this task is jQuery. See their help documentation category on manipulation for more information.
OK, based on your clarification, you're not yet using AJAX. I say "not yet", because you're going to need to. Again, I'll recommend jQuery for that, and their own documentation as the best resource. For a simple "get", your easiest option is the getJSON method.
So, at a very simple level you might do something like:
$(function(){
$.getJSON('url_to_api', function(data) {
$("#SummaryBox").append("<div>" + data.hourly.summary + "</div>");
}
});

jQuery Ajax POST not working with MailChimp

I have the following code I am using to send data to a MailChimp Newsletter List (API v3). Everytime I remove the type: POST from the function it attempts to post the data via GET and it sends the data properly (ok response in MailChimp API dashboard). When testing this in the browser (FF) I get a .part file with "true" response.
$(function(){
$("a#test").click(function(e){
e.preventDefault()
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
}
$.ajax({
type: "POST",
url: 'http://us2.api.mailchimp.com/1.3/?method=listSubscribe',
data: data,
success: function(data){
alert(data);
},
error: function(){
alert("err");
}
})
});
});
Im pulling my hair out on this one, any insight is greatly appreciated.
Thanks in advance,
JN
There is an undocumented endpoint that uses JSONP to do cross-domain ajax requests.
Just change 'post?' to 'post-json?' and add '&c=?' to the end of the standard url to get the JSONP endpoint. This doesn't requires the API key to be exposed on the client-side, or the creation of a server-side view.
I wrote a jQuery plugin that uses this method, if that's useful at all
https://github.com/scdoshi/jquery-ajaxchimp
The main issue is what jc commented on your original post - this simply won't work due to Same Origin Policy issues. Firebug is not as vocal about why the GET call fails, but that's why it returns no data. If you watch that with the POST, you'll see Firefox doesn't even make the call. Chrome's js console on the other hand straight explains the Same Origin policy to you.
All in all, this is a very good thing if for no other reason than it prevents you from publicly publishing your account's API Key, which is a very bad thing to do. If the reason why doesn't immediately sink in, go read through the large number of methods available in the API and then realize that all you need to access them is that API Key.
The correct way to do this is to POST data back to your server, then make the request from there. There are several fully built PHP examples (one using jquery, even), here.
e.preventDefault();
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
};
Could be? Semicolon is important. Hehe

Categories

Resources