I have a project in which I have to be able make a multiple input if needed. I'm really new to JavaScript and the insert method that I'm familiar with is only POST method which I parsed it from Form. My question is how do I do to use query in my script?
This is my code and the query is needed between Do...While at the bottom:
<div id="form" class="hidden">
Nama : <input type="text" name="nama"><br/>
Kuantitas : <input type="text" name="kuantitas"><br/>
Kategori : <select name="idKategori">
<?php
while ($rowKategori = mysqli_fetch_object($resultKategori)) {
echo "<option value='".$rowKategori->id."'>".$rowKategori->nama."</option>";
}
?>
</select>
<input type="hidden" name="hidden" value="bahan">
<input type="button" id="remove" value="Remove">
</div>
<form>
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
$(document).ready(function() {
var form_index = 0;
$("#add").click(function() {
form_index++;
$(this).parent().before($("#form").clone().attr("id", "form" + form_index));
$("#form" + form_index).css("display", "inline");
$("#form" + form_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + form_index);
$(this).attr("id", $(this).attr("id") + form_index);
});
$("#remove" + form_index).click(function() {
$(this).closest("div").remove();
});
});
$("#insert").click(function() {
var i = 0;
do {
i++;
} while (i != 5);
});
im really bad at english , so let me explain it as simple as i can.
i wanted to make a form field with submit button, like the usual.
the difference is i wanted to make a clone button so i could add
more form field with single submit button.
the code that i write is something that i learn from another page and im not familiar with it.
i dont know how to get vallue from the cloned page, and i dont know how to handle the value itself in the script as i really noob at javascript
what i wanted to do is how do you get value from all cloned form field while i click the submit button? the method i familiran with is POST method, but i thinking about writedown all my query on the javascript since the POST method could not do the looping for all the formfield, thats why i make the loop on the javascript
and im sorry with my english, im not really good at it
Ok here you go, here is a fiddle of it.
https://jsfiddle.net/2ngjqxge/3/
HTML/PHP
<div id="form_block_wrapper" class="hidden"> <!-- added an outside wrapper -->
<div class="form_block" class="hidden">
Nama : <input type="text" name="nama[]"><br/>
Kuantitas : <input type="text" name="kuantitas[]"><br/>
Kategori : <select name="idKategori[]">
<?php while ($rowKategori = mysqli_fetch_object($resultKategori)): ?>
<option value="<?php echo $rowKategori->id; ?>">
<?php echo $rowKategori->nama; ?>
</option>
<?php endWhile; ?>
</select>
<input type="hidden" name="hidden[]" value="bahan">
<input type="button" name="remove" value="Remove">
</div>
</div> <!-- close #form_block_wrapper -->
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
Please note, I changed a number of things. Most importantly all the names of the inputs that would get submitted i added [], so nama becomes nama[] etc. Now if you were to submit this as a form, on the server side you would get arrays instead of single elements. Single elements would get overwritten by the next dynamically created "form_block" so this is what we would need to process them. The data you would expect on submission of the form would be like this ( assuming we had 3 "form_blocks" ):
$_POST['nama'] = [
0 => 'nama from first form block',
1 => 'nama from second form block',
2 => 'nama from third form block',
];
$_POST['kuantitas'] = [
0 => 'kuantitas from first form block',
1 => 'kuantitas from second form block',
2 => 'kuantitas from third form block',
];
//etc...
Next, I removed any ID's as we know ids in HTML elements must be unique, so there is no point messing with them when we are creating and destroying dynamic content. We could append an index as you originally did, but the selectors are simple enough so we don't really need to do this. And it's worth it to keep things simple, why over complicate it.
I also used the "alternative" PHP syntax for the while block. while(..): with a colon instead of while(..){ with a bracket. It just looks better to me when mixed with HTML to have the <?php endWhile; ?> insteadd of <?php } ?>. It doesn't matter much here as this is small. But after adding buches of PHP, you would have all these hanging } brackets everywhere. It's easier to keep track of the close of code blocks when they are like endIf; endWhile; etc. I also kept the HTML as HTML and not a big string that has to be echoed out, again because it looks better to me that way. It also makes dealing with the quotes " easier then having to concatenate PHP '<tag attr="'.$php.'">'.
These things you can do either way, just I'm a bit particular and a perfectionist when it comes to formatting and readability. Sort of set in my ways.
Javascript (jQuery)
(function($){
$(document).ready(function() {
//get and cache Outer HTML for .form_block
var selectHtml = $('.form_block:eq(0)')[0].outerHTML;
$("#add").click(function() {
$('#form_block_wrapper').append(selectHtml);
});
//use .on for events on dynamic content ( event delegation )
$("#form_block_wrapper").on('click', 'input[name="remove"]', function() {
$(this).closest(".form_block").remove();
});
$("#insert").click(function() {
//I have no idea what you want to do here?
//Are you trying to insert something into the page
//or Are you trying to insert the data into the DB, ie submit it to the server.
//you can serialze all the data https://api.jquery.com/serialize/
//$('#form_block_wrapper').serialize();
//you can get the selected options and get their value
var d = [];
$('select[name="idKategori[]"]').each( function(){
d.push($(this).val());
});
alert(d.join(','));
});
}); //document.ready
})(jQuery); //assign jQuery to $ - for compatibility reasons.
The first thing to do here is not clone the select but instead take a snapshot of it's html. Stored in selectHtml. There is several reasons why this is better.
if user changes the value of these fields, when we clone we have to reset all those values.
if we remove all form blocks, there is nothing to clone and we are struck on a page without our form elements, tell we refresh.
based just on the length of my code -vs- your orignal code, it should be obvious which method is simpler to handle. Simple is easy to read and maintain, do more with less.
Another thing to note, is you were attaching the remove button's event to each button as they are created. While this is ok, we can do better by using event delegation $.on to handle this element.
I still have no Idea what you want done with Insert,
do you mean insert something into the page
do you mean submit the form and insert the data somewhere.
but hopefully this helps
Related
I'm quite new to PHP so apologies for not being fully aware of code structures.
In a PHP file I have a form with the options in a drop-down menu being populated from a database query (how many rounds for a tournament based on the number of entrants). Once a user has selected an option for the round of fixtures they want to view that option gets passed as a variable to determine what to display on form submit. On form submit the rest of the page changes to display the fixtures from the database that relate to the Round that the user selected from the drop-down.
My challenge is that after selecting the Round number from the drop-down menu I have to click the submit button twice - once to assign the variable and then the second press of submit to be able to use the variable as part of the process to display the fixture information from the database.
I'm aware that it is possible to use JS to store a variable that can then be used on form submit but I'm not sure how to integrate it with the way the form / has been written.
After looking at a few places on the web (like W3Schools) I've got some basic JS and have tried that but I think there's still a disconnect between the user selecting and storing the variable ready to be used when the submit is clicked.
//Basic JS
<script>
function getFormIndex() {
document.getElementById($_POST['roundselect']).innerHTML =
document.getElementById("roundselect").selectedIndex;
}
</script>
//PHP Elements
if(isset($_POST['submit'])){
$roundnum = $_POST['roundselect']; }
<?php
function setround(){
$roundnum = $_POST['roundselect'];
echo $roundnum;
}
?>
//Form
<div class="h2_select">
<? if($fnum) {
$select_opt = (isset($_GET['round'])) ? $_GET['round'] : 1;
?>
<form method="post" action="/tournaments/<?=$lid; ?>/fixtures/<?= $roundnum; ?>" name="rf">
<!--<input type="hidden" name="id" value="/<?=$lid; ?>" />
<input type="hidden" name="page" value="/fixtures" /> -->
<span class="minput">Select Round
<select size=1 class="mselect" name="roundselect" onChange=getFormIndex();>
<? for($i=1; $i <= $total_rounds; $i++) { ?>
<option value="<?= $i ?>" <?php if($i == $select_opt){ echo 'selected'; } ?> > <?= $i?> </option>
<? }
?>
</select>
<input type="submit" name="submit" value="<?= $lang[185] ?>" class="minput"/>
</form>
<? } ?>
</div>
To confirm, the form works and displays the correct information. The problem is that I currently need to click "submit" twice.
Thanks
Good start, I would do it with a bit of AJAX that allows us to send a request and receive an answer "in the background" - so that first time user changes the select I would fetch data from backend in the background and display it without double-submitting needed.
Please check this thread - I think it is illustrating the same thing;
How to Submit Form on Select Change
It is based on JQuery and I think it is a good start for new developers.
But - if you do not want to use a framework and does not care for older browsers you can just use "vanilla" Javascript with Fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and onchange https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Fetch returns the result so then you have to pass it back to the website.
It is very easy to do so with :
1. set a div on your page and add a unique ID to it (like )
2. use document.getElementById("result").innerHTML = resultFromFetch;
So:
listen to onchange on select
fetch from backend when select changes
display fetch result
AJAX is really neat and very good for the user experience as it allows us to get the data asynchronously and in the "back stage" of our application. But then it is a good user experience measure to show also some "please wait" indications and also make sure to show some potential errors (the connection can go "down" when waiting for results and then it is wise to show errors to users instead of them waiting forever).
Hope this helps to point you in a new and exiting direction.
first post so be gentle :)... OK, I'm trying to create a very simple inventory ordering site, but i'm having issues with the following:
Let's say you have (n) items in your inventory, so based on that number i run a 'for' loop and list a hidden input field with an ID of that inventory item and display a button to order. For example:
<form>
for ($i=0; $i<$num_items;$i++) {
<input type="hidden" name="item" value="<?=$ID[$i]?>">
<input type="submit" value="Order" onclick="InsertIntoDB()">
}
</form>
Now, lets say a user want to order only 2 item out of 5 in inventory. They would click on corresponding "Order" buttons and the appropriate hidden input values would be send to DB without redirecting (it would be a seamless experience for a user where once the user clicks on buttons they want the page will not reload or redirect). Here's the script that i have for the button click:
<script type="text/javascript">
function InsertIntoDB (){
var order = $('form input[name="item"]').val();
$.post('send_to_DB.php', {updateDB:order} ); }
</script>
This is what i have for send_to_DB.php file:
|code for connecting to DB|
$writetoDB=$_POST['uptadeDB'];
foreach ($writetoDB as $n) {
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$n'";
mysql_query(insert);
}
I am struggling to get those 2 values that user clicked into the DB. Any help would be much appreciated, lost many hours of sleep due to this one :). Thanks!!!
The form will send values for all the inputs in it. One way of overcoming this could be trying to enclose each set of inputs in its own uniquely identified form inside the iteration loop. But consider the following solution which will achieve the required purpose without using a form, and with a single button instead of two inputs for each item:
For the the inputs in the test.php file, assuming that array $ID is already defined:
<?php
$num_items = count($ID);
for ($i=0; $i<$num_items;$i++) {
?>
<button type="button" value="<?=$ID[$i]?>" onclick="InsertIntoDB(this.value)">Order<?= $i + 1 ?></button>
<?php } ?>
For the posting script in the test.php file:
<script type="text/javascript">
function InsertIntoDB (order){
$.post('send_to_DB.php', {updateDB:order} );
}
</script>
For the handler send_to_DB.php file:
$writetoDB=$_POST['updateDB'];
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$writetoDB'";
mysql_query($insert);
In the above $insert query, you might want to use SET onorder = 1 + onorder in order to keep track of the number of orders for each item.
However.......: I hope you are aware that we should stop using mysql_query: http://php.net/manual/en/function.mysql-query.php
Try this out
<form>
for ($i=0; $i<$num_items;$i++) {
//<input type="hidden" name="item" value="<?=$ID[$i]?>">
<input type="submit" value="Order" onclick="InsertIntoDB(<?=$ID[$i]?>)">
}
</form>
So that in your script you can try this
<script type="text/javascript">
function InsertIntoDB (order){
$.post('send_to_DB.php', {updateDB:order} );
}
Where order will now have the value id of the selected order
Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot
UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.
I'm trying to GET information about rooms and towers in an orientation system. It is a search device throw checkboxes. The point is to select each option to filter the information retrived from the database.
The problem is that the values i'm trying to GET are not even echoing, so I can't use them in the query. On the other hand they are showing in the URL and if I add a submit button I can GET the information I want, but the idea here is to get the information instantly without the button.
This is the refresh code i'm using
var auto_refresh = setInterval(
function()
{
$("#results").load("searchroom.php").fadeIn("slow");
}, 1000);
$.ajaxSetup({ cache: false });
This is how i'm saving the values that are selected in the URL
$('input[type="checkbox"]').on('change', function(e){
var data = $('input[type="checkbox"]').serialize(),
loc = $('<a>', {href:window.location})[0];
$.post('/showbytipo.php?'+data);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?'+data);
}
});
This are the HTML inputs
<form method="GET" action="searchroom.php" id="myform" name="myform">
<p>TIPOLOGIA</p>
<ul>
<li><input class="tipologia" id="tipologia"name="tipologia" type="checkbox" value="services" ><label>Serviços</label></li>
<li><input class="tipologia" name="tipologia" type="checkbox" value="class"><label>class</label></li>
</ul>
<p>TORRE</p>
<ul>
<li><input class="torre" name="torre" value="a" type="checkbox" value="a" ><label>A</label></li>
<li><input class="torre" name="torre" value="b" type="checkbox" value="b"><label>b</label></li>
</ul>
</form>
<div id="results" >
</div>
This is the PHP code to GET the values from the url
<?php
include("connect.php");
$tipo=$_GET['tipologia'];
echo $tipo;
$torre=$_GET['torre'];
echo $torre;
//$tipo='services';
$sql = "select * from rooms where tower='$torre' AND floor='$piso' AND typology='$tipo'";
//$sql = "select * from rooms where typology='$tipo'";
$query = mysql_query($sql) or die ("erro na query");
while($row = mysql_fetch_array($query)) {
echo $row["name"];
echo $row["tower"];
echo $row["typology"];
}
echo 'ola';
?>
Apart from that you have serious security issues by having get variables straight to your query, your input fields are named the same. e.g.: name="tipologia" and name="torre" has 2 instances and in the url only the second one will take effect (if it's selected).
If you want to pass multiple values your names should be like: name="tipologia[]" and this way you will see them in php as an array.
Also I know it's irrelevant, but why you are using $.post since you want to pass the values as get? Why don't you use $.get instead?
Edit:
I didn't saw that refresh part of the question.
You don't pass any variables in the refresh call if you want to pass variables the code should be like:
var auto_refresh = setInterval(
function()
{
$("#results").load("searchroom.php", $('#myform').serialize()).fadeIn("slow");}, 1000);
$.ajaxSetup({ cache: false });
I hope you know what are you doing, because the whole concept with refresh is quite messy to me, but still you have problem with the empty values from checkboxes:
You should have a javascript code which update a separate hidden field, which hold the state of the tipologia or torre fields. otherwise you can't rely on the checkboxes, their value will be always the last one checkbox.
Of course the easiest way is to use radio buttons and then you won't have this problem with the hidden field.
For debugging the variables you should use var_dump($_GET['torre']) and it will give you exactly what is in it. So, if it's empty you should see it or if it's undefined you will see null.
hope that helps.