I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.
Related
I have some google script that generates an initial form then gathers a number does a lookup and then is supposed to return a second form (getfamily function). The second form which is dynamically generated returns blank. I can see the formHTML variable with data in the logger, but it comes up blank in the browser. Any suggestions would be appreciated.
var ssID="xxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
function doGet() {
var html = HtmlService.createTemplateFromFile('index2').evaluate()
.setTitle('Lookup').setSandboxMode(HtmlService.SandboxMode.NATIVE);
return html;
};
function getfamily(form){
Logger.log(form.familyid);
var ssID="xxxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
var formHTML = "<!DOCTYPE html>";
formHTML +="Hello!";
formHTML += '<form id="students">';
var filteredRows = rows.filter(function(row){
var message="made it";
if (row[0] === form.familyid) {
Logger.log(row[2]);
formHTML+= '<input type="checkbox" name ="students value='+ row[1] + '">'+ row[2] + '<br>';
return row[2];
}
});
formHTML+='<input type="submit" value="CheckIn">';
formHTML+='</form>';
Logger.log(formHTML);
var output = HtmlService.createHtmlOutput(formHTML).setSandboxMode(HtmlService.SandboxMode.NATIVE);
return output;
};
Your input type="checkbox" line is hard to figure out what you want. I presume that you plan in insert this form into an already exist DOM so no need the worrying about other tags just stick it in whatever div you have prepared for it.
function getfamily(form){
var ssID="xxxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
var formHTML='<form id="students">';
var message="made it";
rows.forEach(function(row){
if (row[0]==form.familyid) {
formHTTML=Utilities.formatString('<input type="checkbox" name="students" value="%s" /><br />',row[2]);//I presume that you want to change the name but I cant tell how you planned to do it.
}
});
formHTML+='<input type="button" value="CheckIn" onClick="proceesForm(this.parentNode);" />';
formHTML+='</form>';
return HtmlService.createHtmlOutput(formHTML);
};
You can use submit if you really must but I find using google.script.run to be a lot easier. We need to see more of what you're doing to provide a complete answer.
I have an input box and a go button. When the user clicks the go button I want to compare the inserted value with another value. I am trying to acquire the input value inside a function like so
function getInput(){
var entry ='';
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
//return entry
})
return entry
}
Basically I want to return the var entry that has an input value, so I could compare the values later in the code
var input = getInput() // this should have input value
is input > othervalue
I call getInput inside document.ready()
You are doing everything right . There are some scope related issues that is not helping you to get the expected result . My suggestion would be to define othervalue variable as global and check it inside the function like this
function getInput(){
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
if(entry>othervalue) //your code
});
}
I am not sure why you are binding dynamic click event inside a function . If there is nothing else you need to do here except this part, then wrap this piece of code inside document.ready.
I would suggest to declare your var entry =''; globally and assign it before comparing.
var entry="";
$('button.go').on('click',function(){
entry = $(this).siblings('.input').val();
});
//do the comparing..
You should do the comparing, after delegating the click function, inside the function.
var entry = "";
$('button.go').on('click', function(){
var entry = $(this).prev('.input').val();
if (entry < x)
// Do something
});
It remains unclear to me what you want to accomplish.
I made some code that might be somewhere near what you want.
jQuery().ready(function()
{
var startValue = $('input[name="the_input"]').val();
$('form').submit(function()
{
var currentValue = $('input[name="the_input"]').val();
$('body').append('<br />' + startValue + ' - ' + currentValue + ' = ' + (startValue - currentValue));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post">
<input type="text" value="10" name="the_input" /><br />
<input type="submit" value="go!" />
</form>
I have following code to implement simple practice shopping cart using JavaScript. There is a checkout link which calls getcookie() to check the value of the cookies stored. When nothing is in the cookie then click on the link alerts to make input. If non of the values are entered in the input box and hit "add to cart" then validation is done and error message is alerted.
For some reason, the cookie is not taking the value from the input field. I tried quite a while now but was not able to debug the code. Just an empty alert box is shown at last. I appreciate any debugging. Thanks in advance.
<script type="text/javascript">
var value;
var productID;
function setItem(abd) {
value = abd.value;
productID = abd.getAttribute("productID");
var intRegex = /^\d+$/;
var numberOfItems;
if (!intRegex.test(value) || (value <= 0)) {
alert('Please Enter valid numberofitem');
} else {
numberOfItems = value;
}
}
function getCookie() {
if (value == undefined) {
alert("There is nothing in the shopping cart!");
} else {
var cookieArray = document.cookie.split(';');
var printHolder = "";
for (var i = 0; i < cookieArray.length; ++i) {
var pairArray = cookieArray[i].split('=');
alert(pairArray[0]);
}
alert(printHolder);
}
}
function setCookie() {
if (value == undefined) {
alert("Please add number of items in text box");
} else {
document.cookie = productID + "=" + value + "; ";
alert(value + " Product(s) with id " + productID +
" has been added to shopping cart!");
}
}
</script>
Checkout
<input name="item-select" id="item-select"
productid="p001" style="width: 50px" onBlur="setItem(this)" >
<button type="button" onclick="setCookie()">Add to cart.</button>
The result I wanted is something like this at last!
This code works perfectly fine with some changes.
I was using chrome and later found out that
Google Chrome doesn't create cookies when the file is on the local machine and loaded in browser directly using file path.
Rather try with localhost. It is definitely working when you put the code in server. Chrome became pain in a b*t here!
If you were for idea on creating shopping cart with Javascript follow this link.
http://www.smashingmagazine.com/2014/02/create-client-side-shopping-cart/
Your getCookie is likely to give you incorrect results.
var cookiearray= document.cookie.split(';');
var toprint="";
for(var i=0; i<cookiearray.length; ++i)
{
var pairArray= cookiearray[i].split('=');
alert(pairArray[0]);
}
alert(toprint);
Two things wrong here;
1) When you are in your for loop, each time you loop you are alerting the first item in your array at all times pairArray[0] you need to change that to pairArray[i]
2) You are displayed with an empty alert because thats what you have assigned to the toprint variable.
- You assign toprint an empty string before your for loop, then you are alerting that variable without assigning it a new value, so you will be displayed with an empty alert box!
- Also make sure your cookie array is not empty.
Give that a try, enjoy coding :)
Kush
How do I use JavaScript to write cookies from form fields, and then print the info in an alert or hidden div?
Here is an example of what I have tried thus far.....
<script type="text/javascript">
function cookieForm() {
document.cookie = "name_first" + encodeURIComponent(document.forms[0].name_first.value);
}
function printCustomerInfo() {
var queryData = decodeURIComponent(document.cookie);
var queryArray = queryData.split(";");
if (document.cookie) {
window.alert("Your info. is:" + queryArray[0]);
window.alert[0].name_last.value = QueryArray[1].substring(queryArray[1].lastIndexOf("=") + 1);
}
}
</script>
<input type="submit" value="Submit" onclick="cookieForm(), printCustomerInfo()"/>
First, you're missing the "=" in the cookie string:
document.cookie = "name_first=" + encodeURIComponent(document.forms[0].name_first.value);
Second, your queryData has no ";" to split by, and no last name value - at least from what you show here.
This I do not understand:
window.alert[0].name_last.value = ...
I would call a single function from your event, and let that parent both setting the cookie and parsing it. That way you can at least debug it better.
re: a div, you could do something like this:
document.getElementById("yourDiv").innerHTML = "Your info. is:" + queryArray[0];
document.getElementById("yourDiv").style.visibility = 'visible';
But in general it's better to use jquery for manipulating elements, because it mitigates browser differences, though it wouldn't matter in this case:
$("yourDiv").html("Your info. is:" + queryArray[0]);
$("yourDiv").css ( { 'visibility': 'visible' } );
Good luck.
I have a bit of a predicament. I am trying to run a variable on a loop so that it can change the loop. Here is the code that I have at the present time.
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" id="Variable"><P>
</FORM>
<script type="text/javascript">
document.getElementById("Variable").value = i;
var i=5;
for (i=0;i<=5;i++)
{
document.write(" " + i);
document.write("<br />");
}
</script>
I am trying to call upon the text in the textbox from the form in order to define var i. I would also like to point out that I am no master of HTML, and if you see that I have done this all wrong, feel free to tell me that it cannot be done.
I think you mean something like this:
var count = parseInt(document.getElementById("Variable").value, 10);
var i;
for (i = 0; i < count; ++i) {
// ...do something...
}
What that does:
Looks up the element by its ID (you already had that): document.getElementById("Variable').
Retrieves the value of its value property, which is a string.
Converts the string into an number via parseInt, using decimal (as opposed to octal or hexadecimal).
Loops from zero (inclusive) to that number (exclusive).
Note that you can't use document.write after the main parse (initial load) of the page, and you probably don't want to use the value from a form field before the main parse of the page is complete, so you probably won't be doing document.write here. You might set the innerHTML of an element, something like that.
Re my "...you can't use document.write after the main parse...": Technically, you can, but you'll completely replace the page rather than just adding to it.
Re my "...and you probably don't want to use the value from a form field before the main parse...is complete...": You can, though, as long as the form field is above the script in the page markup. I did literally mean you probably don't want to, presumably you want the user to enter some value first.
Update: Here's a more complete example, with a live copy to play with:
var element, value, count, i;
element = document.getElementById("Variable");
if (!element) {
display("Element 'Variable' not found.");
}
else {
value = element.value;
count = parseInt(value, 10);
if (isNaN(count)) {
display("'" + value + "' is not numeric");
}
else {
for (i = 0; i < count; ++i) {
display("Loop " + i);
}
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
Live copy, the display function is obviously a bit of a placeholder for whatever it is you actually want to do.
I did not understand your exact question. but I guess this is your solution :
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" id="Variable">
<input type="button" value="run" onclick="renderIt()" />
<P>
</FORM>
<script type="text/javascript">
function renderIt()
{
var max = parseInt(document.getElementById("Variable").value);
for (i=0;i<=max;i++)
{
document.write(" " + i);
document.write("<br />");
}
}
</script>