My browser keeps refreshing - php

After I created an if inside a SELECT tag (HTML) my browser keeps refreshing.
The purpose of this if is to make an OPTION selected when the condition appear.
I also have done this earlier on the same page and it worked.
My guess is that having the 2 SELECT dropdowns on the same page, having this code is making them to refresh each other (I have a jQuery to do onchange actions).
the code is this:
<select name="ddequipamento" id="ddequipamento" class="cliente" <? if (!$_GET['id']) echo "disabled" ?> >
<option value="---">---</option>
<?
if ($_GET['id'])
{
for ($i = 0; $i < $count_equipamento; $i++)
{
$idequipamento = mysql_result($result_equipamento,$i,"idequipamento");
$marca = mysql_result($result_equipamento,$i,"marca");
$tipo_equipamento = mysql_result($result_equipamento,$i,"tipo_equipamento.tipo_equipamento");
$num_serie = mysql_result($result_equipamento,$i,"num_serie");
echo (' <option value="'.$idequipamento .'" ');
if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
echo (' >'.$tipo_equipamento. ' - '. $marca . ' - '. $num_serie .'</option>');
}
}
?>
<option value="0" >Novo</option>
</select>
and the jQuery:
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val();
});
});

Please pass "eq" through URL , Please change it in script,
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val()+"&eq=<?php echo $_GET['eq'];?>";
});
});
If you want to "id" only then change in PHP part,
if ($_GET['id'] = $idequipamento){ //OLD if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
IF TWO DROPDOWNS WITH DIFFERENT ID "eq" and "id"
if you have 2 drop-downs use,
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val()+"&eq=<?php echo $_GET['eq'];?>";
});
$('#ddcliente2').change(function () { //CHANGE THE ID OF SECOND DROPDOWN
window.location.href = "index.php?eq="+ $(this).val()+"&id=<?php echo $_GET['id'];?>";
});
});
and also change the PHP part for 2 drop-downs
// FIRST DROP DOWN
if ($_GET['id'] = $idequipamento){ //OLD if ($_GET['id'] = $idequipamento){
echo (' selected="true" ');
}
// SECOND DROP DOWN , CHANGE VARIABLE NAME of $idequipamento2
if ($_GET['eg'] = $idequipamento2){ //OLD if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}

Related

Selection option in php loop

I have the code below and this code works, but only after clicking on selection option but code doesn't work when i change value when use arrow up and down.
I tried modification script, change option "click" to "change" but this solution doesn't work. Someone can help me ?
$select = $db_connect -> query("SELECT * FROM templates");
if($select -> num_rows > 0)
{
echo '<select id="subject" name="subject" class="form-select">';
while($row = $select -> fetch_assoc())
{
echo '<option id="'.$row["id"].'" value="'.$row['template_subject'].'">'.$row['template_subject'].'</option>';
?>
<script>
$("#subject #<?php echo $row['id']; ?>").on('click', function(){
if((this.id = "<?php echo $row['id'];?>") && (this.id != 1))
{
$("textarea").html("<?php echo $row['template_text']; ?>");
$("input[name='new_subject']").hide();
}
else
{
$("textarea").html("");
$("input[name='new_subject']").show();
}
});
</script>
<?php
}
echo '</select>';
}
Your problem is in the Javascript code.
<script>
$("#subject").change( function(){
var text = $( "#subject option:selected").val();
var id = $(this).children(":selected").attr("id");
if(id != 1)
{
$("textarea").html(text);
$("input[name='new_subject']").hide();
}
else
{
$("textarea").html("");
$("input[name='new_subject']").show();
}
});
</script>
remove the script from the while loop , put it at the end before </body> tag.

Autofill a select after submission via jQuery

I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $_POST['brand_car']);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
echo json_encode($model);
}
jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
}}
});
});
XHTML + PHP
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
getModels(id, 0);
}
function getModels(id, select) {
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="0">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
$('#model_car').val(select);
}}
});
}
This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
Tag this at the end:
<?php
echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>
This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
// I know nothing about your design, but globals are no good
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $brand_car);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
return $model;
}
AJAX.php
if ($_POST['brand_car']) {
echo json_encode(getModels($dbh, $_POST['brand_car']));
}
In your XHTML + PHP
<select id="model_car" name="model_car">
<?php
foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
}
?>
</select>
PS. It looks like your $_SESSION['brand_car'] is never updated.

Getting value from dynamically created pop up menu

I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>

Language configuration (change url and refresh page on DropDown change)

I am setting up a multilanguage website.
I have a dropdown where there is a set of languages that I cover.
I would like script, when dropdown changes, add or replace variable to url and refresh the page.
I do not want to store language in session or cookie.
My goal is that search egnines indexes all my multilanguage pages and to have url rewritting so my URL would look like http://www.index.php/EN/home, which I will cover later.
Currently I have a DropDown which sumbits form on change:
echo "<select name='lang' onchange='this.form.submit()'>";
$array = oci_parse($conn, "SELECT code, name FROM languages");
oci_execute($array);
while ($row = oci_fetch_array($array))
{
if ($lang == $row[0])
{
echo "<option value=".$row[0]." selected='selected'>".$row[0]."</option>";
}
else
{
echo '<option value='.$row[0].'>'.$row[0].'</option>';
}
}
echo '</select>';
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<select name='lang' id="dropdown">
<option value="EN">English</option>
<option value="FR">French</option>
</select>
<script>
$('#dropdown').change(function()
{
var langValue = $('#dropdown').val(); // i.e. langValue='EN' or langValue='FR'
if(langValue)
{
window.location.href = 'http://www.index.php/' + langValue + '/home';
return true;
}
return false;
});
function addLang(langValue)
{
var url = window.location.href;
var urlP = url.split('/');
if(urlP.length <4)
{
url = url + langValue; // adding new lang
}
else
{
url[3] = langValue; // replace old lang
url = url.join('/');
}
console.log(url);
}
</script>
Try this,
$(document).ready(function(){
$('#form').submit(function()
{
var lang=$("[name='lang']")val();
window.location.href='http://www.index.php/' + lang+ '/home';
}
});
});

How to call/activate the 2nd select list only after 1st select list was selected?

I have the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,

Categories