Change a buttons value if parameters are met, jQuery, PHP, Sessions - php

I have the following button:
<input type="button" count='<?php echo count($_SESSION['children']);?>' name="children" class="add_child" value="Add Another Child"/>
On default when the form loads (with a clean session) there is no input for children, so the button should read "Add a Child".
If there is a text field present with the name children[] then it should just display: "Add another Child".
How would this be done ?
I am using php / jquery / sessions for the fields here is the code for it:
$('.add_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children_form').append($('<li />').append(input));
$('#content li:odd').addClass('alt');
})
<?php
if(isset($_SESSION['children'])) {
foreach($_SESSION['children'] as $index=>$child){ ?>
<li>
<?php echo "<input type='text' name='children[{$index}]' value='{$child}'/>";?>
</li>
<?php } }?>

Try this out with the code you have already:
$('.add_child').click(function(){
//code...
$(this).val('Add Another Child');
})
and the php for the input:
<input type="button" count='<?php echo count($_SESSION['children']);?>'
name="children" class="add_child"
value="<?php echo (isset($_SESSION['children'])?
'Add Another Child':'Add a Child');?>"
/>

Related

PHP form button redirects (is changing the URL) even if I don't want to

So, I have a button in a form.
<form>
<button onclick="alert('<?php echo $value ?>')">Click me!</button>
</form>
$value = "1.png"
When I press it changes the url like this:
Initial:
index.php?id=82
After I click:
index.php?
As you can see, I want the button to only show an alert, not to change the URL
Full code:
<form>
<label>Title</label><br>
<input type="text" value="<?php echo $title ?>"><br><br>
<label>Description</label><br>
<textarea rows="5" maxlength="120"><?php echo $desc ?></textarea><br><br>
<div>
<?php for($k = 0; $k < count($images); $k++) { ?>
<div>
<img src="<?php echo $images[$k] ?>">
<button onclick="alert('<?php echo $images[$k] ?>')">Click me!</button>
</div>
<?php } ?>
</div>
</form>
PS: I'm not sure what's the problem but I think is the form
There are at least two ways of achieving this:
html:
<button type="button" onclick="alert('<?php echo $images[$k] ?>');">Click me</button>
<button onclick="alert('<?php echo $images[$k] ?>');return false;">Click me!</button>
The first option I think would be best if the only thing you want to achieve is to alert a text.
The second option might be better if call a function when you click on the button and want different responses:
<button onclick="return foo('<?php echo $images[$k] ?>');">Click me!</button>
in javascript:
function foo(image) {
//If image is img1 then update the page
//If any other image, don't update the page
if (image == 'img1') {
return true;
}
return false;
}
When you fail to specify the type of a <button> element, the browser will imply that it is a submit type button. Thus, when you press the button, your browser is submitting the form with it.
You should either,
a) Specify a type for the button other then submit, or
b) Return false in the javascript code to run, to prevent the click event from bubbling.

Passing value of textarea with jquery to PHP

I have a tip section that can be "custom" input from a customer. When the customer enters a value, I want to pass it to PHP for updating the order.
I'm unsuccessful and I'm thinking I'm approaching this problem the wrong way since I can't get it to work. What options are available to me without using AJAX?
The tip section:
<?= ($receipt['tip'] > 0 ?
'<tr id="tip-area"><th>Tip</th>
<td><textarea id="tip" name="update_tip" readonly>'. $receipt['tip'].'</textarea></td>
</tr>'
: '') ?>
My form which has different tip options:
<form method="post">
<tr>
<button title="20% Tip" type="submit" name="update_tip" id="update_tip" class="tip-button"
value="<?= ($_SESSION['order']['quote']['subtotal'] * 0.2); ?>">
<small>20%<br><?= number_format(($_SESSION['order']['quote']['subtotal'] * 0.2), 2) ?></small>
</button>
<button title="Edit Tip" type="button" name="update_tip" id="custom-tip" class="tip-button">
<small>Edit<br>Tip<br></small>
</button>
<button title="Save Tip" type="submit" id="save_tip" class="hidden">
<small>Save<br>Tip</small>
</button>
</tr>
</form>
My jQuery:
$('#custom-tip').click(function(){
$('#tip').removeAttr('readonly').focus();
$('.tip-button').addClass("hidden");
$('#save_tip').removeClass("hidden");
});
$('#save_tip').click(function (){
var tip = $('textarea#tip').val();
$('<input type="hidden" name="update_tip" value="' + tip + '">').submit();
});
$('#tip').focus(function(){
this.value = '';
});
When they press "Edit Tip", the readonly property is remove, the area comes into focus and value is cleared.
Then the user should enter a value and hit Save.
Then I'm trying to retrieve the value they entered.
I think this is what you want:
$("form").submit(function() {
$("<input>", {
type: "hidden",
name: "update_tip",
value: $("#tip").val()
}).appendTo($(this));
});
This will create the hidden input with the value from the textarea and append it to the current form when before the form is submitted.
You need to have PHP code on the same page (because your form does not specify an action) that handles the data. Use the 'name' attribute for your input to specify the key of the value you wish to access in the $_POST super global. For example, if I post a form with the following code:
<form method='POST'>
<input type='hidden' value='hello' name='world'>
<input type='submit' value='submit'>
</form>
Then in PHP, I can access the value of the element with the name "world" with the following code:
$_POST['world']
Use this syntax to acquire the data from the form and persist it/update it.

I want to use PHP variable in jQuery in loop

I want to use PHP variable in jQuery.
I am having a 50 students data in table which having textbox and radio button.
By default textbox is hidden but when I clicked on radio button textbox show in table.
$("input[type='radio']").on('change', function() {
if ($(this).val() == "2")
var id = '<?php echo json_encode($absent); ?>';
//$("input[type='text']").show();
else
$("input[type='text']").hide();
});
PHP code:
<input name="nxtmark<?php echo $row[0]; ?>" type="text" id="nxtmark<?php echo $row['id']; ?>" onblur="onleave(this.name);" maxlength="2" placeholder="Enter Mark" hidden="" />
<div class="noerrordiv" id="dnxtmark<?php echo $row[0]; ?>">Mark must not be blank</div>
</td>
<td>
<div align="justify">
<input type="radio" id="rdopresent" name="rdopresent<?php echo $row['id']; ?>" checked="checked" value="1" />Present
<input type="radio" id="rdoabsent" name="rdopresent<?php echo $row['id']; ?>" value="2" />Absent<br />
</div>
</td>
</tr>
You can show / hide text box without using PHP variable. See below code -
$("input[type='radio']").on('change',function() {
//find input text from the previous 'td' for which name starts with 'nxtmark'
var $textBox = $(this).closest('td').prev('td').find('input[name^=nxtmark]');
//show hide text box as per radio button value
if($(this).val() == "2")
$textBox.show();
else
$textBox.hide();
});
If your Problem is just to use PHP variable in jquery then following examples will help you.
if you have to user a php array in jquery then use json_encode in PHP not in SCRIPT.
<?php
$a = array(1,2,3,4);
$a = json_encode($a);
$b = "hello";
?>
<script>
$(document).ready(function(){
alert("<?php echo $a; ?>");
alert("<?php echo $b; ?>");
});
</script>

jquery not sending button choice to php

I have a search function that will accept a search string and send it to a php file for parsing a database column. I'd also like users to choose which aspect of the website they'd like to search (comics, artwork, or both). Comic and Artwork or stored in two separate tables.
This is a function that will accept an input search string from the html below and send it to a php file.
<script type="text/javascript">
function search(searchString) {
//var site = $("#site").val();
$.get("./scripts/search.php", {_input : searchString},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
And this is javascript to accept a choice to search "comics", "artwork" or "all".
function searchChoice(choice) {
alert("Choice: " + choice);
$.get("./scripts/search.php", {_choice : choice}
);
}
</script>
HTML:
<!--Search filtering for comics, artwork, or both-->
<span class="search"><b>Search for: </b> </span>
<div class="btn-group" data-toggle="buttons-radio">
<span class="search">
<button type="button" class="btn" id="comics" onclick="searchChoice(this.id)">Comics</button>
<button type="button" class="btn" id="artwork" onclick="searchChoice(this.id)">Artwork</button>
<button type="button" class="btn" id="all" onclick="searchChoice(this.id)">All</button>
</span>
</div>
<br/>
<br/>
<!--Search functionality-->
<span class="search">
<input type="text" onkeyup="search(this.value)" name="input" value="" />
</span>
<br />
<span id="output"><span class="sidebarimages"> </span></span>
PHP excerpt:
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : "all");
You can see the javascript correctly alerting out "Choice: comics" when comics button is selected, but the php side, echo "</br>Choice: " . $siteChoice;, is echo'ing out "all", which is incorrect.
Any ideas would be greatly appreciated!
As mentioned #E_p, that is the problem ... another option is to create a variable and store the data there ... try this: you don't need change the html
var mySearchString = 0;
var myChoice = 'all';
function search(searchString) {
mySearchString = searchString;
GetSearch();
}
function searchChoice(choice) {
myChoice = choice;
GetSearch();
}
function GetSearch(){
$.get("./scripts/search.php", {_input : mySearchString, _choice : myChoice},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
You do not keep state for _choice.
When search is called it does not pass it to a server.
You need to change buttons to option and in search function pass both. to a server at the same time
Replace the buttons with radio buttons and use form.Serialize()
<form id="searchform">
<input type="radio" name="_choice" value="comics" />Comics<br/>
<input type="radio" name="_choice" value="artwork" />Artwork<br/>
<input type="radio" name="_choice" value="all" />All<br/>
<input type="text" onkeyup="search()" name="_input" value="" />
</form>
Javascript
function search() {
//var site = $("#site").val();
$.get("./scripts/search.php", $('#searchform').serialize(),
function(returned_data) {
$("#output").html(returned_data);
}
);
}
The .serialize() function converts form input to JSON so you don't have to type manually, No more parameter, and no two functions, just one to do them all

Invalid argument supplied for foreach() loop

Hi Stackoverflow i hope you are all well today,
i seem to have run into an issue and am kindly requesting your assistance;
Basically i am using jQuery to manipulate a form, the form then stores in the session and upon returning to the page a foreach loop is used to return the values from the session into the page.
The issue is if I create more than one instance of this foreach loop it gives me an invalid argument (if i add the same code over and over again it works fine)
So firstly here is the code;
jQuery
$(function(){
$('.add_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children_form').append(input);
$('.children_form').append(lineBreak);
})
$('.add_s_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.spouce_children').append(input);
$('.spouce_children').append(lineBreak);
})
});
and the PHP / HTML CODE -> Button One (add_child)
Children, please name your natural and / or addopted children
<?php foreach($_SESSION['children'] as $index=>$child){ ?>
<?php echo "<input type='text' name='children[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['children']);?>' name="children" class="add_child" value="Add Another Child"/>
<div class="children_form">
<?php //add the inputs here?>
</div>
and the PHP / HTML CODE -> Button Two (spouce_children)
<label>Spouces Children, please name all natural and addopted children</label>
<input type="text" name="spoucechild" id="spoucechild" />
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
<?php echo "<input type='text' name='spoucechild[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['spoucechild']);?>' name="spoucechild" class="add_s_child" value="Add Another Child"/>
<div class="spouce_children">
<?php //add the inputs here?>
</div>
I would like to thank you for any help you can / will provide <3
Error Occurs here:
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
#Xavier: You could try --
<?php
if (isset($_SESSION['spoucechild'])) {
foreach($_SESSION['spoucechild'] as $index=>$child){
echo '<input type="text" name="spoucechild[' . $index . ']" value="' . $child . '" />' . "\n";
}
}
?>

Categories