trying to add to database using AJAX - html

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()
},
);
}
};

Related

onClick on Google Script not working for HTML Form

I'm trying to create a html pop up that will then populate a gsheet. I've basically used the same solution found here. For some strange reason though, it isn't working. When I click the submit button on the HTML pop up box after filling out all the data, it doesn't respond. I click, it doesn't close, append the data, or do anything.
The html pop up is created, but the Submit button doesn't work. I am almost sure that it is has something to do with the onClick method I am using.
Here is the code I am working with:
gs file
function registerCustomer() {
var html = HtmlService.createHtmlOutputFromFile('customerMenu.html').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add Customer');
}
function customerAdd(customerForm) {
var ss = SpreadsheetApp.getActiveSpreadsheet;
var cus_db = ss.getSheetByName("customer_db");
cus_db.appendRow([" ", customerForm.name_1, customerForm.name_2, customerForm.phone, customerForm.age, customerForm.channel]);
return true;
}
html file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<br>
<customerForm>
First Name:<br>
<input type="text" name="name_1">
<br>
Second Name:<br>
<input type="text" name="name_2">
<br>
Phone Number:<br>
<input type="text" name="phone">
<br>
Age:<br>
<input type="number" name="age">
<br>
How did they hear about us?:<br>
<input type="text" name="channel">
<br><br>
<input type="submit" value="Add Customer" class ="submit"
onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.customerAdd(this.parentNode)" />
</customerForm>
</html>
I've scoured stackoverflow for almost every solution:
I am running two pop ups so I changed the function names based on the advice here
I tried to use the '''document.forms[0]''' method found here also didn't work
What am I missing?
onClick on Google Script working for HTML Form
GS:
function registerCustomer() {
var html = HtmlService.createHtmlOutputFromFile('ah2')
SpreadsheetApp.getUi().showModelessDialog(html, 'Add Customer');
}
function customerAdd(obj) {
var ss = SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet15');
sh.appendRow(["", obj.name_1, obj.name_2, obj.phone, obj.age, obj.channel]);
return true;
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form>
First Name:<br>
<input type="text" name="name_1" />
<br>
Second Name:<br>
<input type="text" name="name_2"/>
<br>
Phone Number:<br>
<input type="text" name="phone"/>
<br>
Age:<br>
<input type="number" name="age"/>
<br>
How did they hear about us?:<br>
<input type="text" name="channel"/>
<br><br>
<input type="button" value="Add Customer" onClick="addCust(this.parentNode);" />
</form>
<script>
function addCust(obj) {
google.script.run
.withSuccessHandler(function(){google.script.host.close();})
.customerAdd(obj);
}
</script>
</body>
</html>

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.

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>

$resource.save is not functioning

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!

Posting a submit button value

In a form i am making,i need to inform the processing php script what button was clicked.I have three buttons,new,save and delete.I was expecting the form and all the buttons values to be posted but the form + the button clicked only gets posted.I am looking at the html spec here http://www.w3.org/TR/html401/interact/forms.html#submit-format but i am yet to find some explanation if this should be expected.I have this php script
<?php
/**
tpost.php
*/
//Buttons
$new = $_POST['new'];
$save = $_POST['save'];
$delete = $_POST['delete'];
//Error: Notice: Undefined index: save in C:\wamp\www\form-dev\troll.php on line 7
//Forms
$city = $_POST['city'];
$zip = $_POST['zip'];
$cs = $_POST['cs'];
//Error: Notice: Undefined index: save in C:\wamp\www\form-dev\troll.php on line 8
//Buttons echo
echo '<b>'.$new.'</b>' .'<br/>';
echo '<b>'.$save.'</b>' .'<br/>';
echo '<b>'.$delete.'</b>' .'<br/>';
//Forms echo
echo '<b>'.$city.'</b>' .'<br/>';
echo '<b>'.$zip.'</b>' .'<br/>';
echo '<b>'.$cs.'</b>' .'<br/>';
?>
this is the html i am using
<!Doctype html>
<head>
<meta charset="uft-8">
<title>Buttons post</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<style type="text/css">
label{
width:15%;
float:left;
font-style:italic;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('.inew').on("click",function()
{
alert('new');
});
$('.isave').on("click",function()
{
alert('save');
});
$('.idelete').on("click",function()
{
alert('delete');
});
});
</script>
</head>
<body>
<form action="tpost.php" name="troll" method="post">
<label>Enter Your City</label><input type="text" name="city" value="some-city"/><br/><br/><br/>
<label>Enter Your Neighbourhood</label><input type="text" name="zip" value="my-zip" /><br/><br/><br/>
<label>Enter Your Nearest Shopping Mall</label><input type="text" name="cs" value="shop-here" /><br/>
<br/><hr/><br/>
<br/>
<hr/>
<input class="inew" type="submit" name="new" value="new" />
<input class="isave" type="submit" name="save" value="save" />
<input class="idelete" type="submit" name="delete" value="delete" />
</form>
</body>
</html>
What is the explanation for this?.
I found the answer here http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
It says
If a form contains more than one submit button, only the activated
submit button is successful.