$_GET not working on my php file [duplicate] - javascript

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I have a url link that has value of the id and process when clicked.
code:
<?php
<a href='settoActive.php?id=".$row['id']."&process=actives' style='font-size:15px;' name='active' value=".$row['id']." class='btn btn-info' />ACTIVE</a>
?>
<a href='settoActive.php?id=".$row['id']."&process=inactive' style='font-size:15px;' name='active' value=".$row['id']." class='btn btn-info' />inactive</a>
and this is where the page will be redirected to:
<?php
$value = $_GET['process'];
echo "<script> alert(".$value.");</script> ";
if($_GET['proc']="actives"){
$id = $_GET['id'];
$mysqli = new mysqli('10.237.2.152','root','c0k3float','monitoring');
$results = $mysqli->query("UPDATE Shipment_Target SET status='Active' where id=".$id." ") or mysqli0;
echo "<script>alert('Activessss!'); </script>";
//location.replace('addmodel.php')
}
if($_GET['process']="inactive"){
$id = $_GET['id'];
$mysqli = new mysqli('10.237.2.152','root','c0k3float','monitoring');
$results = $mysqli->query("UPDATE Shipment_Target SET status='Inactive' where id=".$id." ") or mysqli0;
echo "<script>alert('Inactive!'); </script>";
}
// location.replace('addmodel.php')
?>
The problem is the 2 if condition trigger and why it is triggering at the same time?

There are 3 mistakes noticed... 2 places '==' operator and 1 place GET variable name 'process'.
$value = $_GET['process'];
echo "<script> alert(".$value.");</script> ";
if($_GET['process']=="actives"){
$id = $_GET['id'];
$mysqli = new mysqli('10.237.2.152','root','c0k3float','monitoring');
$results = $mysqli->query("UPDATE Shipment_Target SET status='Active' where id=".$id." ") or mysqli0;
echo "<script>alert('Activessss!'); </script>";
//location.replace('addmodel.php')
}
if($_GET['process']=="inactive"){
$id = $_GET['id'];
$mysqli = new mysqli('10.237.2.152','root','c0k3float','monitoring');
$results = $mysqli->query("UPDATE Shipment_Target SET status='Inactive' where id=".$id." ") or mysqli0;
echo "<script>alert('Inactive!'); </script>";
}
// location.replace('addmodel.php')
?>

Problem in the html code, try following code
<a href='settoActive.php?id=<?php echo $row['id']; ?>&process=actives' style='font-size:15px;' name='active' value="<?php echo $row['id']; ?>" class='btn btn-info' />ACTIVE</a>
<a href='settoActive.php?id=<?php echo $row['id']; ?>&process=inactive' style='font-size:15px;' name='active' value="<?php echo $row['id']; ?>" class='btn btn-info' />inactive</a>

Related

JS apply only for first element

I need some help to apply js code for all elements, but for now works only for first on each page.
On page are items with buy buttons, that is created by script, so all buttons have same id but is more than one of them - and I can't apply script that disable button if some condition, only work for first button.
<?php $elem = getElement('button_basket'); ?>
<button disabled = "true" onclick = "checkInput(event)" id="b1" class="btn btn-warning btn-lg btn-block tobasket <?php echo $elem['content_tr'] ?>" product_id="<?php echo $v['id']; ?>" name="<?php echo $prdata['full_name'] ?>" nametr="<?php echo $prdata['name1_tr'] ?>" url="<?php echo $cur_url; ?>catalog/<?php echo $v['img_url']; ?>" price="<?php echo $v['price']; ?>" <?php if($v['sold']==1) echo 'sold="true"'; ?>><?php echo $elem['content'] ?></button>
<?php $elem = getElement('button_oneclick'); ?>
<p class="prod-oneclick <?php echo $elem['content_tr'] ?>" <?php if($v['sold']==1) echo 'sold="true"'; ?>><?php echo $elem['content'] ?></p>
<script type="text/javascript">
function checkInput(event){
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
//echo $countChars;
?>
let test = '<?php echo $countChars;?>';
let btncheck = document.querySelectorAll('[disabled]');
// var step;
// for (step = 0; step < 5; step++) {
if (test > 80){
document.getElementById("b1").disabled = true;
}else{
document.getElementById("b1").disabled = false;
}
}
// window.onload = checkInput(event);
// }
</script>
if will need can provide full page script.
You should use data attributes and delegation
Also your script can be vastly simplified
let test = '<?php echo $countChars;?>';
window.addEventListener("load", function() {
[...document.querySelectorAll('[disabled]')].forEach(btn => btn.disabled = test > 80)
});
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
?>
<button disabled class="btn btn-warning btn-lg btn-block tobasket <?php echo $elem['content_tr'] ?>" data-product_id="<?php echo $v['id']; ?>" name="<?php echo $prdata['full_name'] ?>" data-nametr="<?php echo $prdata['name1_tr'] ?>" data-url="<?php echo $cur_url; ?>catalog/<?php echo $v['img_url']; ?>"
data-price="<?php echo $v['price']; ?>" <?php if($v[ 'sold']==1) echo 'data-sold="true"'; ?>><?php echo $elem['content'] ?></button>
<p class="prod-oneclick <?php echo $elem['content_tr'] ?>" <?php if($v[ 'sold']==1) echo 'data-sold="true"'; ?>>
<?php echo $elem['content'] ?>
</p>
Final code, fully working for me was:
<script>
function beCheerful() {
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
?>
let test = '<?php echo $countChars;?>';
window.addEventListener("DOMContentLoaded", function() {
[...document.querySelectorAll('[disabled]')].forEach(btn => btn.disabled = test > 80)
});
}
for (var i = 0; i < 1; i++) {
beCheerful();
}
window.onload = beCheerful;
</script>

PHP/HTML Add onclick function to subcategories with certain name

I am trying to add an onclick function for only certain recursively generated subcategories.
This code currently displays the subcategories correctly:
<?php if($parent) { ?>
<?php $search_params['sCategory'] = $parent['pk_i_id']; ?>
<a href="<?php echo osc_search_url($search_params); ?>" class="parent active" data-name="sCategory" data-val="<?php echo $parent['pk_i_id']; ?>">
<span class="name"><?php echo $parent['s_name']; ?></span><em>(<?php echo ($parent['i_num_items'] == '' ? 0 : $parent['i_num_items']); ?>)</em>
</a>
<?php } ?>
<?php foreach($categories as $c) { ?>
<?php $search_params['sCategory'] = $c['pk_i_id']; ?>
<a href="<?php echo osc_search_url($search_params); ?>" class="child<?php if($c['pk_i_id'] == $search_cat_id) { ?> active<?php } ?>" data-name="sCategory" data-val="<?php echo $c['pk_i_id']; $
<span class="name"><?php echo $c['s_name'];?></span><em>(<?php echo ($c['i_num_items'] == '' ? 0 : $c['i_num_items']); ?>)</em>
</a>
<?php } ?>
</div>
I would like to call say functionX(); written in JS for only the subcategory named "catx".
FunctionX() is working correctly when called else where.
I've tried something like this but get a White screen:
<?php if($search_params == "catX") {
echo '<a onclick="functionX();" href="<?php echo osc_search_url($search_params); ?>" class="parent active" data-name="sCategory" data-val="<?php echo $parent['pk_i_id']; ?>">
<span class="name"><?php echo $parent['s_name']; ?></span><em>(<?php echo ($parent['i_num_items'] == '' ? 0 : $parent['i_num_items']); ?>)</em>
</a>;'
} else {
echo '<a href="<?php echo osc_search_url($search_params); ?>" class="parent active" data-name="sCategory" data-val="<?php echo $parent['pk_i_id']; ?>">
<span class="name"><?php echo $parent['s_name']; ?></span><em>(<?php echo ($parent['i_num_items'] == '' ? 0 : $parent['i_num_items']); ?>)</em>
</a>;' ?>
Pretty new to this, thanks for the help!
When you use an echo you are using ' to specify the borders of what you are going to output.
In your code you have echo 'Some content' but your content contains an ' aswell. Named: $parent['pk_i_id']
There a several ways to do this. Here is an example (Concatenation):
echo '<a onclick="functionX();" href="' . osc_search_url($search_params) . '">Click me</a>'; // ...
The inline notation is useful, in case you have surrounding HTML-Code:
<b>My name is<?php echo $name ?></b>
Just dont mix em :)
It's not an approach that works for everyone but in this kind of scenario I find it visually helpful (and very useful if I need to debug anything) to incrementally build a string using
statements
variables; and
conditional statements
and then echo the string, once I have built it.
Example:
<?php
$Item_Number = ($parent['i_num_items'] === '') ? 0 : $parent['i_num_items'];
$Link = '';
$Link .= '<a ';
if ($search_params === 'catX') {
$Link .= 'onclick="functionX();" ';
}
$Link .= 'href="'.osc_search_url($search_params).'" class="parent active" data-name="sCategory" data-val="'.$parent['pk_i_id'].'">';
$Link .= '<span class="name">'.$parent['s_name'].'</span>';
$Link .= '<em>('.$Item_Number.')</em>';
$Link .= '</a>';
echo $Link;
?>

Modal doesn't open when php variables value is large

I am using an edit button inside while loop for each row of table to pass a row values into a modal form.
<td><a class="custom-links" onclick='EditModal("<?php echo $data['id']; ?>","<?php echo $data['name']; ?>","<?php echo $data['price']; ?>","<?php echo $data['description']; ?>","<?php echo $data['type']; ?>","<?php echo $data['cooking_instructions']; ?>","<?php echo $data['ingredients']; ?>","<?php echo $data['allergen_warnings']; ?>","<?php echo $data['storage_instructions']; ?>","<?php echo $data['case_size']; ?>","<?php echo 'uploaded_images/'.$data['image']; ?>")'>
<button type="button" id="<?php echo $data['id']; ?>" class='btn btn-primary glyphicon glyphicon-edit'></button></a></td>
Then i set values like
function EditModal(id,name,price,description,type,cooking_instructions,ingredients,allergen_warnings,storage_instructions,case_size,image){
document.getElementById("update_id").value = id;
document.getElementById("update_name").value = name;
document.getElementById("update_price").value = price;
document.getElementById("update_description").value = description;
document.getElementById("update_type").value = type;
document.getElementById("update_cooking_instructions").value = cooking_instructions;
document.getElementById("update_ingredients").value = ingredients;
document.getElementById("update_allergen_warnings").value = allergen_warnings;
document.getElementById("update_storage_instructions").value = storage_instructions;
document.getElementById("update_case_size").value = case_size;
document.getElementById("update_image_to_upload").src = image;
$('#update_menu_modal').modal('show');}
update_cooking_instructions, update_ingredients, update_allergen_warnings are textareas.
The problem is that modal gets opened when $data['cooking_instructions'], $data['ingredients'], $data['allergen_warnings'] contain less words or I remove them from EditModal function and when their values are large modal does not open.
Can anyone point out my mistake? What am I doing wrong? Modal is opening when I remove these three variables from EditModal
Give this a try, though note that you'll still have a problem with single quotes:
<td><a class="custom-links" onclick='EditModal(<?php echo json_encode($data['id']); ?>,<?php echo json_encode($data['name']); ?>,<?php echo json_encode($data['price']); ?>,<?php echo json_encode($data['description']); ?>,<?php echo json_encode($data['type']); ?>,<?php echo json_encode($data['cooking_instructions']); ?>,<?php echo json_encode($data['ingredients']); ?>,<?php echo json_encode($data['allergen_warnings']); ?>,<?php echo json_encode($data['storage_instructions']); ?>,<?php echo json_encode($data['case_size']); ?>,<?php echo json_encode('uploaded_images/'.$data['image']); ?>)'>
<button type="button" id=<?php echo json_encode($data['id']); ?> class='btn btn-primary glyphicon glyphicon-edit'></button></a></td>
I've removed the double quotes and instead used json_encode to emit a value. (I'm making the assumption that each value is a string on the PHP side.)
My guess as to the issue (though I'm stumped as to why it doesn't cause a console error) is that your "large" values have quotes or newlines in them. This sort of thing:
EditModal("<?php echo foo; ?>");
will turn into this if you have a newline:
EditModal("first line
second line");
which is not valid JavaScript. Similarly, a double quote would do this:
EditModal("Here is a quote --> " <-- see?");
which is also not valid JavaScript.
Using this instead:
EditModal(<?php echo json_encode(foo); ?>);
will turn those examples into these:
EditModal("first line\nsecond line");
and
EditModal("Here is a quote --> \" <-- see?");
both of which are fine.

AJAX code to save id value in database

I want to pass this value doctoridclickedRightNow into t_appointmentdetails table. I have made few changes to previous code using AJAX and JS as suggested on How to Pass variable from JavaScript to PHP Page using XMLHTTP . Appointment details are getting inserted into DB and I also want the doctorid of the corresponding doctor to be saved. So with the below changes I am able see the correct values being displayed when I use inspect element in mozilla. Kindly suggest me how to pass this to DB. Thanks in advance.
$sql = "SELECT doctorid, FIRST_NAME,LAST_NAME, Address, Qualification, Specialization, Consultation_Fee, Experience,image_path
from t_doctorprofile";
$results = mysqli_query($db,$sql)
or die('MySQL Error');
echo '<h3 style="color:#674172;margin- left:120px;float:center;display:inline-block"><strong>Available Dentists</strong></h3>';
while($result = mysqli_fetch_assoc($results)){
echo '<div class= "fetch" style="margin-left:120px">';
echo "<img src = 'uploads/".$result['image_path']."' width='150' height='150'>";
echo "<div id='info'>";
echo "<p><strong>".$result['FIRST_NAME']." ".$result['LAST_NAME']."</strong></p></div>";
echo "<p>".$result['Qualification']."</p>";
echo "<p>".$result['Specialization']."</p>";
echo "<p>".$result['Address']."</p>";
echo "<p>"."<b>Consultation Fee-</b>"." ".$result['Consultation_Fee']."</p>";
echo "<p>"."<b>Experience-</b>"." ".$result['Experience']."years"." </p>";
echo "<button class='btn btn-success btn-lg' id='$result[doctorid]' data-toggle='modal' data-target='#myModal' onclick='AssignDoctorIdClicked(id)'>
Appointment</button>";
echo "<script>var doctoridclickedRightNow;</script>";
echo "</div>";
echo '<form action="appointment_insert.php" method="POST">';
echo "<div class='modal fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>";
echo "<div class='modal-dialog'>";
echo "<div class='modal-content' style='background-color:#F1A9A0'>";
echo "<div class='modal-header'>";
echo "<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>";
echo "<h4 class='modal-title' id='myModalLabel' style='text-align:center; color:#fff'>
<strong>Book Appointment</strong></h4><br>";
echo "</div><br><br>";
echo "<div class='modal-body'>";
script for AssignDoctorIdClicked function:
<script>
function AssignDoctorIdClicked(id) {
console.log(id);
var doctoridclickedRightNow = id;
console.log(doctoridclickedRightNow);
</script>
appointment_insert.php page
if (isset($_POST["submit"])) {
$login_user = $_SESSION['username'];
$datetime = $_POST['datetime'];
$info = $_POST['info'];
$recieved_1 = $_GET['FIRST_NAME'];
$query = mysqli_query($db, "INSERT INTO t_appointmentdetails (patient_name,datetime,info) VALUES ('$login_user','$datetime','$info');");
$insertedDataBoolean = true;
if($insertedDataBoolean){
echo "Name: " . $recieved_1 . " booked successfully.";
}
else{
echo "Data-insertion error.";
}
}

How to create for each div in a while loop an ID and alert it with JQuery

I have 2 paragraphs coming from the database it work there is no issues with it. But I have added a button that when I click it will alert the ID of this current div which the button is present.
Now this is my table:
+--------+--------------------+
| id | paragraph |
|--------+--------------------+
| 1 | this is text 1 |
| 2 | another text |
+-----------------------------+
My PHP and HTML code:
<?php
$query = mysql_query(SELECT * FROM tests);
while($row = mysql_fetch_assoc($query)){
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id='text' class='<?php echo "$post_id";?>'>
<p><?php echo "$text";?></p>
<input type='button' value='Show id' id='show'>
</div>
<?php } ?>
And now probably 2 paragraphs are generated but when I click at show button it will show only the 1 id even if I click at the second one:
This is my JQuery code:
$('#show').click(function(){
var ids = $("#text").attr('class');
alert(ids);
});
id="" attribute values are supposed to be unique. do the other way around:
<div id="<?php echo $post_id; ?>" class='text'>
<p><?php echo $text; ?></p>
<input type='button' value='Show id' class='button'>
</div>
jquery
$('.button').click(function(){
var ids = $(this).parent('div').attr('id');
alert(ids);
});
Note: Stop using mysql_ functions, instead use mysqli_* or PDO
Sample:
<?php
$con = new mysqli('localhost', 'username', 'password', 'database');
$result = mysqli_query($con, 'SELECT * FROM tests');
while($row = $result->fetch_assoc()) {
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id="post_<?php echo $post_id; ?>">
<p><?php echo $text; ?></p>
<button type="button" class="button">Show</button>
</div>
<?php } ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$('.button').click(function(){
var ids = $(this).parent('div').attr('id');
alert(ids);
});
</script>
Very important point from Jeroen:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Reference
this is hard to read
<?php
$query = mysql_query(SELECT * FROM tests);
while($row = mysql_fetch_assoc($query)){
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id='text' class='<?php echo "$post_id";?>'>
<p><?php echo "$text";?></p>
<input type='button' value='Show id' id='show'>
</div>
<?php } ?>
Try something like this
<?php
$query = mysql_query('SELECT * FROM tests');
while(false !== ( $row = mysql_fetch_assoc($query))):
?>
<div class='text' id='post-<?php echo $row['id']; ?>'>
<p><?php echo $row['paragraph']; ?></p>
<input type='button' value='Show id' id='show'>
</div>
<?php endwhile; ?>
I don't see how the query worked without quotes. Just to explain you can use the alternative syntax for the while, so instead of
<?php while(. .. ){ ?>
<html></html>
<?php } ?>
do
<?php while(... ): ?>
<html></html>
<?php endwhile; ?>
When you have a lot of html ( this is a small example ) you can easily find the diffrence between endif; endwhile; or endforeach; then } } or }
Why don't you just pass the ID as a parameter?
<?php
$query = mysql_query("SELECT * FROM tests");
while($row = mysql_fetch_assoc($query)){
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id='text' class='<?php echo "$post_id";?>'>
<p><?php echo "$text";?></p>
<input type='button' value='Show id' id='show' onclick="showId(<?php echo $post_id; ?>);">
</div>
<?php } ?>
Then your script could look like this:
function showId(theId){
alert(theId);
}
where it says:
class='<?php echo "$post_id";?>'
when you're echoing a php variable, you dont put quotes around it:
class='<?php echo $post_id;?>'.

Categories