I have been looking all over for a way to do this.
I use a PHP while loop to get some variables from a database:
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<script type="text/javascript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
//-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
<? } //end while
?>
Sometimes i get 10 results, and i make 10 Go! bottoms. But when i come to the delete page, the $is variable is off cause the same as the last result, no matter witch of the bottoms i press..
Any ideas on how to get around that, so i get the confirm box, and still keep the right id to be deleted?
You're creating a global function called "go_there" for each entry, so only the last one will remain. Instead of that, create just one function, and fetch the "id" value from an attribute on the button.
function go_there(button)
{
var id= button.getAttribute("data-id");
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
}
Then:
<INPUT TYPE="button" value="Go!" onClick="go_there(this)" data-id="<?php echo $id ?>">
It seems to me like you're creating your javascript function in your loop as well so it only fires one of them (you're creating multiple functions with the same name. How is it supposed to know which one to use). You should create 1 javascript function and pass the id into it as a a parameter
<script type="text/javascript">
function go_there(id)
{
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
</SCRIPT>
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
echo '<td><form><INPUT TYPE="button" value="Go!" onClick="go_there(<?php echo $id; ?>)"></form></td></tr>'
} //end while
?>
Overall this is a poor way to do this. You should avoid wrtiting handlers inline unless you have a specific case where it is the only way. Much better if you attach a handler to the elements in questions (working fiddle - for firefox anyhow...):
<!-- output our inputs with the id value in an attribute data-id-value -->
<?php while ($row = mysql_fetch_array($query)): $id = $row["ID"]; ?>
<td><form><INPUT class="go-button" TYPE="button" value="Go!" data-id-value="<?php echo $id ?>"></form></td></tr>
<?php endwhile; ?>
<script type="text/javascript">
var goButtons = document.querySelectorAll('input.go-button'), // select all out buttons
// define our handler function
goThere = function (event) {
// get the id the we encoded from php from our data attr
var id = event.target.getAttribute('data-id-value');
if(confirm('Are you sure you want to delete?')) {
// if confirm is true then redirect to the delete url
window.location = "index.php?p=delete&id=" + id;
}
};
// loop over the buttons and attach the handler
for (var i = 0; i < goButtons.length; i++) {
goButtons[i].addEventListener('click', goThere);
}
</script>
The issue here is that that isnt necessarily cross browser. Thats typically one of the reasons people use libraries like jQuery or similar so that they don't have to normalize dom querying and listener attachment.
Here is a corrected script.
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<SCRIPT language="JavaScript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to == true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
Your button will not work because you have added the comment markers <!-- and --> to the function. If you want help with that then please comment.
Also, can you clarify you're issue in the comments? We can help you better then.
Related
I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).
index2.php
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$uid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.
<!DOCTYPE html>
<html>
<head>
<title>User_Logs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$uid =$_POST["USERID"];
}
?>
<form method="POST" id="form-add" action="index2.php">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
</body>
</html>
My script:
$(document).ready(function(){
$("#mybtn").click(function(){
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
})
This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST. How can i do that? I have never done this asynchronous POST coding. Kindly help.
i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.post("index2.php", {data :'<?php echo json_encode($json_array);?>'
})
});
})
I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.POST("index2.php", {
var myVar = "<?php echo json_encode($json_array); ?>";
});
});
})
you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)
Can you try this,
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
});
Also in HTML remove action in form
<form method="POST" id="form-add">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
Edit :
Can you try this please ? Second param for post takes an object .
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
var myVar = <?php echo json_encode($json_array); ?>;
console.log(myVar);
$.post("submit.php", {
'id': myVar
},function(data){
console.log(data);
});
});
});
I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?
If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>
Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something
Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>
You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}
Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>
$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})
However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>
First of all I appreciate that all members are trying to help each other.
I want div content by id in my javascript function. I've got function and it works fine with one div and it's content. But now I've got multiple records from DB, so to make div unique I have done following. where $i=$i+1 in while loop
<div id="<?php echo 'fvd'.$i; ?>" class="fake-checkbox star-checkbox"><a id="<?php echo 'tvd'.$i; ?>" onclick="respuestas('<?php echo $user_id1;?>'); return false;" href="#">Add to favourites</a></div>
so here I generate fvd1, tvd1 for next record fvd2,tv2 and so on
Below function process user id and get response by Ajax call and change caption from Add to favourites to Added to favourites and add class name 'checked' which change text color.
function respuestas(str) {
var popID = str;
var gett = document.getElementById('tvd1').innerHTML;
if (gett == 'Add to favourites') {
$.post('personals/addfavourite.php', {
ref: popID
}, function (data) {
if (data == 'no') {
alert('Sorry! something gone wrong!')
} else if (data == 'yes') {
var d = document.getElementById("fvd1");
d.className = d.className + " checked";
document.getElementById('tvd1').innerHTML = 'Added to favourites';
}
});
}
}
Now how can I parse fvd2,tvd2 and so on in this function.
Any help will be much appreciated..Thanks
If you add your $i to the function parameters you can get each grouping dynamically
onclick="respuestas('<?php echo $user_id1;?>',<?php echo $i;?>); return false;"
and
function respuestas(str,num) {
...
var gett = document.getElementById('tvd'+num).innerHTML;
...
var d = document.getElementById("fvd"+num);
...
document.getElementById('tvd'+num).innerHTML = 'Added to favourites';
...
}
You can do
onclick="respuestas(this, '<?php echo $user_id1;?>');
and the first param would be the <a> so you can do
function respuestas(elm, str) {
elm.getAttribute("id");
}
or so. (Not sure about the DOM method name)
BTW why don't you just put the $i to the call as well? Or maybe I didn't get the question right? If not, pls explain.
If you need to access the elements, well then you already have the <a> in elm, and the <div> is in elm.parentElement.
Check HTML DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement
I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one
JavaScript Code
<script type="text/javascript">
function toggle(id){
var el = document.getElementById(id);
if(el != null && el.style["display"]== 'none'){
el.style["display"] = "block";
}
}
</script>
My divs code
<?php foreach($titles_data as $title){ ?>
<div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
<div id="left-ad"></div>
</div>
<?php } ?>
My links code
<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
<a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
</a>
</li>
<?php } ?>
How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?
Thanks
Using native JS:
function toggle(id){
var el = document.getElementById(id);
el.style.display = el.style.display == "none" ? "block" : "none";
}
toggle("myId");
Using jQuery:
function toggle(selector) {
$(selector).toggle();
}
toggle("#myId");
To toggle the display, you dont need to do that much
$("#elementid").toggle();
In reference to your question
$('a').click(function() { // however this is select all anchors, better use class
// selector like $(".mylinkclass")
var id= $(this).attr('id'); //get the id
var ids = id.splite("_"); //split the id on "_", to extract the idtitles
$("#content_"+ids[0]).toggle(); // use that to toggle
});
Assuming that there is always only one div that is displayed, you can check for it:
Alter your logic, to declare a global variable to hold the value of the currently visible div. And then update that variable whenever a link is clicked, to hold the id of the currently visible div. So, using your exisitng code, you can do this :
using core javascript:
var visibleDiv;
function toggle(id){
// hide the previous div using visibleDiv
if(document.getElementById(visibleDiv)!= null) document.getElementById(visibleDiv).style["display"] = "none";
var el = document.getElementById(id);
if ( el.style["display"] == "" || el.style["display"] == 'none' ){
el.style["display"] = 'block';
}
visibleDiv = id; // update the current visible div name
}
using jquery like this :
var visibleDiv;
$("[id^=content_]").each(function() {
if($(this).is(':visible')){
visibleDiv = $(this).attr('id');
}
});
Check my new answer. I just created the sample html page, with 3 divs. Initially all are shown. When you click on one of them, it is hidden. When you click on some other div. The old one is made visible again and the current one is hidden. Modify the logic as per your requirements.
<html>
<head>
<title>asdsa</title>
<script type="text/javascript">
var visibleDiv;
function toggled(id){
//$('#div_2').html($('#div_1').html());
if(document.getElementById(visibleDiv) != null){ document.getElementById(visibleDiv).style["display"] = "block";}
var el = document.getElementById(id);
document.getElementById(id).style["display"] = "none";
visibleDiv = id;
}
</script>
</head>
<body>
<div id="div_1" onclick="toggled('div_1')">div1</div>
<div id="div_2" onclick="toggled('div_2')">div2</div>
<div id="div_3" onclick="toggled('div_3')">div3</div>
<hr/>
</body>
</html>
Thanks.
i have tried:
<?php include("delete.php") ?>
<?php
....
....
....
if($result=mysql_query($sql))
{
echo "<table><th>Id</th><th>Name</th><th>Description</th><th>Unit Price</th>";
while($row = mysql_fetch_array($result))
{
echo "<tr><td>".$row['Id']."</td><td>".$row['Name']."</td><td>".$row['Description']."</td><td>".$row['UnitPrice']."</td>
<td><a href='delproduct($row[Id])' onclick = 'return MsgOkCancel()'>Delete</a></td></tr>";
echo "<br/>";
}
}
?>
following javascript is in the same page:
<script type="text/javascript" language="javascript">
function MsgOkCancel() {
if (confirm("Are You Sure You Want to Delete?"))
{ return true }
else
{return false}
}
</script>
where delproduct is a javascript function in delete.php
written like:
<script type="javascript">
function delproduct(Id)
{
alert('Id '+ Id);
}
<script>
** after ** clicking Delete a okcancel message-box appear asking conformation
** but ** after clicking 'ok' it should execute statements inside delproduct function but it doesn't
it gives error like:
Object Not Found :The requested URL was not found on this server.
what would be the problem?
pls help,
thanks
A URI without a scheme (such as http:) is treated as a relative URI.
You appear to be looking for javascript: (which should never be used for anything other than creating bookmarklets).
What you should be doing is something along the lines of:
onclick="if (MsgOkCancel()) { delproduct($row[Id]); return false; } else { return false; }"
However, you should have something that works in the href, but since this appears to be making a significant change on the server, you should be using POST not GET, so a link is the wrong tool.
What you probably should have is:
<form action="/delete" method="post" onsubmit="return delete(this);">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($row[Id]); ?>">
<input type="submit" value="Delete">
</form>
Combined with:
function delete(form) {
if (confirm("Are You Sure You Want to Delete?")) {
delproduct(form.elements.id.value);
}
return false;
}
Better yet, get rid of the onsubmit attribute and assign the event using JavaScript.
I think you need a different setup.
First of all, if you are going to call javascript functions in an href attribute, you need to prepend it with javascript: like so href="javascript:delproduct(...)". But calling javascript from an href attribute is not recommended. That attribute is intended for urls.
I would advice you to create a function that displays the messagebox and based on the action of the user, calls the delproduct function. Something like:
function confirmDelProduct( id )
{
if( msgOkCancel() )
{
delproduct( id );
}
// return false is meant to stop the href url from being called
return false;
}
And in your html:
<a href="#" onclick="return confirmDelProduct(' . $row[ 'id' ] . ')"> ... etc
What about this one:
PHP:
<a href="javascript:void(0);" onclick=\"delproduct({$row[Id]})\">
JS:
function delproduct(Id){
if(MsgOkCancel()) alert('Id '+ Id);
}