So i'm trying to make it so when I select something from the first select box will create a PHP variable.
Say in the select box I select option 1, it will create a php variable like $number = 1;. or if I select option 5 it'll create a variable like $number = 5;.
I know this require's ajax, but I have minimal to no experience with this at all.
Code:
<form class="form-horizontal row" id="select-service">
<div class="form-group">
<label class="col-sm-4 control-label">Select Social Media</label>
<div class="col-sm-4">
<select class="form-control" name="category" id="category" onchange="func(this.value)">
<?php
$stmt = $pdo->prepare('SELECT * FROM categories');
$stmt->execute();
if($stmt->rowCount() > 0) {
echo'<option selected="true" style="display:none;">Select a social media</option>';
} else {
echo '<option selected="true" style="display:none;">No social medias are available</option>';
}
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Select Service</label>
<div class="col-sm-4">
<select class="form-control" id="service" onchange="quantity(this.value)">
<option selected="true" style="display:none;">Please select a category.</option>
</select>
</div>
</div>
<ul class="pager wizard">
<div class="pull-right">
<li class="next">
<button href="#" class="btn btn-info"><i>Next</i></button>
</li>
</div>
</ul>
You cannot alter PHP variables on runtime (at least not from the same document you are executing the AJAX script). This is because PHP and jQuery are executed on diferent levels:
PHP is server side processing and jQuery happens on the client side.
Yes. AJAX can be used to make PHP requests but it does not exactly can alter variables in real time.
AJAX is a client side solution for calling external php files. in these files you could do basically anything you can do with a php request:
Read data from server
Insert data to server
Update parameters
Etcetera.
What you could do, depending on what you need is desing your site so what you need could be done using an external php file.
You call myfile.php?number=1 using AJAX
And then in myfile.php
<?php
$number = $_GET["number"]; // this sets the $number var to 1
//process or do whatever you need with the number
echo $number;
?>
This echo call will not be displayed on sceen as it normally is but instead you fetch it to Javascript or jQuery and process whatever you need it for.
I recomend you read the W3 Schools guide on AJAX for JS because it contains examples and it is very well explained on what you can do and how tho acomplish it.
Related
This has been answered before, however I'm asking again for two reasons: I can't find any resources that utilize PDO, and regardless of that, all of the ones I've found consist of code without any comments or explanations, which makes it hard to interpret and adapt them to my use case.
I need to be able to make a dropdown dynamically update itself based on the selection of the previous one, and if I change that selection, it should re-update itself without having to submit the form or reload the page.
I've updated the code with what I've learned and found so far, but it's still not working properly. Everything works up to the point where the second dropdown should begin loading values.
HTML:
<div class="form-group row">
<label class="col-sm-2 form-control-label" onchange="productorInfo(this.value);">Codigo Productor (*)</label>
<div class="col-sm-4">
<select name="vendedor_codigo">
<?php foreach ($dd_productor_result as $dd_productor_display) : ?>
<option value="<?= $dd_productor_display['vendedor_codigo']; ?>">
<?= $dd_productor_display['vendedor_codigo']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<label class="col-sm-2 form-control-label">Nombre (*)</label>
<div class="col-sm-4">
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
Ajax script:
function productorInfo(id) {
$.ajax({
type: "GET",
url: "/controller/produccion/db_ajax_update.php",
data: "mainid =" + id,
success: function (result) {
$("#ajax-vendedor").html(result);
}
});
};
First dropdown PHP code:
$dd_productor = "SELECT vendedor_codigo FROM lista_productores";
$productor_stmt = $pdo->prepare($dd_productor);
$productor_stmt->execute();
$dd_productor_result = $productor_stmt->fetchAll();
Second dropdown (ajax call):
if(isset($_GET['mainid'])){
productorInfo($_GET['mainid']);
$prod_value = productorInfo($_GET['mainid']);
}
$ajax_productor = "SELECT vendedor_nombre FROM lista_productores WHERE vendedor_codigo = {$prod_value}";
$productor_stmt = $pdo->prepare($ajax_productor);
$productor_stmt->execute();
$ajax_productor_result = $productor_stmt->fetchAll();
The onchange call should be on the select element not on the label
<label class="col-sm-2 form-control-label">Codigo Productor (*)</label>
<select name="vendedor_codigo onchange="productorInfo(this.value)">
But also it occurs to me you may not quite understand the process. Your ajax call won't be fired when the page loads so this bit:
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
i would think is giving you undefined variable warnings (unless you are setting $ajax_productor_result initially in some way)
Responses from ajax are usually drawn in .js via success: function
(result) {
$("#ajax-vendedor").html(result);
}
from the looks of this though - unless there is more code that what has been posted, you are passing the .html() function an array or database rows so it's never going to display anything.
so you need to
1)draw a select with no options in it on pageload (or default options if you have them)
2)return a response that the success function can make use e.g. a json string which jquery can the parse
3)format the data in jquery into the <options> and then user the .html() function to update the select
4)if you want this to happen when the page initially loads then add in a document ready call to the productorInfo(id) function - this would be relevant if you are setting the initial select value in some way (so it may not be relevant to you)
I am currently creating an image gallery website, and somehow no matter what I do, the first image that I posted on the system is always unavailable. I have this 'show info' button on the image, which does a post request that calls on the showinfo.php.
This is the display.php that displays all available image in the database.
if ($method == "0") {
$stmt = $conn->prepare("SELECT * FROM image");
$stmt->execute();
$result = $stmt->get_result();
echo "
<div class='container'>
<div class='row text-center' style='display:flex; flex-wrap: wrap;'>";
while ($row2 = $result->fetch_assoc()) {
echo "<div class='col-md-3 col-sm-4'>
<div class='thumbnail'>
<img src='".$target_dir.$row2['filename']."'>
<div class='caption'>
<h4>".$row2['name']."</h4>
</div>
<p>
<form action='showinfo.php' method='POST' enctype='multipart/form-data'>
<input type='hidden' name='image_id' value='".$row2['id']."'>
<button name='showinfo' class='btn btn-primary'>More Info</button>
</form>
</p>
</div>
</div>";
}
echo "</div> </div>";
}
This is how it looks like on the webpage, notice that the first image/first row of the table in mysql will still be fetched:
And when click on the 'more info' button, it will redirect to the showinfo.php, which shows something like this:
However, it never works for the first image. I have done some testings, it never gets to the showinfo.php page and it will always redirect back to the homepage after I click the button. I have used postman to do a post request, setting the image_id to 1 and that gets me the info page of the first image, just not when the button is clicked. I am using XAMPP 5.6.37
This is the expected result I should get for the first image
Ignore the jammed up stuff.. but the post request goes through.
This is the showinfo.php code
Why using form to show data of that product on next page what if user copy link and share it to somewhere else it will not have it's post data in it and result will be error page with no data. So far better way to use it.
if ($method == "0") {
$stmt = $conn->prepare("SELECT * FROM image");
$stmt->execute();
$result = $stmt->get_result();
echo "
<div class='container'>
<div class='row text-center' style='display:flex; flex-wrap: wrap;'>";
while ($row2 = $result->fetch_assoc()) {
echo "<div class='col-md-3 col-sm-4'>
<div class='thumbnail'>
<img src='".$target_dir.$row2['filename']."'>
<div class='caption'>
<h4>".$row2['name']."</h4>
</div>
<p>
<a href='showinfo.php?image_id=".$row2['id']."'> <button name='showinfo' class='btn btn-primary'>More Info</button></a>
</p>
</div>
</div>";
}
echo "</div> </div>";
}
on showinfo.php page you can use $_GET['image_id'] to get data from mysql as per image id and will work globally everywhere with link.
thanks for all the suggestions. Someone mentioned that I should try to take our the redirect code to see why the problem is happening. I did that, and I was able to get the first image's info without any issue. So I look into the code on my homepage ... It turns out it's none of the issues we talked about. On my homepage I have wrapped around the "method" selection code in a form, which is why it's causing that problem. My code originally look like this, and the showImages(this.value) is a js function that will call the display.php shown above.
The div with the id "showimage" is where all the thumbnails show up.
Once I take out the , I was able to solve my issue.
<form>
<div class='form-inline'>
<input class='form-control' type='text' id='menu_search_input' size='50' placeholder="enter content first if searching by name..">
<select class='form-control' id='menu_search' onchange='showImages(this.value)'>
<option value=''>Search by</option>
<option value='0'>Search by Latest</option>
<option value='1'>Search by Image Name</option>
<option value='2'>Search by Category</option>
<option value='3'>Search by Most Popular</option>
<option value='4'>Search by Least Popular</option>
<option value='5'>Search by Most Credit Needs</option>
<option value='6'>Search by Least Credit Needs</option>
</select>
<div id="showimage">Loading images ...</div>
</div>
</form>
I have a very simple form:
<form action="system/web/push.php" method="post">
<div class="row">
<div class="col card_input_push card_input_push_language">
<select name="<?php echo PARAM_PUSH_LANGUAGE; ?>">
<?php echo get_languages($mysqli); ?>
</select>
</div>
</div>
<div class="row">
<div class="col card_input card_input_push">
<input type="text" name="<?php echo PARAM_PUSH_TITLE; ?>" placeholder="<?php echo $language_array[LV_PUSH_INPUT_TITLE]; ?>"<?php echo set_value(PARAM_PUSH_TITLE); ?>required/>
</div>
</div>
<div class="row">
<div class="col card_input_push card_input_push_message">
<textarea name="<?php echo PARAM_PUSH_MESSAGE; ?>" placeholder="<?php echo $language_array[LV_PUSH_INPUT_MESSAGE]; ?>"<?php echo set_value(PARAM_PUSH_MESSAGE); ?>required></textarea>
</div>
</div>
<div class="row">
<div class="col text-center card_input_push card_button_push_send">
<button class="btn btn-default" type="submit" name="<?php echo REQUEST_SEND_GCM; ?>" value="<?php echo $language_array[LV_PUSH_INPUT_SEND]; ?>"><?php echo $language_array[LV_PUSH_INPUT_SEND]; ?></button>
</div>
</div>
</form>
When i now press the submit button i dont want the post to perform instantly. I first want a confirmation dialog to show up with yes or no answers and only if the user says yes i want the post action to be performed.
What i NOT want is to use JavaScript. Is there a way to do that?
EDIT
Thank's for the answers. To satisfy all respondents i would like to tell you, why i dont want to use JavaScript. The answer is simple. I have no idea about JavaScript. I never have used it before but the project im working on (as always) has to be finished ASAP. That's the only reason.
Yes there is a way, use GET (not POST) the first time, on the PHP file check if GET was used and if so generate a form that sends confirmation form back to the user. Then make confirmation form to submit using POST and you are done.
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// generate confirmation form
}elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// process your data
}
If anyone has access to a book called Head First PHP-MySQL they cover a similar example on page 280.
Maybe you could do something like this, with some css for design your dialog.
change your form with :
<form action="this_page">
If you submit, you call this page, display the dialog with a form, and when you submit with second form, you post to your needed php file.
if (isset($_POST['your_submit'] )) {
echo "<yourdialog>";
echo "<form action="system/web/push.php">";
echo "content";
echo "<submit yes>";
echo "</form>";
echo "</yourdialog>";
}
Your workflow is:
gather form data
send to server
get confirmation that that's what the user wants.
if yes then process data.
If you want to do that all via php then the server's handling the full load, so you'll want two forms, one to collect and one to confirm. And you'll want to store the first form's data so you can process it according to the second form's result. A bit old fashioned but not difficult.
I am making a simple page and I have found this little problem. I have this in my template:
<?php foreach ($this->vypis_serie as $value) : ?>
<div class="serie">
<div id="serie_header">
<?= $value['nazev_cviceni'] ?>
</div>
<div id="serie_info">
<p>Number of excercises: TODO</p>
<p>Sport type: <?= $value['typ'] ?></p>
<p>KCal summary: <?= $value['kcal'] ?></p>
</div>
<div class="button_upravit">Edit</div>
<div class="button_smazat">Delete</div>
</div>
<?php endforeach; ?>
basically it is a block that fills in information about particular exercise (it is a sport app). SO If I have 3 entries in DB, it will print this code three times with corresponding info.
The problem I have is with the edit button, which upon clicking opens modal window. It is made purely with CSS, so no Javascript.
When I click the button, it jumps to this code:
<div id="openModal_edit" class="modalDialog">
<div>
X
<div id="editace">
<form id="platba" action="serie/edit/" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Edit serie</legend>
<ol>
<li>
<label for="name">Name of the series</label>
<input id="name" name="nazev_cviceni" type="text" required autofocus>
</li>
<li>
<label for="typ">Sport type</label>
<select name="typ">
<option value="Kolo">Bike</option>
<option value="Běhání" selected="selected">Running</option>
</select>
</li>
</ol>
</fieldset>
<fieldset>
<button type="submit">Save</button>
</fieldset>
</form>
</div>
</div>
</div>
But since I jump to div id and I am not using a new page where I could choose a controller and pass a variable, I need somehow to pass the variable (id of the exercise) to the modal window, so I can know which of the possible buttons I have clicked. Is there any way to do it, without the need to rewrite all other pages where I have used this modal window?
I can't use another foreach like in the first part, because the modal window is always a single object that appears, unlike all the entries on the page that are there as many times as there are entries in the DB.
Hope that it is understandable, sorry for my English :)
The simplest way to do this using a single modal window involves adding some javascript code to your page.
First, add the relevant information to the edit link, with a new data-serie-<name> for each piece of data you want to pass:
<a href="#openModal_edit" data-serie-name="<?= $value['nazev_cviceni'] ?>" ...>
Next, add an onclick event handler to that same link. This handler will extract the embedded data from the <a> element and inject it in the modal window. The dataset element provides access to the data-* attributes from javascript
// Example
onclick="serieName=this.dataset.serieName;document.querySelector('#openModal_edit input#name').value = serieName;return true;"
I have read through all the "dynamic multiple dropdown lists" questions here on stackoverflow but could not find what I am looking for.
It's a form for states and cities. User select a state, through ajax I request the cities for that specific state ID.
But, I need to have the two selects already created and displayed (maybe the city select grayed out). An example here PenskeAutomotive.
What I managed to do so far is to have only the state select and upon the execution of ajax, from the XMLHttp.ResponseText to create the city select. An example here Dorpdown list example - at bottom of page.
I need to have both selects displayed and then only update the city select with the new values of the XMLHttp.ResponseText.
Can anybody point me to some direction?
UPDATE:
Right after posting I found a question that I have not read before. Went into it and I may have found my direction. I am just trying that right now. It's jQuery/Ajax. Question
Not sure where you're having trouble, but to (hopefully) point you in the right direction:
You could have both of your <select> elements created on the page, with the City dropdown having the HTML disabled attribute, which will gray it out.
The disabled dropdown will have no options, aside from maybe one that says something like "select state."
You'll add an onchange event listener to your State dropdown which will perform the AJAX call, and I would recommend you get your response back in JSON format.
Then you can clear out the options of the next dropdown and create and append the new options from your server, then enable the dropdown.
If you want to provide what you've done so far, I'm sure we can help debug it.
I use this code in my site, maybe is usefull for you:
in head:
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select1").change(function(event){
var id = $("#select1").find(':selected').val();
$("#select2").load('../scripts/depto.php?id='+id);
});
});
</script>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select2").change(function(event){
var id = $("#select2").find(':selected').val();
$("#select3").load('../scripts/municipios.php?id='+id);
});
});
</script>
and in select:
<div class='control-group'>
<label class='control-label' for='typeahead'>País </label>
<div class="controls">
<select name="IDPAIS" id="select1" required>
<?
$sql = $conn->prepare("SELECT * FROM lista_paises");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion].'</option>';
}
?>
</select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Departamento </label>
<div class="controls">
<select name="departamento" id="select2" required></select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Municipio / Ciudad</label>
<div class='controls'>
<select name="ciudad" id="select3" required></select>
</div>
</div>
in the lista_paises.php
<?
include('../include/config.php');
$query = $conn->prepare("SELECT * FROM PAISES);
$respuesta="[";
foreach ($aMunicipios as $muni) {
$respuesta .="{id:".$muni["id_municipio"].",nombre_municipio:'".$muni["municipio_nombre"]."'},";
}
$respuesta = substr($respuesta,0,strlen($respuesta)-1);
$respuesta.="]";
echo $respuesta;
}
?>
in depto.php
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM lista_estados WHERE relacion = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion1].'</option>';
}
?>
in municipios.php(ciudad/city)
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM MUNICIPIOS WHERE relacion1 = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion2].'</option>';
}
?>
maybe works for you