Select form with javascript - php

I would like to get select form with variable amount of fields. To achive this first I connect to db and converting data from php to javascript. Then i got array (wynik) with values, but when i try to print it i get empty select form and all values shown next to it. There is my javascript function:
<script language="javascript">
function addInput() {
document.getElementById('text').innerHTML += "<select name='add' /><br />";
for (i=0;i<wynik.length;i++)
{
document.getElementById('text').innerHTML += "<option value=" + "wynik[i]" + " />" + wynik[i] + "</option />";
}
document.getElementById('text').innerHTML += "</select />";
}
</script>
And HTML code:
<form name="add" action="add_form.php" method="post">
<div id="text">
</div>
<br>
<input type="submit" value="Submit" />
</form>
<input type="button" onclick="addInput()" name="add" value="Add value" />
Please help me to put that into form.

The browser will attempt to fix the DOM each time you write HTML to it, consequently you cannot write just a start tag to innerHTML.
Build all your HTML up in a string and then insert it in one go.
Better yet, use createElement, appendChild and friends instead.

Perhaps you need to remove <br /> after <select name='add' /> . Also </select /> does not need a / in the end (it has it in the begining) - </select>.

Another approach you can try with ajax:
<!-- Script -->
<script type="text/javascript">
$(function(){
$("#add").on('click', function(){
$.ajax({
url : 'ajax.php',
type : 'POST',
success : function(resp){
$("#backend").html(resp);
},
error : function(resp){
}
});
});
});
</script>
<!-- HTML -->
<div id="text"><select id="backend" name=""></select></div>
<input type="button" id="add" value="Add value" />
<!-- Backend ajax.php -->
<?php
#your query here to fetch $wynik
$str = "";
foreach($wynik as $value){
$str .= '<option value="'.$value.'">'.$value.'</option>';
}
return $str;

Related

Automatically increment input type="hidden" value

I have this line of code
<html>
<head></head>
<body>
<script>
$(document).ready(function(){
$("#update").click(function(){
$("#id2").css("display","hidden");
var r = $("#id2").val()+1;
$("#id2").val(r);
});
});
</script>
<title>CV Education Form</title>
.
.
.
.
</fieldset>
<input type="text" name="id" id="id2" value="<?php echo ($id == 0 ? 1 : $id );?>"/>
<input type="submit" value="Update" name="submit"/>
</form>
</body>
</html>
and I want to change it to hidden so it is invisble but also when i click on a button update (which I have it) then it increments the value ($id) ... More simple i want something like that id+1.
Do you know how can I do that?
When I click on update button i want the 1 which is the $id to become $id+1 but I dont want to add myself I want to do it automatically when i click the update button and also hide the textfield
Just specify the update button id and id of the inputs. Use the code below
<html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$("#update").click(function(){
$("#id2").css("display","none");
var r = parseInt($("#id2").val(),10)+1;
$("#id2").val(r);
});
});
</script>
<title>CV Education Form</title>
.
.
.
.
</fieldset>
<input type="text" name="id" id="id2" value="<?php echo ($id == 0 ? 1 : $id );?>"/>
<input type="submit" value="Update" id="update" name="submit"/>
</form>
</body>
</html>
Check it here
http://jsfiddle.net/53cov3uq/3/
Hope this helps you
you can do it very simply using either Jquery or JavaScript .find the code below
function update()
{
var count=parseInt($('#counter').val());
$('#counter').val(count+1);
alert($('#counter').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" id="counter" name="id" value="0"/>
<button onclick="update()">update</button>
i just kept alert at the end that will popup the current value of the id.
try this,
<script type="text/javascript">
function increment_val(){
var id_val = parseInt(document.getElementById('id').value);
id_val++;
document.getElementById('id').value=id_val;
}
</script>
and in button html call js function,
<input type="button" value="update" id="btn_id" onclick="increment_val();"/>
For that use javascript. Php is server-side script.
<script type="text/javascript">
function increment()
{
var elem = document.getElementById("hiddenElement");
elem.value = 1 + parseInt(elem.value);
}
</script>
<input type="hidden" id="hiddenElement" name="id" value="0" />
<button onclick="increment()">Click me</button>
You can use below code which increments the value on click of a button.
<button onclick="document.getElementById('id').value = document.getElementById('id').value + 1;">Update</button>
HTML
<input type="text" name="id" value="<?php echo ($id == 0 ? 1 : $id );?>" />
To change input type you can use the syntax like:
$("#id").attr('type','hidden');
To increment the value use
document.getElementById('id').value=parseInt(document.getElementById('id').value)+1;
or using jquery
$("#id").val($("#id").val()+1);
Hope it helps.
try this if you want to change text to hidden element and increment value
HTML Code:
<input type="text" name="id" value="<?php echo ($id == 0 ? 1 : $id );?>" />
<button onclick="increment_value()">Update</button>
JS:
function increment_value()
{
var txt_field = document.getElementsByName("id")[0];
txt_field.value = parseInt(txt_field.value) + 1;
txt_field.setAttribute("type", "hidden");
}
OR
If you want to simply hide the text field just use this version of the above function
function increment_value()
{
var txt_field = document.getElementsByName("id")[0];
txt_field.value = parseInt(txt_field.value) + 1;
txt_field.style.display = "none";
}
<input type="hidden" name="id" id="id" value="<?php echo ($id == 0 ? 1 : $id );?>" />
Jquery
$(function(){
$("button").click(function(){
$("#id").val($("#id").val()+1);
})
})

alert not working not showing up

I've input some code so that I can measure the current temperature of a location. I have the script which allows my user to check the location but the alert is not working.
<h3> Weather Data </h3>
<form method="POST" action="about.php">
<input type="text" name="city" value= 'city'/>
<input type="submit" name="submit" value="submit" />
</form>
<?php
$city=$_POST['city'];
var_dump($city);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/5e8af95dbdebbd73/geolookup/conditions/forecast/q/UK/<?php echo $city; ?>.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
?>
</script>
The alert should be appearing but nothing is am I doing something wrong.
You have an unnecessary closing php tag before your closing script tag:
}
});
});
?> // this is a problem!
</script>

Why isn't the .post jquery function working in my code?

I tried a jquery function using jQuery and it's not working
It's pretty weird. I put some alerts in the js file, but when I click on the button (with id="gettotalnutrients"), none of the alerts from the js file happen.
this is where I grab the data for the js file (and display the data):
<div id="feedback"></div>
<br />
<form id="form_date_nutrient_getter" action="account-overview.php" method="POST">
Select a start date: <input id="datestart" type="text" name="beginday_calendar"><br />
Select a end date: <input id="dateend" type="text" name="endday_calendar"><br />
<input type="button" id="gettotalnutrients" value="Get the total nutrients" ><br /><br /><br /><br /><br /><br /><br />
</form>
</div>
js file:
$('#gettotalnutrients').click(function(){
alert('test');
var datestart = $('#datestart').val();
alert(datestart);
var dateend = $('#dateend').val();
alert(dateend);
$.post('getTotalNutrients.php',(beginday_calendar: datestart, endday_calendar: dateend), function(data){
$('#feedback').text(data);
});
});
wrap your click() function in $(document).ready() or something like that:
$(document).ready(function() {
$('#gettotalnutrients').click(function(){
// the rest of your code goes here
});
});
Also, are you seeing any errors in the js console?
Did you try chnaging the brackets to {
$(function(){
$('#gettotalnutrients').click(function(){
//remaining code
$.post('getTotalNutrients.php',{ beginday_calendar: datestart, endday_calendar: dateend}, function(data){
$('#feedback').text(data);
});
});
});

How to POST to 2 pages by help of button or link in HTML?

Hey Friends
i am having one forms and two button, and some text fields,what i need it if i click button 1 then the details in the text box should be POST to Page1.php if i click Button2 the details in the text box should be POST to Page2.php, i am having 8 text boxes to do the in form, how can i do that?
Let's suppose your button one id is btn1 and second has btn2 and form name is frm, you can do something like this:
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
btn1.onclick = function(){
document.forms['frm'].action = 'page1.php'
document.forms['frm'].submit(); // submit the form
};
btn2.onclick = function(){
document.forms['frm'].action = 'page2.php'
document.forms['frm'].submit(); // submit the form
};
A PHP solution would be:
<form action='' method='post'>
<input name='inputText' /><br />
<button value='1' name='whichOption'></button><br />
<button value='2' name='whichOption'></button><br />
</form>
At the top of the page this form is in, put this:
<?php
if(isset($_POST['whichOption']) {
switch($_POST['whichOption']) {
case 1: /* do something */ break;
case 2: /* do something else */ break;
}
}
?>
"something" is an include, a session variable set, or whatever you like.
Try this:
<input type="button" value="page1" onclick="this.form.action='Page1.php'; this.form.submit();" />
<input type="button" value="page2" onclick="this.form.action='Page2.php'; this.form.submit();" />
Why not just use the same page? When I need multiple submit alternatives I simply use submit buttons with different names:
<input type="submit" name="submit-save" value="Save" />
<input type="submit" name="submit-delete" value="Delete" />
When I need to know what action it is, I just check which data is sent:
if(isset($_POST['submit-save']))
{
//Do something
}
elseif(isset($_POST['submit-delete']))
{
//Do something else
}
Html:
<input id="Button1" value="Button1" type="button" /><br />
<input id="Button2" value="Button2" type="button" /><br />
<textarea id="TextBox1" cols="40" rows="5"><br />
<textarea id="TextBox2" cols="40" rows="5">
jQuery:
function PostToPage(DOOMid,uri) {
var vDOOMEl = $("#" + DOOMid);
$.ajax({
type: 'POST',
url: uri,
data: ({text : vDOOMEl.innerHTML}),
success: function() {},
dataType: "html"
});
}
function init() {
$('#Button1').click(function(e){
PostToPage('TextBox1','Page1.php');
});
$('#Button2').click(function(e){
PostToPage('TextBox2','Page2.php');
});
}
window.onload=init;
PHP:
<?php
//do something with $_POST['text'];
?>
You must download jQuery, and use it for this solution

Beginning jQuery help

I'm trying to make a simple MySQL Admin thing with php and jQuery. I've never used jQuery so my code is probably quite lol-worthy. The problem I'm having with the code is that when I click the button, nothing happens. I know the even fires because if I open the html file in firefox (not going to the url, using the file:/// thing) and click it, it shows my php code in the box I want the returned content to go into. The first thing i'm trying to do is connect to the database specified and return a list of the tables. Heres my code
index.html
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
var Server = 'None';
var Username = 'None';
var Password = 'None';
var Database = 'None';
$("#connect").click(function() {
Server = $('#server').val();
Username = $('#username').val();
Password = $('#password').val();
Database = $('#database').val();
loadTables();
});
function loadTables() {
$.get("display.php", { server: Server, username: Username, password: Password, database: Database, content: "tables" },
function(data){
html = "<ul>";
$(data).find("table").each(function() {
html = html + "<li>" + $(this).text() + "</li>";
});
html = html + "</ul>";
$('#content').html(html);
}
);
}
</script>
</head>
<body>
<center>
<div class='connection'>
<form name='connectForm'>
Server: <input type='text' size='30' id='server' />
Username: <input type='text' id='username' />
Password: <input type='password' id='password' />
Database: <input type='text' id='database' />
<input type='button' id='connect' value='Connect' />
</form>
</div>
<div id='content'>
</div>
</center>
</body>
</html>
display.php
<?
mysql_connect($_GET['server'], $_GET['username'], $_GET['password'])
or die("Error: Could not connect to database!<br />" . mysql_error());
mysql_select_db($_GET['database']);
$content = $_GET['content'];
if ($content == "tables") {
$result = mysql_query("show tables");
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xml .= "<tables>";
while ($row = mysql_fetch_assoc($result)) {
$xml .= "<table>" . $row['Tables_in_blog'] . "</table>";
}
$xml .= "</tables>";
header('Content-type: text/xml');
echo $xml;
}
?>
EDIT:
I have updated the code according to a mix of a few answers, but I'm still having the same problem.
Ok, firstly don't do that and by "that" I mean:
Don't put DB connection details in Javascript; and
Don't use input from the user without sanitizing it. You're just asking to be hacked.
That being said, your main problem seems to be that $(#content) should be $("#content"). Also putting an onclick on the button isn't really the jQuery way. Try:
<body>
<div class='connection'>
<form name='connectForm'>
Server: <input type='text' id="server" size='30' name='server' />
Username: <input type='text' id="username" name='username' />
Password: <input type='password' id="password" name='password' />
Database: <input type='text' id="database" name='database' />
<input type='button' id="connect" value='Connect' />
</form>
</div>
<div id='content'></div>
<script type="text/javascript" src="/jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function() {
$("#connect").click(function() {
$.get(
"display.php",
{
server: $("#server").val(),
username: $("#username").val(),
password: $("#password").val(),
database: $("#database").val(),
content: "tables"
},
function(data) {
$("#content").html("<ul></ul>");
$(data).find("table").each(function() {
$("#content ul").append("<li>" + $(this).text() + "</li>");
});
}
);
});
});
</script>
</body>
Edit: minor corrections to the above and tested with this script:
<?
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<root>
<?
$tables = array('one', 'two', 'three', 'four');
foreach ($tables as $table) {
echo " <table>$table</table>\n";
}
?>
</root>
I hope this helps. I noticed three things about your code:
1) display.php doesn't close the tag.
2) You refer to the 'content' div using $(#content), which throws a Javascript error. Make sure to encapsulate this selector in quotes, like $('#content').
3) I'm not sure about "$("table", xml).text()". Instead, used the very cool find('tag').each() syntax to walk through the XML response. This worked for me as a replacement for your function(data) statement:
function(data) {
htmlTable = '<ul>';
$(data).find('table').each(function(){
htmlTable = htmlTable + '<li>' + $(this).text() + '</li>'; });
htmlTable = htmlTable + '</ul>'
$('#content').html(htmlTable);
});
Here is a working piece of code:
<script type='text/javascript'>
function connect() {
$.ajax({
url:'display.php',
type: 'POST',
dataType:'xml',
success: {
server: $('#server').val()||'None',
username: $('#username').val()||'None',
password: $('#password').val()||'None',
database: $('#database').val()||'None',
content: "tables"
},
function(data){
$('#content').html('<ul></ul>');
var contentUL = $('#content>ul');
$(data).find('table').each(function(){
$('<li></li>').html($(this).html()).appendTo(contentUL);
});
},
'xml'
});
}
</script>
</head>
<body>
<center>
<div class='connection'>
<form id="connectForm" name='connectForm'>
Server: <input id="server" type='text' size='30' name='server' />
Username: <input id="username" type='text' name='username' />
Password: <input id="password" type='password' name='password' />
Database: <input id="database" type='text' name='database' />
<input type='button' onclick='connect();' value='Connect' />
</form>
</div>
<div id='content'>
</div>
</center>
</body>
But in my opinion it's better and easier to use JSON instead of xml, it's more easier to work with it (last lines of get function):
function(data){
$('#content').html('<ul></ul>');
var contentUL = $('#content>ul');
$.each(data.tables, function(){
$('<li></li>').html(this).appendTo(contentUL);
});
},
'json');
Also you can use jquery.form plugin to submit a form. It also can update specified elements using response, example:
$(document).ready(function() {
$('#connectForm').ajaxForm({
target: '#content'
});
});
I'm not sure exactly what the question is. But you don't need the $(function() {}) inside your $.get callback - passing a function to $() actually binds an event handler to the "ready" event which only gets called when your page is first loading. You just provide a function that takes your XML as a parameter (here you have it as "data" but reference it as "xml"?) and use it. I'd start by reading http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype, and http://docs.jquery.com/Events/ready#fn. Also, install Firebug and check out the error console to see where your JavaScript is having problems - you can go to the "Script" tab and set breakpoints to see how your code is executing to get a feeling for where things are going wrong.
You should use the jQuery.forms.js plugin.
http://malsup.com/jquery/form/
$(#content) // This is definitely a problem.
Selectors must be strings, so $("#content") would be correct.

Categories