$resource.save is not functioning - json

I am a novice developer of angularJs.
Working on some tutorials and facing the following problem now.
This is my view.
<!DOCTYPE html>
<html lang="en" ng-app="eventsApp">
<head>
<title>Event Registry</title>
<meta charset="utf-8"/>
<link type="text/css" rel="stylesheet" href="css/app.css"/>
<link type="text/css" rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body ng-cloak>
<div id="container">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li> Add Event
</ul>
</div>
</div>
<div ng-controller="EditEventController">
<div class="container">
<h1>New Event</h1>
<hr/>
<form name="editEventForm">
<fieldset>
<label for="eventname">Event Name :</label>
<input id="eventname" type="text" ng-model="event.name" placeholder="Enter your Event Name"/>
<label for="eventdate">Event Date :</label>
<input id="eventdate" type="text" ng-model="event.date" placeholder="format is (dd/mm/yy)..."/>
<label for="eventtime">Event Time : </label>
<input id="eventtime" type="text" ng-model="event.time" placeholder="Enter the start time and end time"/>
<label for="eventlocation">Event Location :</label>
<input id="eventlocation" type="text" ng-model="event.location.address" placeholder="Enter the location of the event"/>
<br/>
<input id="eventstate" type="text" class="input-small" ng-model="event.location.state" placeholder="Enter the state of the location of the event"/>
<input id="eventcountry" type="text" class="input-small" ng-model="event.location.country" placeholder="Enter the country of the location of the event"/>
<br/>
<label for="eventImageUrl">Image Url:</label>
<input id="eventImageUrl" type="url" class="input input-xlarge" ng-model="event.imageUrl" placeholder="enter the image url"/>
</fieldset>
<img ng-src="{{event.imageUrl}}" src=""/>
<br/>
<br/>
<button type="submit" class="btn btn-primary" ng-click="savestatus(event,editEventForm)">Save</button>
<button type="button" class="btn btn-default" ng-click="reset()">Cancel</button>
</form>
</div>
</div>
</div>
<script src="lib/jquery-1.9.1.min.js"></script>
<script src="lib/jquery-ui.js"></script>
<script src="lib/underscore-min.js"></script>
<script src="lib/bootstrap.min.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-sanitize.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/services/services.js"></script>
<script src="js/services/EventData.js"></script>
<script src="js/services/GravatarUrlBuilder.js"></script>
<script src="js/controllers/controllers.js"></script>
<script src="js/controllers/EventController.js"></script>
<script src="js/controllers/EditEventController.js"></script>
<script src="js/controllers/EditProfileController.js"></script>
<script src="js/app.js"></script>
<!--<script src="js/filters.js"></script>-->
</body>
</html>
and my controller is
angular.module('eventsApp.controllers').controller('EditEventController',function EditEventController($scope,eventData){
$scope.event={};
$scope.savestatus=function(event,form){
if(form.$valid){
eventData.save(event).
then(function(response){
console.log("success :",response);
},
function(response){
console.log("failure:",response);
});
};
} ;
$scope.reset=function(){
window.location='../app/EventList.html';
}
});
and the app.js file is
angular.module('eventsApp', [ 'ngSanitize' ,'eventsApp.controllers', 'eventsApp.services','ngResource'
])
and the services file i am using is:
angular.module('eventsApp.services').factory('eventData',function($resource,$q){
var resource= $resource('data/eventData/:id.json',{id:'#id'});
return{
getEventItem:function(){
var deferred=$q.defer();
resource.get({id:1},
function(eventItem){
deferred.resolve(eventItem);
},
function(response){
deferred.reject(response);
});
return deferred.promise;
} ,
save:function(event){
var deferred=$q.defer();
event.id=999;
resource.save(event,
function(response){
deferred.resolve(response);
},
function(response){
deferred.reject(response);
}
);
return deferred.promise;
}
};
}
) ;
When i am trying to save the input text details on click of the savestatus() button
I am unable to save them as a json file on the disk as shown in the tutorial I am referring to..
Whenever I have tried to save it I am getting the following error...
POST http://localhost:8000/app/data/eventData/999.json 501 (Not Implemented) angular.js:7073
failure: Object {data: "", status: 501, headers: function, config: Object}

I encountered this problem and solved my case. Here's how I did:
You have to modify your back-end (in my case: web-server.js
from angular-seed project, running with NodeJs) in order
to accept 'POST' method requests.
Then, when a POST request will be sent, you
must catch it (a simple 'if' would do the trick) and call a function
to handle it.
Finally, you have to write this function which will
catch the request data and do what you want with it (e.g. create a
JSON file and copy the data into it).
If you're also using NodeJs and maybe the web-server.js from angular-seed, here's what I've done : modified Web-server.js
Hope it will help you or someone else to avoid 501 errors!

Related

How to send data from Html File To another one Using angular?

i try sample project which take some data in form in html file .. then pass it to spring service .. which return object successfully .. now i want to pass this object to another Html fie to Display
Form's Html File :
<!DOCTYPE html>
<html ng-app="phase2">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<title>Sign UP Page</title>
<script src="RigesterationController.js"></script>
</head>
<body >
<center>
<p>Enter Your User Name : <input type="text" , name="UserName" id ="UName" required /> </p>
<p>Enter Your Email : <input type="text" , name="Email" id ="email" required /> </p>
<p>Enter Your Password : <input type="password" , name="pass" id ="Pass" required/> </p>
<p>Choose Gender : <br> Male<input type="radio" name="gender" value="m" id="Gender" /> Female<input type="radio" name="gender" value="f" id="Gender"/> </p>
<p>Choose User Type :<br> Student<input type="radio" name="UserType" value="s" id="Utype" /> Teacher<input type="radio" name="UserType" value="t" id="Utype"/> </p>
<div ng-controller="SignUP">
<input type="button" name="signup" value="SignUP" ng-click="save()" />
</div>
</center>
</body>
</html>
RigesterationController.js file :
angular.module("phase2" , [])
.controller("SignUP" , function($scope , $http )
{
var dat ;
$scope.save = function() {
var email= document.getElementById("email").value;
var UName=document.getElementById("UName").value;
var Pass=document.getElementById("Pass").value;
var gender=document.getElementById("Gender").value;
var UserType=document.getElementById("Utype").value;
var Info ;
$http.get('http://localhost:8090/SignUp/'+email+'/'+UName+'/'+Pass+'/'+gender+'/'+UserType)
.then(function(response)
{
Info = response.data;
dat=Info ;
alert(dat.name) ;
window.location.href="http://localhost:8060/TheAngular_Project/StudentPage.html";
});
}
});
second Html file :
<!DOCTYPE html>
<html ng-app="phase2">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="RigesterationController.js"></script>
<head>
<title>Student Page</title>
</head>
<body>
<div ng-controller="SignUP">
<p><span class="name">Welcome {{dat.name}}</p>
</div>
</body>
</html>
now nothing appeared in dat.name in second html file ..
although .. in regestrationController.js ..I test dat.name in an allert and it appeared successfuly ..
thanks in advance
i found the answer by Wawy in this post..
[AngularJS - Passing data between pages
You need to create a service to be able to share data between controllers.
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
In your controller A:
myService.set(yourSharedData);
In your controller B:
$scope.desiredLocation = myService.get();
Remember to inject myService in the controllers by passing it as a parameter.

How to fix recaptcha error?

I have a sitekey and I want to reproduce the captcha locally. However, when I open the html it says invalid domain for sitekey.
this is the code in my html file:
<script type='text/javascript' src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form method="post" action="you cannot see this link">
<input type="text" placeholder="productcode_size" name="pid">
<input type="text" placeholder="productcode" name="masterPid">
<input type="hidden" value="1" name="Quantity">
<input type="hidden" value="" name="x-PrdRtt" id="captcha_val">
<input type="hidden" value="Add To Bag overlay" name="layer">
<input type="hidden" name="ajax" value="true">
<br>
<br>
<br>
<br>
<div style="opacity: 0.3" class="g-recaptcha" data-sitekey="you cannot see this sitekey"></div>
<br>
<div class="contionue-shopping-wrapper">
<form class="co-formcontinueshopping" action="You cannot see this link" method="post" id="dwfrm_cart_d0ffhvzsobkp">
<fieldset>
<button class="rbk-button-red button-primary bp-black right" type="submit" value="Continue Shopping" name="dwfrm_cart_continueShopping">
<span>Continue Shopping</span>
</button>
</fieldset>
</form>
</div>
</form>
<script>
check = setInterval(function() {
v = document.getElementById('g-recaptcha-response').value
if (v.length > 0) {
var r = '&x-PrdRtt='+v+'"">ATC Link</a>';
document.getElementById('captcha_val').value = v
var sz = document.getElementById('sz').value;
var pid = '?ajax=true&pid='+sz;
document.getElementById('hack').innerHTML = '<a href="'+document.forms[0].action+pid+r;
clearInterval(check);
}
}, 400)
</script>
</body>
</html>
Please can someone help me fix this? I want to be able to complete the captcha locally to extract the captcha response.
According to this page https://developers.google.com/recaptcha/docs/start
If you would like to use "localhost" for development,
you must add it to the list of domains.
so simply add "localhost" (or "127.0.0.1") , that should work for you.

AngularJS Form - Default Value for Select

I'm trying to create an angularjs form with two fields, one text input and a select. By default, the text input is blank but the select should have a value (the first element on the select). I'm following the angularjs form docs and using a master object which on reset is copied into the page's model. Here's the thing, if I set the select to something by default it comes blank. If I do the same with the text field it displays the default value. Below you'll find my code and here's a plunker. I think it might have to do with the copy being made on the reset function but I'm printing the object to the console at that point and it looks like it's being copied. If I try to do this without the master stuff, just setting it straight to the user and not calling reset it works ok.
controller
(function(angular) {
'use strict';
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.businessUnits = [{"businessUnitId":1,"name":"Auto"},{"businessUnitId":2,"name":"Life"},{"businessUnitId":3,"name":"Health"},{"businessUnitId":4,"name":"Surety"},{"businessUnitId":5,"name":"Finance"},{"businessUnitId":6,"name":"Dwelling"}];
$scope.master.businessUnit = $scope.businessUnits[0];
$scope.master.name = "John";
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function(form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
$scope.user = angular.copy($scope.master);
console.debug($scope.user.businessUnit);
};
$scope.reset();
}]);
})(window.angular);
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example33-production</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form name="form" class="css-form" novalidate>
Name:
<input type="text" ng-model="user.name" name="uName" required="" />
<br />
<div ng-show="form.$submitted || form.uName.$touched">
<div ng-show="form.uName.$error.required">Tell us your name.</div>
</div>
E-mail:
<input type="email" ng-model="user.email" name="uEmail" required="" />
<br />
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
<select class="form-control" ng-model="user.businessUnit" ng-options="unit as unit.name for unit in businessUnits" required></select>
Gender:
<input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female
<br />
<input type="checkbox" ng-model="user.agree" name="userAgree" required="" />
I agree:
<input ng-show="user.agree" type="text" ng-model="user.agreeSign" required="" />
<br />
<div ng-show="form.$submitted || form.userAgree.$touched">
<div ng-show="!user.agree || !user.agreeSign">Please agree and sign.</div>
</div>
<input type="button" ng-click="reset(form)" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
</div>
</body>
</html>
Add the following code to your <select>
ng-init="user.businessUnit = businessUnits[0]"
It should look like this:
<select class="form-control" ng-model="user.businessUnit" ng-init="user.businessUnit = businessUnits[0]" ng-options="unit as unit.name for unit in businessUnits" required></select>

trying to add to database using AJAX

I tried following a couple of examples on the web about adding to a mysql database using ajax but it isn't posting to the database but is executing the header at the bottom of the page.
This is the html document where you input the information
edit: Thank you for all your answers, This has now been fixed.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="message.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Add a comment!</title>
</head>
<body id="bodymain">
Home
<br>
<div id="main">
<?=$blog_post_history?>
</div>
<br>
<br>
<form method="post" action="addreply.php">
<input type="hidden" name="blogid" value="<?php echo $_GET['id'] ?>">
Author: <input type="text" name="poster" size="60">
<br>
Email: <input type="text" name="email" size"60">
<br>
Comment: <textarea name='content' rows=10 cols=50 id='content'></textarea>
<input type="submit" value="send" />
</form>
</body>
</html>
This is the javascript
$(function(){
//Whenever the form submites, call this
$("form").submit(function()) {
//submit using ajax
submitMessage();
//prevent from submitting
return false;
}
};
var submitMessage = function (){
if($("#content").val().length > 0 && $("author").val.length > 0)
{
//start ajax request
$.post(
"addreply.php"
{
content: $("#message").val(),
author: $("#author").val(),
email: $("email").val(),
blogid: $("blogid").val()
},
);
}
};
And this is the php page adding to database
<?php
include("connect.php");
$add_comment_query = $db->prepare("
INSERT INTO `comments`
(`email`, `author`, `content`, `postid`)
VALUES
(:email, :author, :content, :postid)
");
$add_message_query->execute(array(
':email' => $_POST['email'],
':author'=> $_POST['author'],
':content' => $_POST['content'],
':postid' => $_POST['blogid']
));
// This calls for a '301' response code instead of '200', with a 'Location'
// sent to tell the browser where to redirect to.
header("Location: home.php");
?>
Can anyone see where I am going wrong. I am completely stumped.
$("author") and $("#author") should be $("#poster").
Also, all your <input> elements are midding id attributes. So:
<input type="text" name="poster" size="60">
should be:
<input type="text" name="poster" id="poster" size="60">
and similarly for all the other inputs.
Your selectors aren't correct.
Did you try debugging the javascript in your browser to see what the value of for instance $("#author") is?
The hash is the ID selector so you need the HTML for that element to have an id property:
<input type="text" name="poster" id="poster" size="60">
All of your other fields should be modified similarly so that each element you are going to use has an ID and each jquery selector is in the format "#" Currently author, email, and blogid have wrong selectors.
Make the HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="message.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Add a comment!</title>
</head>
<body id="bodymain">
Home
<br>
<div id="main">
<?=$blog_post_history?>
</div>
<br>
<br>
<form method="post" action="addreply.php">
<input type="hidden" id="blogid" name="blogid" value="<?php echo $_GET['id'] ?>">
Author: <input type="text" name="poster" id="poster" size="60">
<br>
Email: <input type="text" name="email" id="email" size"60">
<br>
Comment: <textarea name='content' rows=10 cols=50 id='content'></textarea>
<input type="submit" value="send" />
</form>
</body>
</html>
and your jquery:
var submitMessage = function (){
if($("#content").val().length > 0 && $("#poster").val.length > 0)
{
//start ajax request
$.post(
"addreply.php"
{
content: $("#message").val(),
author: $("#poster").val(),
email: $("#email").val(),
blogid: $("#blogid").val()
},
);
}
};

Handling a form purely from Javascript

I have the following form in a website of mine.
<form action="" method="GET">
<input type="text" name="query" value="" />
<input type="button" name="talk" value="talk" onClick="askCow(this.form)" />
</form>
Clicking the button does fire an AJAX request that updates the page. Using return does not, however; it simply submits the form using GET, which is not the desired behavior. Using onsumit="return false;" or similar disables submission, but this is not the desired behavior.
How can I execute the askCow function on an enter press ("form submission") while making sure the form is NOT submitted? Am I a bad person for doing this? The reason I use AJAX is that it lets me omit templating logic on the server side entirely.
Thanks!
Edit: here is the complete page
<html>
<head><title>Psycowlogist</title></head>
<body>
<div id="history">
Previous discussion
</div>
<div id="cow">
<pre>
_______________________
< What is your problem? >
-----------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
</pre>
</div>
<div id="talk">
<form id="talkForm" action="" method="GET" onsubmit="askCow(this)">
<input type="text" name="query" value="" />
<input type="button" name="talk" value="talk" onClick="askCow(this.form)" />
</form>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js" type="text/javascript" charset="utf-8"></script>
<script type="text/coffeescript">
$j = jQuery
window.askCow = (form) ->
$j.get "/cowanswer",
{q: form.query.value},
(data) -> $j("#cow pre").html(data["cow-answer"])
return false
</script>
</html>
Just use onsubmit event of form
<form action="" method="GET" onsubmit="return askCow(this);">
<input type="text" name="query" value="" />
<input type="button" name="talk" value="talk"/>
</form>
askCow function should look something like this
function askCow()
{
//do ajax stuff
return false;
}
You can use jQuery Form Plugin .
And within the call, you can call askCow() .
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#theForm').submit(function() {
askCow(this);
$(this).ajaxSubmit(options);
return false;
});