Image change from dropdown using AJAX - php

Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data:'id='+val,
success: function(data){
$("#style_code").html(data);
}
});
}
</script>
Here is check.php
<?php
$con=mysqli_connect("localhost","root","","db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con,$query);
while ( ($row=mysqli_fetch_array($results))){?>
<option value="<?php echo $row["color_name"]; ?>">
<?php echo $row['size'] ; ?>
</option>
<?php
}
}
?>

Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.
It would be something like that :
check.php
<?php
$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
$data = new stdClass(); // This object will carry the results
while (($row = mysqli_fetch_object($results))) {
$data->option[] = $row;
}
// Another query to get the image name
$query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
if ($row = mysqli_fetch_object($results)) {
$data->image_name = $row->name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
HTML & Javascript:
...
<div class="thumb-image" id="style_image" >
<img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>
...
<script language="javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data: {id: val},
dataType:'json',
success: function(data) {
$("#style_code").children().remove(); // empty the dropdown
// Add new options in the dropdown from the result data
data.option.forEach(function (item) {
$("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
});
// Change the 'src' attribute of the <img>
$("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
}
});
}
</script>

Related

How can I get clicked input radio value from autocomplete to send in form to php file

I'm doing an input with autocomplete where my user can select multiple users from database and I want to submit those select users in my form where action goes to a php file that does a INSERT in the database.
So this is the input, I want the selected users to show up in p#selecionados but user selects one at a time:
<form id="formCriaJogo" method="post" action="./components/insert.php">
<label>Other users</label>
<input type="text" name="autor" id="autor" placeholder="Write users name" />
<div id="autorLista"></div>
<p id="selecionados"></p>
<button type="submit">Insert</button>
</form>
And this is jquery code to do the autocomplete:
$(document).ready(function() {
$('#autor').keyup(function() {
var query = $(this).val();;
if (query != '') {
$.ajax({
url: "./components/search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$("input#autor").css("margin-bottom", '0');
$("#autorLista").css("display", 'block');
$('#autorLista').fadeIn();
$('#autorLista').html(data);
},
error: function(error) {
console.log(error);
}
});
}
});
$('input#autor').on('change', function() {
alert($('input[name=autor]:checked', '#formCriaJogo').val());
});
});
Also, here is search.php that does the search:
<?php
include_once "../connection/connection.php";
if (isset($_POST['query'])) {
$link = new_db_connection();
$stmt = mysqli_stmt_init($link);
$output = '';
$input = $_POST['query'];
$query = "SELECT id_user, nome_user FROM users WHERE nome_user LIKE CONCAT(?, '%')";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, 's', $input);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_user, $name_user);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
while (mysqli_stmt_fetch($stmt)) {
$output .= "<input type='radio' value='" . $id_user . "' name='autor'>" . $name_user . "<br>";
}
} else {
$output .= '<p>The user your looking for doesn't exist.</p>';
}
echo $output;
}
Now the clicked input type=radio value which contains users' id and name I want the user name in p#selecionados just to show them what he selected and also send id and name of user selected when submitting my form.
You can create an array in jquery so , whenever you select an option from autocomplete box.. put that value inside that array in jquery .I have use checkbox instead of radio-button in below code and whenever user select any option that data will get inserted in array i.e:index and when insert button is clicked the selected data will get display in p#selecionados tag and also an ajax will call to send your selected data to php page.Also i have added value='" . $id_user."," . $name_user . "' you can split this using .split() with delimiter , to get both userid and username.Sample code :
var index = [];
//when check-box is changed
$('input[name=autor]').change(function() {
//checking if checkbox is check put it in array
if ($(this).is(':checked')) {
index.push($(this).val());
console.log(index)
} else {
//if uncheck remove the element from array
if ((index1 = index.indexOf($(this).val()) !== -1)) {
index.splice($.inArray(index1, index), 1);
console.log("remove");
}
}
});
//when insert button is click
$("button").click(function() {
//clear the p tag content
$("p#selecionados").html("");
for (var i = 0; i < index.length; i++) {
//append all selected check box
$("p#selecionados").append(index[i] + "<br />");
console.log("userid & username" + index[i]);
}
if (index != '') {
$.ajax({
url: "yourphp_page_name",
method: "POST",
data: {
//sending array to php
data: index
},
success: function(data) {
//do something
},
error: function(error) {
//do something
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<button type="submit">Insert</button> <br/><br/> Selected data :
<p id="selecionados"></p>
Then in your php side ,you need to get that array i.e : data using $_POST['data'] and then explode your array and use it as per your requirement.

ajax search displaying id onclicking the name

this code displays the name as i type, as i type it gives suggestion of names and when clicked on it it displays the result in the textbox.but i want to display the id related to that name from database when i clicked on that name from the dropdown option. please help
<input type="text" name="st_id" id="st_id" ><div id="txtHint" style="position: absolute; width:390px ;"></div>
ajax code:
$(document).ready(function () {
$("#st_id").keyup(function () {
var search = $(this).val();
if (search != '') {
$.ajax({
type: "POST",
url: "ajaxcode.php",
data: {search: search},
success: function (data) {
$("#txtHint").fadeIn();
$("#txtHint").html(data);
}
});
}
});
});
php code
<?php
if (isset($_POST["search"])) {
$display = '';
$q = $_POST["search"];
$stmt = $DBconnect->prepare("SELECT * FROM table1 WHERE First_name LIKE :sh ");
$stmt->bindValue(':sh', '' . $q . '%', PDO::PARAM_STR);
$stmt->execute();
$display = '<ul class="list-unstyled">';
foreach ($stmt as $row) {
if ($row) {
$display .= '<li>' . $row["First_name"] . ' ' . $row["Middle_name"] . ' ' . $row["Last_name"] . '</li>';
} else {
$display .= '<li>name not found</li>';
}
}
$display .= '</ul>';
echo $display;
}
?>
Most naive way I can come up with is adding an id to the top ul
<ul id="name_suggestion" class="list-unstyled">
and the id to the <li> tag with a data- attr
$display .= '<li data-user-id = '. $row["id"] . '>'.$row["First_name"].' '.$row["Middle_name"].' '.$row["Last_name"].'</li>';
Then add an a click listener to the li:
$('#name_suggestion li').on('click', function(e){
let val = $(this).attr('data-user-id');
$('#st_id').val(val);
});

how to show another dropdown box depend on dropdown box value

please i need help
i need to do specail command
when some value selected then show another dropdown box
my first dropdown box is in php
and he is my code :
$conn = mysqli_connect("localhost", "root",
"", "phoneunlock" )
or die("Cannot connect to database:" .
mysqli_connect_error($conn));
echo "<select name='selectedValue' class= 'dropdown' >";
echo '<option value="">'.'Please Select Service'.'</option>';
$sql = "SELECT id, manufacter FROM product";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{ echo "<option value='" . $row['manufacter']. "'>" . $row['manufacter'] . '</option>';
}
echo '</select>';
and know i need some command like this :
if dropdown box selected = value then
do this
end if
sow please can any one help me
if you mean like chained combobox. try using jQuery like this :
$('#yourcomboid').on('change', function() {
var id = $(this).val();
$('#youranothercombo').empty();
$.ajax({
url: 'your-route-to-get-data/' + id,
success: function(data) {
$('#youranothercombo').empty();
for(var i = 0; i < data.length; i++) {
var item = data[i];
$('#youranothercombo').append($('<option></option>').val(item.column-name).text(item.column-name));
}
}
});
});
Hope this code works.

Dynamic drop down menus

I want to create a dynamic drop down where the options of the second drop down changes after the selection of the first drop down.
The test.php file
<?php
$con=mysqli_connect("localhost","******","****","******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM countries");
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['country_id'] . "'>" . $row['country_name'] . "</option>";
}
?>
</select>
<div id="get_state"></div> // Sub will be appended here using ajax
<script type="text/javascript">
function get_states() { // Call to ajax function
var country = $('#country').val();
var dataString = "country="+country;
$.ajax({
type: "POST",
url: "getstates.php", // Name of the php files
data: dataString,
success: function(html)
{
$("#get_state").html(html);
}
});
}
</script>
<?php
mysqli_close($con);
?>
and the gestates.php is:
<?php if ($_POST) {
$country = $_POST['country'];
if ($country != '') {
$sql1 = "SELECT * FROM states WHERE country_id=" . $country;
$result1 = mysql_query($sql1);
echo "<select name='state'>";
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result1)) {
echo "<option value='" . $row['id'] . "'>" . $row['state_name'] . "</option>";}
echo "</select>";
}
else
{
echo '';
}
}
?>
However the above code does not work!
on change on first drop-down you need to make an ajax call which will get the options and you can then populate the next drop-down
Try adding single quotes around $country
$sql1 = "SELECT * FROM states WHERE country_id='" . $country . "'";
or
$sql1 = "SELECT * FROM states WHERE country_id='$country'";
EDIT: Also, you can only echo one result. Your second echo will be ignored by Jquery as the first will be considered a success.
You should format your results differently.
Perhaps a json encoded array.
In your php:
while($row = mysql_fetch_array($result1))
{
$data[$row['id']] = $row['state_name'];
}
echo json_encode($data);
In your Jquery set dataType: 'json'
$.each(html,function(key,value){
$("#get_state").append($('<option>',{
value:key,
text: value
}));
});

How to save a page with html5 webstorage?

I have the following page, which works with MySQL, PHP and AJAX
if I click a NAME (id="orderN") it gives me back the result of the consult, which orders the names descending or ascending.
Is there any way that if you refresh(F5) the page, the result is saved as it was before closing, (ASC or DESC)?
I heard about cookies and HTML5 Storage, which is better than cookies.
if you can do it with either of them, let me know please
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
</head>
<body>
<table>
<tr><th>Name</th></tr>
</table>
<?
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "SELECT NAME
FROM STUDENTS";
$query = mysql_query($consult);
echo "<div id='DivConsult'><table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['NAME'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
<script>
$(document).ready(function() {
var contName = 0;
$('#orderN').click(function() {
contName++;
if (contName % 2 !== 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=ASC",
success: function(data) {
$('#DivConsult').html(data);
}});
}
if (contName % 2 == 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=DESC",
success: function(data) {
//alert(data);
$('#DivConsult').html(data);
}});
}
});
});
</script>
</body>
AJAX:
<?php
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "";
if (isset($_POST['tipOrder'])) {
if ($_POST['tipOrder'] == 'ASC') {
$consult = "SELECT NOMBRE
FROM STUDENTS ORDER BY NAME ASC";
}
if ($_POST['tipOrder'] == 'DESC') {
$consult = "SELECT NAME
FROM STUDENTS ORDER BY NAME DESC";
}}`
$query = mysql_query($consult);
echo "<table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['Name'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
You can do it but just saving a container (any div, span or even body) as
localStorage.variableName = document.getElementById("id");
And then you can access by using
if(Storage!=="undefined" && localStorage.variableName!=null)
now you can set value as
container.val = localStorage.variableName

Categories