Set initial value of dropdown output constructed with ajax - javascript

I have the following dropdown list which changes the output of <div id="item"></div> with ajax when select option is changed. I'm not using select2.
<?php
$biqsQuery = "SELECT biq.biqid, biq.name FROM biq";
$biqs = $db->query($biqsQuery);
?>
<select name="itemselector" id="itemselect">
<?php foreach ($biqs ->fetchAll() as $biq): ?>
<option value="<?php echo $biq['biqid']);?>">
<?php echo e($biq['name']);?>
</option>
<?php endforeach; ?>
</select>
<div id="item"></div>
PHP File:
if(isset($_GET['itemselector'])){
$biqQuery = "SELECT biq.biqid, biq.name, biq.img
FROM biq
WHERE biq.biqid= :biqid ";
$biq= $db ->prepare($biqQuery);
$biq->execute(['biqid' => $_GET['itemselector']]);
$selectedBiq=$biq->fetch(PDO::FETCH_ASSOC);
echo '<img src="'. $selectedBiq['img']. '">';
}
Javascript File:
$('#itemselect').on('change',function(){
var self = $(this);
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : self.val()},
success: function(data){
$('#item').html(data);
}
});
});
It's currently succesfully changing the output, no problem on that part.
But when the page is first loaded, it shows the first value of the table on the dropdown menu, however it doesnt output the image of that first value into <div>.
What i need is; when the page is loaded i need the first entry in the database to be outputted into the <div id="item"></div> automatically.
Any help is appreciated, thanks in advance.

you could write on body load event to accomplish this. please correct if any type mistake will there but this will help you to get it rid
$(document).ready(function(){
var first = $("#itemselect option:first").val();
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : first},
success: function(data){
$('#item').html(data);
}
});
});

Related

Jquery is not spotting that a form select has changed

I have a db table of all postcodes in the UK and want to create functionality to filter down into local locations to decrease load times of the page. The issue I am having is that I am a bit out of practice with JQuery and there seems to be an issue where selecting the country is not being picked up by the JQuery.
Here is the HTML/PHP for the select:
<label for="country_select">
Select Country
</label>
<select id="country_select" name="country_select" class="form-control search-select">
<option value=""> </option>
<?PHP
if ($result = mysqli_query($link, "SELECT DISTINCT(`country`) as countrylist FROM `postcodes`")) {
while($member = mysqli_fetch_assoc($result)) {
$country=$member['countrylist'];
?>
<option value="<?PHP echo $country; ?>"><?PHP echo $country; ?></option>
<?PHP
}
}
?>
</select>
Here is the PHP to check for the post and create a mysql statment to then create another drop down for cities. I am wondering if the issue lies here, i added an echo to see if it appears when the option has been changed, but nothing is appearing.
<?PHP
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo $statement;
}
?>
And here is the jquery:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
}
}
});
});
});
I am unsure where I am going wrong as it has been a while since I have coded. I have looked around at others' issues with no luck. Any help would be greatly appreciated.
The issue was the jquery. The code should be the following:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
alert(data);
}
});
});
});`

jquery ajax post to self not working

i am taking a value from the dropdown using jquery on change , i am using ajax to post to self, but i am not able to echo the posted variable.
<form>
<label>Select Doctor:</label>
<select class="docdrop">
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id}, //using 'd_id1' did not make a change
success: function(){
alert(d_Id]);
}
});
}
});
});
</script>
//php code in same page
<?php
if(isset($_POST['d_id1']))
$d_Id = $_POST['d_id1'];
?>
<p><?php echo $d_Id; ?></p>
i get the alert on success but , i am unable to echo the posted variable. i dont want to use serialize() or post the entire form. just d_Id whic i obtain in jquery
If you want you can do this without using jQuery in this way :
<?php
$d_id1 ="";
if(isset($_POST['d_id1'])){
$d_Id = $_POST['d_id1'];
echo $d_Id;
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<form>
<label>Select Doctor:</label>
<select class="docdrop" >
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id},
success: function(data){
d_id1 = data;
document.getElementById('name').innerHTML = d_id1;
console.log(data);
}
});
}
});
});
</script>
<p id ="name"><?php echo $d_id1;?></p>
</body>
</html>
php code execute one time on page load, so that time your variables $d_Id and $d_Id1 are not created, so it is not display any value.
also ajax execute without page refresh and all code in side success executed without any error.
success: function(data){
alert(data);
}
You will alert the data send from backend i.e. echoed by your php part, which in your case will be the result of <p><?php echo $d_Id; ?></p>, if you just need your $d_id selected without the paragraph tags change your code to <?php echo $d_Id; ?>. Of course you may prefer to use JSON as output of your backend and then parse it in the success callback with $.parseJSON(data) per instance or use data type 'json' in your AJAX reques.

Making AJAX show a 'result data' in correct div witoud refreshing

I'm currently into developing simple 'one score' votting system and I'm facing the problem: though php script workd fine I cant get AJAX updating the answer div without reloading page. I've tried different methods, some do nothing, other reload page, for example, I've tried adding (return: false) after AJAX or PreventDefault in it. Here is html and php index page:
<body>
<div align="center">
<h3>Voting with jQuery, Ajax and PHP</h3>
<?php
include('config.php');
$sql=mysqli_query($bd, "SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$total_score=$row['total_score'];
?>
<div id="main">
<div class="box1">
<img class='image'src="img/thumbsup.png">
<span class='this'><?php echo $total_score; ?></span><div class='tr'></div>
<img class='image' src="img/icon-down.png"></div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php
}
?>
</div>
</body>
And here is my working up_vote.php (down_vote.php is almost same, so I wont add it)
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysqli_query($bd,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysqli_num_rows($ip_sql);
$sql = "update Messages set total_score=total_score+1 where mes_id='$id'";
mysqli_query($bd, $sql);
$sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";
mysqli_query($bd, $sql_in);
$count=mysqli_num_rows($ip_sql);
}
?>
And finally, the complete JQUERY - AJAX script (this's my problem - need to show the results in (div class = 'this') without refreshing the page):
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success:function(data){
$(".this").append(data);
},
complete: function() {alert('complete');};
});} else
{
$(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle" style="height: 10px;width:10px;">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false
}).done(function ( data ) {
$('.this').append(data);
});
}
return false;
});
});
I have spent whole my day and I know the solution is obvious, Im just really new in this all and so I would appreciate any helpful response. Thanks in advance.
I have added this code to up_vote.php at the buttom:
$result=mysqli_query($bd, "select total_score from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result);
$up_value=$row['total_score'];
echo $up_value;
Thanks to all of you guyz!!! It works now! The problem was that php script didnt return anything!!! As I though - obviouse))) THANKS!
HAve NEW PROBLEM NOW - WHEN I CLICK ON ICONS IT UPDATES ALL OF THEM!! IN EVERY DIV! I VOTE FOR ONE THING - AND IT ADDS VOTES FOR EACH ONE!! whats wrong with that?

Ajax with PHP same page not working

I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work

Single Div refresh with jquery Ajax and PHP

Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}

Categories