Single Div refresh with jquery Ajax and PHP - javascript

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
}

Related

How to fetch mutiple values on select option and display in input type using ajax?

I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research

how to retrieve ajax data in "multiple" drop box?

I have 2 multiple select drop box.. form one I want to inflate the other multiple select drop box.. can anyone help me with this?
When I get result from the jQuery or ajax i want that result to display in 2nd number multiple select drop box...
this is my ajax..
function demo1() {
var emp_id = document.getElementById("employeeName").value;
alert(emp_id);
var datastring = "emp_id=" + emp_id;
//alert (emp_id);
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "text",
//async: false,
success: function (data) {
//$("#clname").append(data);
$('#clname').html(data);
//document.getElementById("clname").innerHTML=data;
}
});
}
This are 2 multiple drop box..
<label>Select Employee </label>
<select multiple="multiple" class="w300" name="employeeName[]" id="employeeName" >
<?php $result = $conn->query("SELECT id,first_name,last_name,employee_id FROM employees");
while ($row = $result->fetch_assoc()){ ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['id']; ?><?php echo $row['first_name']; ?>
<?php echo $row['last_name'] ?></option>
<?php } ?>
<!--<?php echo $option;?>-->
<!--<?php echo $option2;?>-->
</select>
</br>
<label>Select Client</label>
<select multiple="multiple" class="w300" name="clname[]" id="clname">
<!--<?php echo $c;?>-->
</select>
.html() will set the innerHTML content of a DOM element, you can't do that on a <select>. There are two ways to solve it:
1) Quick & dirty: replace HTML
Make your search_emp.php also return the HTML code for the <select>, like this:
echo '<select multiple="multiple" class="w300" name="clname[]" id="clname">';
while($row = mysqli_fetch_assoc($ress)) {
echo '<option value="'.$row['gn_id'].'">'.$row['gamename'].'</option>';
}
echo '</select>';
Then you can use jQuery.replaceWith() to replace the whole DOM element:
$('#clname').replaceWith(data);
2) Much nicer: Build DOM from JSON
Instead of returning HTML code, your search_emp.php should return JSON, something like
[
{
"gn_id": "123",
"gamename": "superduper client"
},
{
"gn_id": "234",
"gamename": "another client"
}
]
You can easily do this by passing the client array to PHP's json_encode() and add a JSON content type header (Note that you will have to change the dataType attribute of $.ajax to "json" or you could use the shortcut function $.json():
// identify the content as JSON
header('Content-Type: application/json');
// put your MySQL query here.
// if errors occur, send a HTTP 500 header and return a useful error message as JSON
// collect results in an array
$rows = array();
while($row = mysqli_fetch_assoc($ress)) {
$rows[] = $row;
}
// return the results as a JSON list
echo json_encode($rows);
Before you make the AJAX call, you would want to remove all existing options from the select. In the success function of the AJAX call, you can loop through the results and append them to the select:
// reset the select options
$('#clname').empty();
// make the ajax call
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "json",
success: function (data) {
// build the options from the JSON data
for (let client of data) {
$('#clname').append('<option value="' + client.gn_id + '">' + client.gamename + '</option>');
}
},
// optional, but good to have: error handling
error: function (data) {
alert("An error occurred:\n" + data.error)
}
});
jsfiddle
Note: let client of data only works in modern browsers (ES2015 compatible). If you want to support older browsers, do an old-fashioned for (len=data.length, i=0; i<len; ++i) loop. Or use jQuery.each() (although this might be slower)

Set initial value of dropdown output constructed with ajax

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);
}
});
});

Wordpress plugin ajax returns 0

I'm trying to send AJAX data to my wordpress table but all I can get from my PHP is a 0. Its on the admin side. Can anyone help me?
Also all of this code is inside my plugin-admin.php file inside my plugin folder.
<?php
if ( ! defined( 'ABSPATH' ) || ! current_user_can( 'manage_options' ) ) exit;
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<script>
jQuery(document).ready(function($) {
var spostsarray = new Array();
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: "POST",
action: "featured_submit_action",
data: {"posts": spostsarray},
success: function(data){
console.log(data);
}
});
});
});
</script>
I've condensed it a bit but the general idea is that I can grab all the recent posts and the user can select which ones they want to feature, send that to the PHP method and edit the table with it.
The problem is with my AJAX callback I only ever return 0 and not the data sent from the javascript.
SOLVED:
After some help from Rohil_PHPBeginner I figured it out. The reason it didn't work is that I was executing the code from the menu page at at that point it was too late to add a hook. Here is the page I used to solve it:
AJAX in WP Plugin returns 0 always
Below code worked perfectly fine for me:
<?php
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<?php
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
add_action( 'wp_ajax_nopriv_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<script>
jQuery(document).ready(function($) {
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
});
});
</script>
You don't need to pass the AJAX url in that way because when I used your code, it is showing me with PHP. WordPress provides a default url for AJAX so you can use that( ajaxurl which I used in below code).
Other than that You have not added code for no-privilege user (if it is going to use only for privileged user then it is okay otherwise you need to add code for that).
WordPress returns 0 when an ajax call doesn't find a valid callback function (though the 0 could be return from many other things).
WordPress looks for callbacks matching wp_ajax_{callback} when a user is logged in and wp_ajax_nopriv_{callback} when the user is logged out. {callback} is populated with the POST'd value of the "action" hidden input. Note that you're not passing the action into your AJAX call. You should change:
data: {"posts": spostsarray},
to
data: data
Since you're not going to match a callback function without passing in action, WordPress is returning 0

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

Categories