Say I have 3 variables, id, name, number, on a php script, $name, $number, $id
On the PHP, I create a button
print "<td><form><input type='button' name='edit' id='edit' onclick=ed($name, $number, $id) value='Edit' /></td>";
I want those 3 variables sent to my javascript.
The function call seems to work just fine if I use
onclick=ed(this.id)
and modify the function header, and this passes the string "edit" but that's not quite useful.
function header in javascript is
function ed(name, number, id) {
//stuff here
}
For whatever it's worth using this code gets me an error on the html, something about an unexpected } on line2 of the html document.
Edit:I should clarify I said that code gives me errors so someone didn't just say "Well use this!" when I already expected it not to work.
Using this:
<input type='button' id='$id' onclick=ed(this.id) value='Edit' />
Allows me to send the value in $id to the javascript function because it was saved in the id field. Something along those lines is what I'm hoping for, but I'm unable to find if there's any way to do that. edit: for 3 variables.
Edit again:
Using:
<form><input type='button' name='$name' id='$id' title='$number' onclick='ed(this.name,this.title,this.id)' value='Edit' /></form>
sent the values of all 3 php variables to the javascript function.
It's not pretty, but it works.
For custom attributes define data-attributes, e.g. as shown on Mozilla Dev:
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe
</div>
var el = document.querySelector('#user');
// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''
el.dataset.dateOfBirth = '1960-10-03'; // set the DOB.
// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// 'someDataAttr' in el.dataset === true
In your case, it seems you only need data-number as the other two are standard properties of the DOM-element.
I think the problem is with your quotes so try this
print '<td><form><input type="button" name="edit" id="edit" onclick=ed('.$name.','.$number.','.$id.') value="Edit" /></td>'
You can only send 3 value like this:-
onclick="javascript:func_name('<?php echo $var1 . "," . $var2 . "," . $var3;?>');
In the js function take only one argument and then split 3 values using "," as a delimiter.
Related
I've got a set of checkboxes but one shuld be always checked, I want that this checkbox is also hidden from my page, I need this beacause I have the DB that can be read only if this attribute is checked..
Please I need answers where you teach me how to hide the checkbox and NOT where you say that I can change the comand on SQL
$sqlPers= "SELECT * FROM personalizzazione";
$countPers = 0;
foreach ($dbh->query($sqlPers) as $rowPers){
$selez = '';
if($rowPers['Condimento'] == 'Base')
$selez = " checked = 'checked' ";
echo "<div class='checkbox'><label class='bianco'><input type='checkbox'" .
$selez . "name='".$rowPizza["idPizze"]."_".$rowPers["idPersonalizzazione"].
"' id='".$rowPizza["idPizze"]."_".$rowPers["idPersonalizzazione"]."'>".
$rowPers['Condimento']." (€ ".$rowPers['Prezzo'].")</label></div>";
$countPers++;
}
I tried to add type = 'hidden' in the variable $selez but nothing
Otherwise can someone say me how to disable it or hide it throught ccs?
I've tried searching on internet and there weren't full solutions for my question
There are two things you can do:
Method 1 - Hide it using CSS:
<input type='checkbox' style='display:none;'>
Method 2 - Use a hidden type instead of checkbox:
Another option would not have a checkbox, but rather have a separate hidden input tag.
<input type='hidden' name='pizza' value='value'>
You can hide it with style="display:none;"
But since it is hidden, does it have to be a checkbox?
A regular hidden input would do the job, too.
Look at the HTML that gets sent to the browser: You have already set type='checkbox' in your string, so having an additional type='hidden' may not give you what you want. You end up with <input type='checkbox' type='hidden'...
Your error was tough to see because you're writing your code in a way that is really difficult to debug. It's better practice to do all the logic up front. You're better off building all the attributes in code first. For example:
//run test to make $hide true for the loop where you want to hide the checkbox
$type = 'checkbox';
$style = $hide? "display:none" : "";
$name = $id = "$rowPizza[idPizze]_$rowPers[idPersonalizzazione]";
...
//then later when you can build your html
$html = "<div class='checkbox'><label class='bianco'><input type='$type' name='$name' id='$id' style='$style'>";
//Finally once you've built the whole html you can echo it
echo $html;
Note that we set display:none style when the $hide variable is true. Otherwise, the style will just be an empty string and the checkbox will be shown
I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.
I have a text area page which is launched from the previous page:
$message = $_POST['editPost'];
header("location:editPost.php?msg=$message");
The editPost.php retrieves this and fills the text area like so:
echo "<form action='index.php' method='post'>
Your Post:<br/>
<textarea name='comments' cols='100' rows='100'>".$_GET["msg"]."</textarea>
<br/>
<input type=submit value='submit'>
</FORM>";
The problem I'm getting is not all the data of 'msg' seems to get passed across, or the message gets cut of at the point where it reaches a quotation mark e.g. '
The text I want it to fill the textarea with this text:
So this is my second blog post for this assignment, I've progressed a bit since my previous post
however it only add this to the text area this:
So this is my second blog post for this assignment, I
As I say it seems to not contain any more of the string after the quotation mark is reached. Is there anyway around this so I can pass the whole message across?
EDIT
I might add, I'm aware a more simple solution would be to retrieve the message again from the MySQL database as that's what I'm using, but I'm just intrigued as to how this works.
if(isset($_POST['edit'])) {
//$_SESSION['postToEdit'] = $_POST['editPost'];
$message = htmlentities($_POST['editPost'], ENT_QUOTES);
header("location:editPost.php?msg=$message");
That is what I do with the data once it is posted from this form:
foreach($posts as $postid=>$post)
{
echo '<div class="blogPosts">'.$post;
if(isset($_SESSION['username'])) {
if($_SESSION['isAdmin'] == "true") {
echo "<br/><br/><form name='adminTools' action='index.php' method='post'>
<input type='hidden' name='editPost' value='$post'>
<input type='submit' value='Edit' name='edit'/>
<input type='hidden' name='deletePost' value='$postid'>
<input type='submit' value='Delete' name='delete' /></form>
</div>";
echo "<form action='index.php' method='post'>
Your Post:<br/>
<textarea name='comments' cols='100' rows='100'>".htmlspecialchars($_GET["msg"])."</textarea>
<br/>
<input type=submit value='submit'>
</FORM>";
textarea seems an odd container for it, but that's your call
I think I get it.
header("location:editPost.php?msg=$message"); doesn't smells good.
If you simply want to fix the problem use http://php.net/manual/en/function.urlencode.php and when getting the value http://www.php.net/manual/en/function.urldecode.php
You're getting a post request and then forwarding it using header location. That's definitely a poor way to do it. The problem probably is taking place when you pass the parameter as a query string on ?msg=$message
Since MVC and alike applications (n-layered apps) is the standard now. You should not do that spaghetti code, mixing html and php and using header as your FrontController dispatcher.
I'd suggest you to use for example, the SLIM framework. If you do not want to learn this. You should at least follow the standards described here.
E.g.:
<?php
// index.php
// load and initialize any global libraries
require_once 'model.php';
require_once 'controllers.php';
// route the request internally
$uri = $_SERVER['REQUEST_URI'];
if ($uri == '/index.php') {
list_action();
} elseif ($uri == '/index.php/show' && isset($_GET['id'])) {
show_action($_GET['id']);
} else {
header('Status: 404 Not Found');
echo '<html><body><h1>Page Not Found</h1></body></html>';
}
In short, create a FrontController file that will map to the desired actions (controllers) according to the request without using header() to execute specific actions (the exception is only if actually the headers are needed, in fact).
Use addslashes($message) before passing it in querystring and stripslashe($_GET['msg']) function before displaying it.
Click addslashes() and stripslashes() for more references.
I'm trying to pass a parameter from php into my javascript function inside html. Is this at all possible? This is what I've got so far, but it seems to crash once it hits the condition:
$str="<input type='submit' value='-' onclick='Call(".$row['field1'].");'/>";
I hope that I won't have to find a work around for this.
Thanks.
EDIT:
This is the function that I'm trying to call
function Call(stuff)
{
alert(stuff);
$.get('reports.php',
{'param':'section', 'text':stuff},
function(returned_data)
{
alert(returned_data);
});
//alert('end');
}
And this is the function that I'm populating a table with.
function PopTable()
{
alert('end');
document.getElementById('table').innerHTML = 'Loading...';
$.get('reports.php',
{'param':'getstuff'},
function(returned_data)
{
document.getElementById('table').innerHTML = returned_data; // Clear the select
});
alert('end');
}
This is the php that I'm sending back population the table:
$str.= '<tr>';
$str.='<td bgcolor="#ffffff">' . $row['stuff'] .'</td>';
$str.='<td><input type='submit' value='-' onclick="Call('$row['stuff']');"/></td>';
$str.='</tr>'; //accumulate table
I can't seem to get a return value for Call(), and the alert doesn't even pop up
Try:
$str='<input type="submit" value="-" onclick="Call(\''.$row['field1'].'\');"/>';
I would bet you need quotes around the value if it is a string value
For example if $row['field1'] = 'test'; then:
Your version: <input type='submit' value='-' onclick='Call(test);'/> which would fail because test is not a valid variable
My Version <input type="submit" value="-" onclick="Call('test');"/> which would work becase 'test' is a string
What you're trying to do is possible, whereas it is not possible to pass a parameter from JavaScript into a PHP function.
When you say it crashes once it hits the condition, do you mean when you click on the input on the page? In that case, it's an error in your JavaScript syntax. I would try using Firebug with Firefox to track down the issue.
My first guess is there are no quotation marks inside the Call() method. So you're doing this:
Call(something)
and it should be like this:
Call('something')
This is possible, but I would be very careful about mixing PHP echos and javascript inline with strings because you need to escape javascript datatypes properly
In your example, $row['field1'] is probably from a database, so it's a string, so you need to surround the value with quotes in your javascript call. But that's not all, because what if there's a quote in your string, or a special character like a newline which needs to be escaped in javascript? And then what about html escaping?
A better approach is to import your javascript values in one place using json_encode(), then use your variables from there.
E.g.:
<?php
$jsonrow = json_encode($row);
?>
<script type="text/javascript">
var jsrow = <?=htmlspecialchars($jsonrow);?>;
</script>
<?php // some time later... ?>
<input type="submit" value="-" onclick="Call(jsrow.field1);" />
The below code is in PHP
echo "<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return confirm('Please Confirm Delete');'>"
I am trying to create a delete button, when a user clicks on delete button , it should ask confirmation. but in this case, its not working.
is there any best way to delete with confirmation in php with/ or javascript
and no ajax
Your quotes are breaking themselves here;
onclick='return confirm('Please Confirm Delete');'>
Instead use;
onclick="return confirm('Please Confirm Delete');">
Well, in javascript you can do it as:
<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return askme();'>
//javascript function
function askme() {
if(confirm("Are you sure you want to delete this..?")) {
//delete someting
}
}
The quotes are going wrong, use this instead:
echo "<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return confirm(\"Please Confirm Delete\");'>"
You are going out of your attribute by opening the single quote again inside your confirm.
You cannot "call php code into jquery". The only thing you can do is to set up a request (AJAX) to a server side PHP script which will take over the respective parameters you transferred to the script and produce an output (using echo or print) which will automatically be available in the request's callback.
With jQuery it's as easy as that
$.post('url/to/script.php', {parameter1: 'whatever', param2: 'something'}, function(response) {
// the output of the PHP script is available in the variable "response"
alert(response);
});
The PHP script can take over the parameters, take any action with it and create output
$param1 = $_POST["parameter1"];
$param2 = $_POST["param2"];
// do whatever you want with $param1 and $param2
// create some output using echo/print
echo "This will be transferred back to the calling Javascript";
You can try this, quite easy and it works.
<td> <a onClick="return confirm('DELETE: Are You sure ??');" href="member_delete?id=<?php echo $row['memID'];?>" >delete <i class="fa fa-trash-o" aria-hidden="true"></i></a></td> [DEMO][1]
I assume, its in a table list of members.