cakephp javascript dynamic update - javascript

all creating a cakephp(using 2.1.2) page. we prompt the user to enter how many fields they are after(an int) and then we want the page to use a for-loop for the number entered.
here is the code for the add page
<h2>Please select how many fields you wish to add</h2></br>
<?php
print $this->Session->flash('flash', array('element' => 'alert'));
echo $this->Form->create('Field', array('action'=>'add'));
For(int i=0; i<'flash'; i++)
{
echo $this->Form->input('name',array('label'=>'Please Enter Field Name: ', 'type'=>'text'));
echo $this->Form->input('description',array('label'=>'Please Enter Field Description: ', 'type'=>'text'));
}
echo $this->Form->end('Click Here To Submit Template');
?>
here is the code for the alert
<script type="text/javascript">
prompt('How many fields?','<?php print $message; ?>');
</script>
the question is how do we create a variable with the alert.ctp then be able to use that variable for a for loop to print out a form that takes user input.
EDIT:
Javascript function:
<script type="text/javascript">
var number_of_fields=prompt("How many fields?",'<?php print $message; ?>');
var field_html="";
for (i=0; i<number_of_fields; i++)
{
field_html +='<input type="text" name="data[FIELD]['+i+'][name]">';
}
$("#FORMID").append(field_html);
</script>
View:
<?php
print $this->Session->flash('flash', array('element' => 'alert'));
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->end('Click Here To Submit Template');
?>
Get no errors now, but cant display any fields. What do we put in the view to print the fields (which will be more input- so user can create a field)?

Since we are getting the value of no: of required in javascript , i recommend to create fields also in javascript by following conventions used by cakephp to create input fields. So you can use javascript for loop and concat the fields in to a js variable and insert this html inputs to the form using javascript.
eg:
var number_of_fields=prompt("How many fields?",'<?php print $message; ?>');
var field_html="";
for (i=0; i<number_of_fields; i++)
{
field_html +='<input type="text" name="data[MODELNAME]['+i+'][name]">';
}
$("#FORMID").append(field_html);
i hope this would make sense

Related

How do I out put a PHP var containing JS into a form value?

I have a javascript to generate ETH address and private keys. I want to output the value of the private key and the address to a hidden field in a registration form.
However..
As plain PHP, this outputs the desired results:
$wallet_address = "<script type='text/javascript'>document.writeln(wallet.address);</script>";
echo $wallet_address;
But, when I try and put the $wallet_address into a form field:
<input type="hidden" name="user_wallet" id="user_wallet" class="input" value="<?php echo $wallet_address; ?>" />
I dont get the address, I get the javascript source line: <script type='text/javascript'>document.writeln(wallet.address);</script>
How do I get the value of $wallet_address to be the actual address in the form field?
You echo the script, not the render of the script;
Do sth like :
$wallet_address = '<script type="text/javascript">function writeWallet(){ document.getElementById(user_wallet).value = "yourAdress";} window.onLoad(writeWallet);</script>';

changing data output with onchange event

I have an option box which lists the users of something in my site. I then have two input boxes. One for wins and another for losses. I am trying to create an onchange event, so that whenever a certain user is selected from the option box, the php will output that users info. As of now the output is not changing. What am I doing wrong with my onchange event?
function myFunction() {
var wins_var = document.getElementById('wins');
var losses_var = document.getElementById('losses');
}
PHP that outputs the data and html with inputs
if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE user_id=user_id")) {
$stmt->execute();
$stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses);
//var_dump($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
$stmt->store_result();
echo "<select name = 'member' onchange='myFunction()'>";
while ($row = $stmt->fetch()) {
echo "<option value = '{$ranking_user_id}' data-wins = '{$ranking_wins}' data-losses = '{$ranking_losses}'";
echo ">{$ranking_firstname}</option>";
}
echo "</select>";
} else {
echo "<p>There are not any team players yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}?><br><br>
<label>Wins
<input type="text" value="<?php echo $ranking_wins; ?>" id="win">
</label>
<label>Loss
<input type="text" value="<?php echo $ranking_losses; ?>" id="losse">
</label>
You're on the right lines, and you don't need to do any Ajax just to achieve what you asked in your question.
The main problem is that in your Javascript, you get a reference to the two inputs for wins and losses, but you don't actually assign any value to them.
Assuming you're using jQuery (as you tagged it), then it's much easier to use this for the onchange binding and value assignments.
Firstly, you just need to make sure your "member" select has an ID instead (or as well) as a name, and you don't need the "onchange" as we'll bind that with jQuery:
echo "<select id = 'member'>";
Then, your Javascript just needs to look like this:
$(document).ready(function() {
$("#member").change(function() {
myFunction();
});
myFunction();
});
function myFunction() {
$selectedOption = $("#member option:selected");
$("#wins").val($selectedOption.data("wins"));
$("#losses").val($selectedOption.data("losses"));
}
The initial $(document).ready() function sets up the onchange binding to call myFunction(), and the second myFunction() call just ensures the wins and losses inputs are populated for the default selected option on the initial page load.
JS Fiddle here: http://jsfiddle.net/fa0kdox7/
Oh yes, and finally, your wins and losses inputs just need to look like this:
<label>Wins
<input type="text" value="" id="wins">
</label>
<label>Loss
<input type="text" value="" id="losses">
</label>
Note that I corrected a couple of typos in their IDs.

Using auto complete textbox get table record from mysql database and shows in text fields

I need to access the table record from the database when they press enter in the autocomplete textbox (at the time of select value), and it shows data in text element.
I have tried this code but cannot get the whole record:
html code:
<input class="form-control" name="sel_product_name" id="sel_product_name" >
<input class="form-control" name="sel_product_id" id="sel_product_id">
javascript code:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_product_name").autocomplete({
source:'autocomplete.php',
minLength:1
});
});
</script>
autocomplete.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("es_restaurant");
$term=$_GET["term"];
$query=mysql_query("SELECT fld_product_id,fld_product_name
FROM tbl_product_master_header
where fld_product_name like '%".$term."%' ");
$json=array();
while($product_name=mysql_fetch_array($query))
{
$json[]=array(
'value'=> $product_name["fld_product_name"]
//I want to add one more column value to display fld_product_id in
//another text box
);
}
echo json_encode($json);
?>
Try hanging the code to this:
$json = array();
while($product_name=mysql_fetch_array($query)) {
$json[]= $product_name["fld_product_name"];
}
echo json_encode($json);
I think because you are adding another layer to the array it is not working.
http://jqueryui.com/autocomplete/ shows using an array without keys.
http://www.smarttutorials.net/jquery-autocomplete-search-using-php-mysql-and-ajax/ also confirms this.
As to your comment try this:
while($product_name=mysql_fetch_array($query)) {
$json[]= array('id' => $product_name["fld_product_id"],
'value' => $product_name["fld_product_name"]);
}
http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/

PHP: print from a list of data (loop difficult)

Hi i have a little problem,my code create a list of buttons and each button have a name(value) from my list (table 'usernames')
....for exemple (table 'usernames' have 3 lines aa-bb-cc my code make 3 button with values aa & bb & cc..............
so what i want to do, is when i click on a button i want to print the value of this button in a div, for exemple if i click on the button who have the value 2 i want to print 2 in the div(i have a problem whit my loop, and i need help please)
this is my code:
$conn=mysqli_connect("localhost", "root", "pwd","sn") or die(mysqli_error());
$que2=mysqli_query($conn,"select usernames from posts", MYSQLI_USE_RESULT); // return a lot of lines on 'usernames'
$re=0;
$datax=array();
$i=0;
while ($r = mysqli_fetch_array($que2))
{
$re = $r["cnt"];
$datax[$i]=$re;
?>
<input id="ppost" name="ppost" value="<?php echo $datax[$i]; ?>" type="submit">
<br>
<script type="text/javascript">
$(function(){
$('#ppost').click(function(){
alert("<?php echo $datax[$i]; ?>");
});
});
</script>
<?php
$i++;
}
Ok, so there're few things to have a look at:
take the <script> out of the loop - one script can take care of all the buttons
you can't give same ID to all your inputs - id="..." has to be unique throughout your script
the JS script (assuming you have jQuery included prior to your ) should be:
<script type="text/javascript">
$(function(){
$('input[type="submit"]').click(function(){
alert($(this).attr('value'));
});
});
</script>
this should do the trick, let me know if this is what you wanted.

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Categories

Resources