updating SQL database using ajax and grails - javascript

I am working with grails, in springsource tool suite, and I am facing a problem updating the SQL databse. In the page, the user is asked to enter details of his property, say address, city etc., and once clicking on button 'save' the details need to be saved in the database. Now what I need to do is, dynamically add the input fields (of address, city, etc) to the page, everytime the user clicks on button 'add'. So because of this, i need to use AJAX to post the data to the server. However, I am having trouble updating it. Here is the code of the view(.gsp file)-
<head>
<script type="text/javascript">
var rad1, rad2, button1, button2;
function add() {
var newP = document.createElement("p");
var input1, input2,
area = document.getElementsByTagName("form")[0];
input1 = document.createElement("input");
input1.type = "text";
input1.placeholder = "street";
input1.id = "address";
newP.appendChild(input1);
input2 = document.createElement("input");
input2.type = "text";
input2.placeholder = "city";
input2.id = "city"
newP.appendChild(input2);
area.appendChild(newP);
}
</script>
</head>
<body>
<form name='prop' method="post" action="save">
<g:hiddenField name="owners.id" value="${session.user.id }" />
<input type="button" value="+Add" onclick= "add();" ><br>
<input type="button" name="create" id="save_button" class="save" value="save" />
</form>
<script type="text/javascript" src="ajax.js"></script>
</body>
Here is what my Ajax code looks like in a separate ajax.js file-
$('#save_button').click(function() {
var street = $('#address').val();
var city = $('#city').val();
$.ajax({
type: "POST",
url: "${createLink(controller: 'property', action: 'save')}",
data: { address: street, city: city },
success: function(data) {
alert(data);
}
});
});
And here is the code in my property controller(save action)-
def save = {
def propertyInstance = new Property(params)
if (propertyInstance.save(flush: true)) {
flash.message = "Property successfully added."
redirect(controller:"user", action: "show", id:params.owners.id)
}
else {
render(view: "create", model: [propertyInstance: propertyInstance, id:params.owners.id])
}
}
What am I doing wrong here? I am not at all familiar with Ajax, so sorry if its an obvious mistake.. please help.

$('#address').val(); and $('#city').val(); will get you the value of the first #address or #city element jQuery finds. If you want to make, let's say, an array for all the address and city values provided you could do this:
var cities = [];
var addresses = [];
$('#address​​​​').each(function() {
addresses.push($(this).val());
});​
$('#cities​​​​').each(function() {
cities.push($(this).val());
});​
If there's two address and city inputs on the page, the result will look something like this:
console.log(addresses); // [address1, address2]
console.log(cities); // [city1, city2]
Edit: To reset the fields on submission (or "add" if you change the jQuery selector), you could do this:
$('#save_button').click(function() {
// ... all your regular ajax stuff ...
// reset the fields
$('#address').val('');
$('#city').val('');
// ... and so on until you reset all fields
});

Related

Save text field to a variable using jQuery, showing undefined

I am trying to save the text field with the id #modelBox to a global variable so that it can be used later. However it seems no matter what I try the modelNumber is alerting 'undefined'. Any help is appreciated.
<input type = "textbox" value = "Enter Model Number" id="modelBox">
var modelBox="";
$('#modelBox').val('test');
var modelNumber = $('#modelBox').val();
alert(modelNumber);
var manufacturer = "unknown";
$(document).ready(function(){
$('#submit').click(function findManufacturer(){
var firstFour = modelNumber.substring(0,4);
if (firstFour.includes("B")){
manufacturer = "AU Optronics";
$('#answer').after("AU Optronics");
}else{
$('#answer').after("No Manufacturer found");
}
});
});
this needs to be INSIDE your click handler so that you grab the value when you click. The way you have it, the val gets set on page load -- which is likely undefined at that point.
var modelNumber = $('#modelBox').val();
$('#submit').click(function findManufacturer(){
var modelNumber = $('#modelBox').val();
var firstFour = modelNumber.substring(0,4);
if (firstFour.includes("B")){
manufacturer = "AU Optronics";
$('#answer').after("AU Optronics");
}else{
$('#answer').after("No Manufacturer found");
}
});
});
EDIT: You can also place it outside of the click handler, so long as it is inside the docready, and the field never changes between page load and clicking the submit button.
I just tried your code in below snippet, it alerts 'test'. Found no issue!
var modelBox = "";
$('#modelBox').val('test');
var modelNumber = $('#modelBox').val();
alert(modelNumber);
var manufacturer = "unknown";
$(document).ready(function() {
$('#submit').click(function findManufacturer() {
var firstFour = modelNumber.substring(0, 4);
if (firstFour.includes("B")) {
manufacturer = "AU Optronics";
$('#answer').after("AU Optronics");
} else {
$('#answer').after("No Manufacturer found");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="textbox" value="Enter Model Number" id="modelBox">

Why do my DOM changes disappear when I click a form button?

This is my first post, so consider me a n00b.
I have created a simple form to access a value stored in a javascript array. I am trying to append an element to display the proper value. The logic works, my result will show, but only briefly, before it is overwritten. Can you help?
html
<form>
<input type="text" label = "sitex" id="site"><br>
<input type = "submit" value = "Submit" onclick="getFormData(document.getElementById('site').value)">
</form>
<div id = "result"><p>Results:</p></div>
<script type="text/javascript" src="logic.js"></script>
javascript
var results = "";
function getFormData(val1) {
var pw = {
"site1": "xyzabc",
"site2": "defghi",
"site3": "jklmno",
"site4": "pqrstu",
"site5": ["id1", "vwxyza"],
"site6": ["id2", "bcdefg"],
"site7": "hijklm",
"site8": ["id3", "nopqrs"],
"site8": ["id4", "tuvwxy"],
"site9": ["id5", "zabcde"],
"site10": "fghijk",
"site11": ["id6", "lmnopq"],
"site12": "rstuvw"
};
results = pw[val1];
showResults(results);
}
function showResults(val2) {
var div = document.createElement('div');
var pss = document.createTextNode(val2);
div.style.color = "red";
div.appendChild(pss);
document.getElementById("result").appendChild(div);
}
You're actually submitting your form when you click the Submit button and page is reloading. Just change the type of button from submit to button:
<input type="button" value="Submit" onclick="getFormData(document.getElementById('site').value)">
Pass your Javascript function 2 arguments, the first is the event object, the second is the value you are passing. You can then use this to prevent the default behavior of a form (which is to submit the form and refresh the page)
<form>
<input type="text" label = "sitex" id="site"><br>
<input type = "submit" value = "Submit" onclick="getFormData(event, document.getElementById('site').value)">
<div id = "result"><p>Results:</p></div>
<script type="text/javascript" src="logic.js"></script>
then in your javascript, prevent the default behavior with .preventDefault();
var results = "";
function getFormData(event, val1) {
event.preventDefault();
var pw = {
"site1": "xyzabc",
"site2": "defghi",
"site3": "jklmno",
"site4": "pqrstu",
"site5": ["id1", "vwxyza"],
"site6": ["id2", "bcdefg"],
"site7": "hijklm",
"site8": ["id3", "nopqrs"],
"site8": ["id4", "tuvwxy"],
"site9": ["id5", "zabcde"],
"site10": "fghijk",
"site11": ["id6", "lmnopq"],
"site12": "rstuvw"
};
results = pw[val1];
showResults(results);
}

Using AJAX to send and receive info from a server

I'm working on a page that is supposed to interact with the server via AJAX, but my experience with AJAX is extremely limited. Here's how the page is supposed to work.
When the button is clicked, if the "test" radio button is clicked, just display a pop up saying the input was valid.
When the button is clicked, if the "live" radio button is clicked, the program is supposed to send a request to the server using the URL "http://cs.sfasu.edu/rball/351/exam2.php" with the contents of the input box being the value for the "name" parameter.
The page will then send back a JSON object that I need to parse into a regular variable.
I'll leave the rest of the JSON stuff alone since that's not what I asked.
So far I have the design of the page done, but like I said I don't really know what I'm doing with the AJAX stuff. I have some code written for it, but not sure that it's right.
Here is my code:
<html>
<head>
<title>anner, Taylor</title>
<style type = "text/css">
canvas {
border: 2px solid black;
}
</style>
<script type = "text/javascript">
window.onload = function() {
var TTcanvas = document.getElementById("myCanvas");
var TTcontext = TTcanvas.getContext("2d");
TTcontext.strokeStyle = "red";
TTcontext.fillStyle = "red";
TTcontext.fillRect(250,50,100,100);
TTcontext.stroke();
TTcontext.beginPath();
TTcontext.moveTo(600, 0);
TTcontext.lineTo(0, 200);
TTcontext.lineWidth = 5;
TTcontext.strokeStyle = "black";
TTcontext.stroke();
}
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
var TTtest = document.getElementById("test");
var TTlive = document.getElementById("live");
if(TTtest.checked == true) {
alert("Input is valid");
}
else if(TTlive.checked == true) {
return ajaxStuff();
}
}
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
var TTresponse = TTrequest.responseText;
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML.TTresponse;
}
}
}
</script>
</head>
<body>
<h1>Tanner, Taylor</h1>
<canvas id = "myCanvas" width = "600" height = "200"></canvas> <br>
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "radio" id = "test" value = "test">Test
<input type = "radio" id = "live" value = "live">Live <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
<div id="myDiv">
</div>
</body>
</html>
And here is a link to my page on our server:
cs.sfasu.edu/cs351121/exam2.html
Also, I know it says exam, but this is actually just a review we were given for the actual exam that's next week. I'm just trying to figure out how this works but don't know what I'm doing wrong.
I'm not sure what the problem is. The code is correct
Ok now i get the problem. You are calling the request variable outside the scope. You are declaring the request variable inside your ajaxStuff function so its only accessible in that area. Thats why it is undefined. Try this:
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML=TTrequest.responseText;
}
}
}
to get the result just do this
TTrequest.send();
var response=TTrequest.responseText;
I know, I do not see the jQuery tag, but consider it if there are no framework restrictions.
Example:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});

Get a value from Javascript

I want to get the value that I entered in the prompt, and save it in a variable to use it to update a DB later .. I try this but is does not work !!
#{
var fileName = "";
var db = Database.Open( "GP" );
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
<html lang="en">
<body>
<script>
function myFunction() {
newName = prompt("Please enter new file name :");
if (newName != null)
{
#fileName = newName;
}
}
</script>
</body>
</html>
JavaScript is client side language. You can't updated db with it. You can send request to your server side script, which will update something in datatable.
You can find example of doing this here or just use google.
Try this code:
$(document).ready(function() {
var fileName = '';
var newName = prompt('Please enter a new file name');
if(newName != null) {
fileName = newName;
console.log(fileName);
}
});
Its getting the value you entered through javascript.
Demo here
From your question is not clear what is your goal.
If you want to store a value in your page waiting to use it when the page is posted, you could use a hidden input field.
In my example the value inputed when the page is loaded is stored until the user clicks the submit button:
#{
if(IsPost){
var fileName = Request["fileName"];
var db = Database.Open("GP");
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
}
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<form method="post">
<input type="hidden" name="fileName" id="fileName" value="" />
<input type="submit" />
</form>
<script>
$(document).ready(function () {
var newName = prompt('Please enter a new file name');
$('#fileName').val(newName);
});
</script>
</body>
</html>
Else, if you want to update your database without submitting your page, you should use Ajax. This article could help you: Posting Data With jQuery AJAX In ASP.NET Razor Web Pages.

Pass Multiple values via AJAX

I am stuck in passing the multiple value through AJAX call in Codeigniter.
My View is :
<script>
$( document ).ready(function() {
var current_id = 0;
$('#btn').click(function(){
nextElement($('#Outer_00'));
})
function nextElement(element){
var newElement = element.clone()
.find("input:text").val("").end();
var id = current_id+1;
current_id = id;
if(id <10)id = "0"+id;
$('input', newElement).attr("id", id );
newElement.appendTo($("#elements"));
if($('#elements').find('div').length=='5')
{
$('#btn').prop('disabled',true);
}
}
$('#exercises').on('click', '.remove', function() {
if($('#elements').find('div').length<'6')
{
$('#btn').prop('disabled',false);
}
if($('#elements').find('div').length=='1')
{
$('.remove').addAttr("disabled",true);
}
$(this).parent().remove();
return false; //prevent form submission
});
});
</script>
/******************************
<script>
var base_url = '<?=base_url()?>';
$(document).ready(function()
{
$('#Edit').click(function()
{
$('#Name').removeAttr("disabled");
});
$('#Add').click(function()
{
$('#Name').attr("disabled","disabled");
$('#Phone').attr("disabled","disabled");
$('#email').attr("disabled","disabled");
$('#CurrentlyLocated').attr("disabled","disabled");
$('#KeySkills').attr("disabled","disabled");
//var queryString = $('#form1').serialize();
$.ajax({
url: '<?php echo site_url('PutArtistProfile_c/formDataSubmit');?>',
type : 'POST', //the way you want to send datas to your URL
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
success : function(data)
{ //probably this request will return anything, it'll be put in var "data"
$('body').html(data);
}
});
});
});
</script>
<p>
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" id="00" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
<div id="count"></div>
<input type="button" id="btn" value="Add Audio"></button>
</p>
My Controller is :
public function formDataSubmit()
{
$queryAudio1 = $this->input->post('Audio1');
$queryAudio2 = $this->input->post('Audio2');
$queryAudio3 = $this->input->post('Audio3');
$queryAudio4 = $this->input->post('Audio4');
$queryAudio5 = $this->input->post('Audio5');
}
How can I pass Multiple Values of text box? The above code is passing the values to the controller. But on clicking 'x' Button the value of text box is been getting deleted, but the id of the textbox is getting Incremented, Thus I am not able to pass the further values of textbox to controller via AJAX. Please help me over here.
instead of doing :
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
You can do as
data:$("#Form_id").serialize(); // all form data will be passed to controller as Post data.
If you have a remove button then getting the value by id may result in a js error, Why don't you make use of html element array:
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" name="audio[]" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
IT is very simple:
Consider you want to pass: user name, surname, and country. These are
three input boxes then:
using Jquery do so:
Javascript side
$.post("url",{name:name,surname:surname,country:country},
function(data){
console.log("Query success");
});
In your Model or controller where your Query will be handled
$name=$this->input->post("name");
$surname=$this->input->post("surname");
$country=$this->input->post("country");
in your case just pass parameters that YOU need. I use codignitter and
this method works fine!

Categories

Resources