Forms - synchronous request and displaying a div on submission - javascript

I'm making a yahtzee-type two player dice game. To start the game, the user enters 2 names and submits, which should start the game and display the dice area. I've done a lot of trial and error, but I haven't been able to submit the form, get the input, and show the play area.
HTML:
<div id="top_area">
<div id="new_game_form">
<form action="http://examples.funwebdev.com/process.php" method="post" name="new_game">
Player 1:
<br>
<input type="text" name="player1">
<br> Player 2:
<br>
<input type="text" name="player2">
<br>
<input id="newGameSubmit" type="submit" value="Start Game">
</form>
</div>
<div id="player_turn">
Please enter player names and load a new game!
</div>
<div id="player_scores">
Current Score
</div>
</div>
<div id="play_area">
<div class="play_div" id="game_board">
<a class="diceimage" id="dice1"></a>
<a class="diceimage" id="dice2"></a>
<a class="diceimage" id="dice3"></a>
<a class="diceimage" id="dice4"></a>
<a class="diceimage" id="dice5"></a>
</div>
<div class="play_div" id="submit_move">
<form class="play_div" action="http://examples.funwebdev.com/process.php" method="post" name="submit_move">
<input type="submit" value="Roll the dice!" onclick="rollDice()">
</form>
</div>
<div id="submit_score">
<form action="">
<select name="Score">
<option value="2OfAKind">Two of a kind</option>
<option value="3OfAKind">Three of a kind</option>
<option value="4OfAKind">Four of a kind</option>
<option value="5OfAKind">Five of a kind</option>
<option value="fullHouse">Full house</option>
</select>
<input type="submit" value="Submit your score">
</form>
</div>
</div>
JavaScript:
$(document).ready(function () {
//game setup
$("#new_game").on("submit", newGameListener);
});
function newGameListener(e) {
e.preventDefault();
setUpUsers();
$(".play_area").show();
}
I've also tried:
$(document).ready(function () {
$("#new_game").submit(function (event) {
var newGameData = {
"player1": $("input[name=player1]").val(),
"player2": $("input[name=player2]").val()
};
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
(".play_area").show();
});
event.preventDefault();
});
});
and:
$(document).ready(function () {
$("#newGameSubmit").click(function () {
event.preventDefault();
var player1 = $("#player1").val();
var player2 = $("#player2").val();
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: dataString,
cache: false,
success: function () {
(".play_area").show();
}
});
}
return false;
});
});
I suspect my usage of form name may be wrong (should I be using id instead? is the # right? etc.) but I've played around with that and still couldn't get it.

I tried modifying your last approach. I hope it will work once you update it with below modified code:
In your HTML; play_area is an id given to <div> element. So to deal with it JQuery we need to use # and not the dot. Like $("#play_area").show();
CSS:
#play_area{
display:none;
}
Jquery:
$(document).ready(function () {
$("form[name=new_game]").submit(function (e) {
return false;
});
$("#newGameSubmit").click(function (event) {
event.preventDefault();
var player1 = $("#player1").val();
var player2 = $("#player2").val();
var newGameData = {
"player1": player1,
"player2": player2
};
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: newGameData,
cache: false,
success: function () {
$("#play_area").show();
}
});
});
});
I have created a fiddle too; but it won't work because we can't make cross domain Ajax calls from within jsfiddle.net to your funwebdev.com domain.
But you can refer it:
http://jsfiddle.net/vijayP/bkvw95jn/2/

Fixed the form not being submitted. Check the following code.. !!
<script>
jQuery(document).ready(function($) {
$("#new_game").submit(function() {
var newGameData = {
"player1": $("input[name=player1]").val(),
"player2": $("input[name=player2]").val()
};
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: newGameData,
dataType: 'json',
encode: true,
success: function(data) {
(".play_area").show();
alert(data);
}
});
return false;
});
});
</script>
</head>
<body>
<div id="top_area">
<div id="new_game_form">
<form action="#" method="post" id="new_game" name="new_game">
Player 1:
<br>
<input type="text" name="player1">
<br> Player 2:
<br>
<input type="text" name="player2">
<br>
<input id="newGameSubmit" type="submit" value="Start Game">
</form>
</div>
<div id="player_turn">
Please enter player names and load a new game!
</div>
<div id="player_scores">
Current Score
</div>
</div>
<div id="play_area">
<div class="play_div" id="game_board">
<a class="diceimage" id="dice1"></a>
<a class="diceimage" id="dice2"></a>
<a class="diceimage" id="dice3"></a>
<a class="diceimage" id="dice4"></a>
<a class="diceimage" id="dice5"></a>
</div>
<div class="play_div" id="submit_move">
<form class="play_div" action="http://examples.funwebdev.com/process.php" method="post" name="submit_move">
<input type="submit" value="Roll the dice!" onclick="rollDice()">
</form>
</div>
<div id="submit_score">
<form action="">
<select name="Score">
<option value="2OfAKind">Two of a kind</option>
<option value="3OfAKind">Three of a kind</option>
<option value="4OfAKind">Four of a kind</option>
<option value="5OfAKind">Five of a kind</option>
<option value="fullHouse">Full house</option>
</select>
<input type="submit" value="Submit your score">
</form>
</div>
</div>

Related

PHP Submitting a form without refreshing the page and call a function

We have created a feedback form and once a user submits the feedback, we want to run the function that submits it to Airtable and then show the Next button.
Problem: The jQuery is working, showing the button after submit, but the function in (isset($_POST['submit']) isn't saving at all.
I've read through many posts but can't find the answer. Any help would be great!
Here is our current code
public function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&comments='+comments+'&reason='+reason,
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason2</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
if (isset($_POST['submit'])){
$reason = $_POST['reason'];
$comments = $_POST['comments'];
save($reason, $comments);
}
?>
<?php
}
I assume you want to transfer the entries "reason" and "comment" to the page "requests.php". Then you don't need the second post request because you use ajax:
<?php
function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'get',
data: { 'result' : comments +'*'+reason, 'feedback' : 'true' },
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason3</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
}
The "request.php" looks like this:
<?php
if(isset($_GET['feedback']))
{
$result = $_GET['result'];
$parts = explode("*", $result);
print "reason: ".$parts[1]."<br>";
print "comments: ".$parts[0]."<br>";
}
?>
What I can see from the snippet is that:
if (isset($_POST['submit'])){
While the submit button is:
<input type="submit" value="submit" name="subbtn" >
Just fix this line:
isset($_POST['submit'] to isset($_POST['subbtn']
Hope this helps.

When I select the options from the dropdown the button should be triggered automatically and produce the unique Id

I have a drop down and when I select one option from the dropdown the button has to be triggered automatically and it produces some unique id. I am not sure how the trigger can happen when we select the value from the dropdwon.
I have refered this link
Auto trigger click on a button when selecting from dropdown list
but its not working and its not showing any error. I can see that its not going inside the button click function. can someone help me how to do the auto click when we select the dropdown option?
I am attacching the code here
<div id="dialog-form" title="Send Email Invite">
<form>
<fieldset>
<label for="select1">Round Level</label>
<div class="col-md-4">
<select name="select1" class="form-control" id="select1" style="width:200px; height:30px;" required>
<option value="">Select the below option</option>
{% for each_round in round_names %}
<option value="{{each_round.round_id,each_round.round_name}}">{{each_round.round_name}}</option>
{% endfor %}
</select>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">Please fill out this field</div>
<div class="col-md-4" id="generateButton" style="display:none;" required>
<input id="generateUrl" value="generate url" size="40%" readonly />
<input type="button" class="btn btn-info" value="Generate URL" id="urlbutton"></input>
</div>
<div id="result">
<textarea name="rdesc" id="rdesc" style="width:200px; height:300px; display:none;"
required></textarea>
</div>
</div>
<script>
$("#select1").on('change', function () {
$("[name='select1']:submit").trigger("#urlbutton")
var dropdownValue = document.getElementById("select1");
var roundName = dropdownValue.options[dropdownValue.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'blah',
data: {
'blah': blah
},
success: function (results) {
$("#rdesc").show();
$("#rdesc").text(results.round_description);
}
})
})
</script>
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<script>
$("#urlbutton").click(function () {
console.log("i am coming here");
$.ajax({
type: 'POST',
url: 'blah',
data: {
'blah':blah
},
success: function (data) {
var url_textbox = document.getElementById("generateUrl");
url_textbox.setAttribute('value', data.url);
}
})
})
</script>
You can click the button programmatically like this.
On your select change click the button.
("#urlbutton").click()

How to post form submit to database along with ID logged in console

I am trying to add a form submission in a bootstrap modal along with an ID of the row that was clicked to open to modal to a database. I can add the ID alone and I can add the form submission alone, but I cannot combine these two sources of information in the same database.
In the code below I get the ID (var uid), and it is logged in the console.
Is it possible to add that logged value to the ajax post? And how can I do that, so it is sent along with the form values?
$(document).ready(function () {
$(document).on('click', '#getUser', function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
console.log(uid);
$("#bestilform").on("submit", function(e) {
var formURL = $(this).attr("action");
var antal_ordre = $("antal_ordre").val();
var navn_ordre = $("navn_ordre").val();
var email_ordre = $("email_ordre").val();
var telefonnummer_ordre = $("telefonnummer_ordre").val();
$.ajax({
url: formURL,
type: "POST",
data: {'id': uid, 'antal_ordre': antal_ordre, 'navn_ordre': navn_ordre, 'email_ordre': email_ordre, 'telefonnummer_ordre': telefonnummer_ordre},
dataType: 'json'
})
hide modalcontant and show order
success: function(data, textStatus, jqXHR) {
$("#seordre").show();
$("#afgivordre").hide();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
//submit form with id #submitForm
$("#submitForm").on('click', function() {
$("#bestilform").submit();
});
});
</script>
this data: 'id': uid just gives me a 0 in the database. I am converting to integer in my php file.
Define your var uid outside of the function which sets it and the function which needs it. Make it global for both functions. (not the best way to do). The better way to pass the parameter to the function which does submit. In this case you'll achieve consistency and your UID never will be undefined. You code may looks like ...
$(document).ready(function() {
//define variable
var uid;
$(document).on('click', '#getUser', function(e) {
e.preventDefault();
// set it in one function
uid = $(this).data('id'); // get id of clicked row
console.log(uid);
// and call another one
$("#bestilform").submit();
});
$("#bestilform").on("submit", function(e) {
var formURL = $(this).attr("action");
var antal_ordre = $("select[name$='antal_ordre']").val();
var navn_ordre = $("input[name$='navn_ordre']").val();
var email_ordre = $("input[name$='email_ordre']").val();
var telefonnummer_ordre = $("input[name$='telefonnummer_ordre']").val();
// uid will be avaiable over here
$.ajax({
url: formURL,
type: "POST",
data: {
'id': uid,
'antal_ordre': antal_ordre,
'navn_ordre': navn_ordre,
'email_ordre': email_ordre,
'telefonnummer_ordre': telefonnummer_ordre
},
dataType: 'json'
});
// something else???
return false;
});
//submit form with id #submitForm
$("#submitForm").on('click', function() {
$("#bestilform").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="getUser" data-id="67">click me</td>
</tr>
</table>
<br><br>
<form method="post" action="bestil.php" data-toggle="validator" role="form" class="form-group" id="bestilform">
<!-- antal måltider, som køber vil bestille-->
<div class="form-group">
<label>Antal måltider</label>
<select class="form-control selectpicker" name="antal_ordre">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<!-- navn på køber-->
<div class="form-group">
<label for="InputName1">Fulde Navn</label>
<input name="navn_ordre" type="text" class="form-control" id="exampleInputName1" placeholder="Indtast dit navn">
</div>
<!-- email på køber-->
<div class="form-group">
<label for="InputEmail1">Email</label>
<input name="email_ordre" type="email" class="form-control" id="exampleInputEmail1" placeholder="Indtast din e-mail" data-error="Hov! Det er vist ikke en email...">
<div class="help-block with-errors"></div>
</div>
<!-- telefonnummer på køber-->
<div class="form-group">
<label for="InputPhonenumber1">Telefonnummer</label>
<div class="input-group">
<span class="input-group-addon">+45 </span>
<input name="telefonnummer_ordre" data-minlength="8" type="number" class="form-control" id="exampleInputPhone1" placeholder="Indtast dit telefonnummer">
</div>
</div>
<!--modal footer-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" data-toggle="modal" data-target="#lavbestillingaccepter">Tilbage
</button>
<button type="button" class="btn btn-primary" id="submitForm" form="bestilform">Køb Måltid!
</button>
</div>
</form>

Form submission works with html but not javascript at the same time

I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});

Ajax - How to submit one by one input value - Codeigniter

Sorry for my english is not so good. And i'm newbie :)
I want to update one-by-one input value with ajax in Codeigniter, but it not work right.. only one save button (one form) work, others form not work .. please help me edit below code
Here's the demo code:
View:
<script>
$(function(){
$(".submit45").click(function(){
dataString = $("#prod_upd").serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
document.getElementById('dd').innerHTML=data;
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" id="prod_upd" method="post" >
<input type="text" name="p_ppx" id="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" id="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="button" name="sub" id="sub" class="submit45" value="Save4" />
<div id="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>
Controller:
function change_ppx3(){
$id_p = $_POST['ids_p'];
$rs = $this->ppx->get_ppx_by_id($id_p);
$ppx_value = $_POST['p_ppx'];
$this->ppx->update_ppx(array("id"=>$id_p),array("ppx_r"=>$ppx_value));
if($_POST['p_ppx']):
echo "done: ";
print_r($_POST['ids_p']);
echo "-";
print_r($_POST['p_ppx']);
return true;
endif;
}
because every form has the same id="prod_upd".
test this
<script>
$(function(){
$(".prod_upd").submit(function(){
var $this = $(this), dataString = $this.serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
$this.find('.dd').html(data);
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" class="prod_upd" method="post" >
<input type="text" name="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="submit" class="submit45" value="Save4" />
<div class="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>

Categories

Resources