Guys I am very new in Jquery and Json trying, I am trying to create a Dependent Option list with Jquery but it's not working. I am expecting your kind help.
here is my HTML code..
<div class="form-group">
<label for="categoriesId">
Categories</label>
<select class="form-control" id="categoriesId" name="categoriesId">
<option selcted="">Select
Categories</option>
<?php
getCat();
?>
</select>
</div>
and my fetchProductDta.php page code is here
<?php
require_once 'db_connect.php';
if(isset($_POST['cid'])){
$sql = "SELECT product_id, product_name
FROM product WHERE categories_id = '". $cid
."'";
$result = $connect->query($sql);
while($product = $productData->fetch_array()) {
echo "<option value='".$product['product_id']."'>
".$product['product_name']."</option>";
}
}
?>
My Jquery Code is here
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: 'cid' + cid
.done(function (product) {
console.log(product);
product = json.parse(product);
product.forEach(function (products) {
$('#product').appned();
});
});
});
In your jquery you have mistakes , first of all you are getting html response from server as Nigel Ren said.So,to get that you don't need to use json.parse .Also i didn't find any id with name product in your html code.and there is no appned function in jquery .So,make below changes in your code to make it worked.
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: {cid : cid },
success:function(data){
$("#product").html(data);//here response from server will be display in #product
}
});
});
Related
I am new to Ajax and JavaScript
I have a similar problem with my selects that depends on the other select but don't know where it is going wrong?
This is my Controller code- that passes the member_id to the model and it is supposed to return data back to the view selected.
public function getStates() {
$this->load->model('ReferenceModel');
$this->load->model('DailyModel');
$this->load->model('MembersModel');
$this->load->model('FundsModel');
$postData = array('member_id' => $this->request->getPost('member_id'));
$dataa = $this->FundsModel->getStates($postData);
echo json_encode($dataa);
}```
This is my AJAX Request Code
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#member_id').change(function(){
var member_id = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>Historic/getStates',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
// Remove options
$('#id').find('Select Member').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#id').append('<option value="'+dataa['id']+'">'+dataa['fund']+'</option>');
});
}
});
});
});
</script>
Model
public function getStates($postData){
$sql = 'SELECT * FROM vw_funds_summary WHERE member_id =' .$postData['member_id'] ;
$query = $this->db->query($sql);
return $query;
}```
And My HTML Codes
<select id="member_id" name="country" class="form-control">
<option>Select Member</option>
<?php
for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->member_id."'>".$fMembers->row($i)->member_name."</option>";}
?>
</select>
<select class="form-control" id="id">
<option>Select Fund</option>
</select>
What is really wrong with my Code?
I have a view of both the funds and the members, that are giving the results as shown in the attached picture.
Or is there another way to do it without having to use AJAX?
I create a load more button for load more posts from the database but when I add like button for that if one time clicks on load more button and then click on the like button, like.php file runs two times and adds two lines in likes table. if I click 2 times on load more then like.php file runs 3 times and...
I want to know how I should create a loadmore button and like the button to works fine.
this is simple of my codes:
posts.php :
<div id="comnts2"></div>
<button id="btn2" >load more</button><script>
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
ld_comco.php:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" src="pc3/up.png">'.$lik.' Likes</img>';
?>
</span>
<?php }?>
<script type="text/javascript">
$(document).ready(function() {
var uid=<?php echo $uid;?>;
$(document).on("click", ".li_ik1", function() {
var psid = $(this).data('id');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
});
</script>
like.php:
<?php
$id=$_POST['psid'];
$uid=$_POST['uid'];
$Y=mysqli_query($conn,"INSERT INTO `t_plik` (pid,uid) VALUES ('$id','$uid')");
$Q=mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
?>
thanks
I think the problem is, that you bind your like button multiple times globally. Each time you load the content from ld_comco.php you also call $(document).on("click", ".li_ik1", ...) in the $(document).ready block, which means you bind all ".li_ik1" buttons on the entire document (but some of them has already been bind).
I would remove the $(document).ready(...) block from the ld_comco.php and move the logic into the posts.php right before you render your content. A further positive aspect is you have your business logic at one place.
KEEP IN MIND: You get a response of buttons in msg2, thats why you do not need to filter $msg2 anymore. But if you wrap your buttons with further html tags in ld_comco.php, your buttons will be on a deeper level, so you need to use a selector again, like you did with .on("click", ".li_ik1", ...).
posts.php
...
var $msg2 = $(msg2);
// Now you bind only the loaded buttons instead of
// the buttons in the entire document for multiple times
$msg2.on("click", function() {
var $element = $(this);
var psid = $element.data('id');
var uid = $element.data('uid');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
$("#comnts2").append($msg2);
...
In your ld_comco.php you need to add the data-uid="'.$uid.'" and remove the script block. Then your file should look like this:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" data-uid="'.$uid.'" src="pc3/up.png">'.$lik.' Likes</img>';
}
?>
$("#btn2").trigger("click");
this in posts.php means click the #btn2
so after clicking it, you click it again
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#sale_type').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'getTypeDetails.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
});
});
And here is getTypeDetails.php:
<?php
require_once('../include/global.php');
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM purchases WHERE sale_type = :data";
// MySQL
$results = $conn->prepare($query);
$results->bindValue(":data", $data);
$exec = $results->execute();
$res = $results->fetchAll();
$data = array();
$i = 0;
foreach($res as $row){
$data[i] = $row['sale_details'];
$i++;
}
echo json_encode($data);
?>
the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
EDIT
Those are my HTML drop lists:
<label for="sale_type" class="col-lg-1 control-label" style="float:right">النوع</label>
<select id="sale_type" name="sale_type" class="dropdown-header" style="float:right">
<option value="undefined">اختر</option>
<?php
foreach($fetchType as $ft){ ?>
<option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
<?php } ?>
</select>
<label for="sale_details" class="col-lg-1 control-label" style="float:right">الصنف</label>
<select id="sale_details" name="sale_details" class="dropdown-header" style="float:right">
</select>
It should be something like this:
.done(function(data) {
var secondDropdown = $("#second-dropdown");
secondDropdown.empty();
$.each(data, function(index, value) {
secondDropdown.append("<option>" + value + "</option>");
});
return;
}
Replace your js code with my code
<script>
$(document).ready(function() {
$('#sale_type').change(function() {
var formData = { 'selectedValue' : $( "#sale_type option:selected" ).val() };
console.log(formData);
$.ajax({
type: 'POST',
url: 'getTypeDetails.php',
data: formData,
success: function(data){
var obj = jQuery.parseJSON(data);
var secondDropdown = $("#sale_details");
secondDropdown.html('');
for (var prop in obj) {
secondDropdown.append("<option>" + obj[prop] + "</option>");
}
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
});
</script>
and add jquery link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your <head> tag
How I can post all the information in database to it's designated textboxes. I need to post the value on textboxes for example, Pr # data into pr_num textboxes and so on. The problem is my ajax function is only for one textboxes. How I can post it in every textboxes? Any Help will appreciate.
Table Structure
Pr # | Supplier | Receipt # | Receiver |
--------------------------------------------
321-B | Villman | 312312331 | John |
556-B | Dockers | 903232317 | William |
Ajax.php
<?php
if(isset($_POST['pr_code'])) {
$pr_code= $_POST['pr_code'];
$sql = $mysqli->query("SELECT * FROM pr_table WHERE pr='$pr_code'");
while($row = $sql->fetch_assoc())
{
$pr= $row['pr'];
$supplier = $row['supplier'];
$receipt_num= $row['receipt_num'];
$receiver= $row['receiver'];
}
echo $pr;
echo $supplier;
echo $receipt_num;
echo $receiver;
}
?>
index.php
<select id="pr">
<?php ... ?>
</select>
<input id="pr_num">
<input id="supplier">
<input id="receipt">
<input id="receiver">
<script type="text/javascript">
$(document).ready(function()
{
$('input[id="pr"]').change(function()
{
var prjt_code = $("#pr").val();
$.ajax({
type: "POST",
url: "ajax.php",
data :"pr_code="+pr_code,
dataType:'html',
type:'POST',
success:function(data){
$('#pr_num').val(data);
}
});
return false;
});
});
</script>
get the other textbox values also and post like below
var pr_num= $("#pr_num").val();
var supplier= $("#supplier").val();
var receipt= $("#receipt").val();
var receiver= $("#receiver").val();
and in ajax
data :{"pr_code":pr_code,"supplier":supplier,"receipt":receipt_num,"receiver":receiver}
UPdate
in php do like this
echo json_encode(array("pr" => $pr, "supplier" => $supplier,"receipt_num"=>$receipt_num,"receiver"=>$receiver));
in ajax
get values like
var pr=data.pr;
var supplier=data.supplier;
var receipt_num=receipt_num;
var receiver=receiver;
UPDATE2
you have to add another option value,so that the onchange event will fired. If you have only one value then the change event will not be called.So add another option.
and why are you printing echo $option; outside option tag??
<select id="tag">
<option value="">wala</option><?php echo $option; ?>//what are you trying to do here
</select>
Encode the mysql query results into a json array, then in your javascript function, parse the data with JSON.parse, then loop over it and create the elements using the pr id and set the values or dynamically create the form elements from here
<?php
if(isset($_POST['pr_code']))
{
$pr_code= $_POST['pr_code'];
$sql = $mysqli->query("SELECT * FROM pr_table WHERE pr='$pr_code'");
while($row = $sql->fetch_assoc())
{
$results[$i++] = $row;
}
json_encode($results);
}
?>
<input id="pr_num">
<input id="supplier">
<input id="receipt">
<input id="receiver">
<script type="text/javascript">
$(document).ready(function()
{
$('input[id="pr"]').change(function()
{
var prjt_code = $("#pr").val();
$.ajax({
type: "POST",
url: "ajax.php",
data :"pr_code="+pr_code,
dataType:'html',
type:'POST',
success:function(data)
{
var json = JSON.parse(data);
$.each(json, function(item)
{
//assuming the field names are "pr", "supplier", "receipt", "receiver"
var pr_code = json[item].pr;
var supplier = json[item].supplier;
var receipt = jsonitem].receipt;
var receiver = json[item].receivor;
//TODO: display results here
});
$('#pr_num').val(data);
}
});
return false;
});
});
</script>
I've got some JQuery which monitors a form. Basically, for every keyup it will call a php file to search the database.
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2) {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
});
This works fine, however it filters the results in #searchresultdata depending on the query. The only thing is, if nothing is in the form, I want it to load everything - the user should not have to click the form to do this, therefore a .blur would not work.
The PHP file is simply:
if(isset($_GET['keyword'])){}
you should handle a [*] search on your server
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
if (faq_search_input =='') faq_search_input ='*';
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2 || faq_search_input=='*') {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
$("#faq_search_input").trigger('keyup');
});
If you're loading all results initially, then could you not just store this in a JavaScript array and filter the results with JavaScript? This would save you a HTTP request on every key press, which can only be good for speed and resource usage of your site.
EDIT: Sample.
<?php
$sql = "SELECT `title` FROM `your_table`";
$res = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row['title'];
}
echo '<script>var data = ' . json_encode($rows) . ';</script>';
?>
<form method="post" action="">
<fieldset>
<input type="text" name="search" id="faq_search_input" />
</fieldset>
</form>
<script>
// I presume you're using jQuery
var searchInput = $('#faq_search_input');
var searchResults = $('#searchresultdata');
var tmpArray = data;
// add all results to results div
$.each(data, function(key, val) {
searchResults.append('<li>' + val + '</li>');
});
searchInput.attr('placeholder', 'Begin typing to search');
searchInput.keyup(function() {
// hide any <li> in your #searchresultdata that don't match input
});
</script>
I don't know what is in your serverresponse variable, so I can only guess what gets put into the searchresultdata <div>. You'll also need to modify the SQL query to match your table and column names.
Contents of searchdata.php
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%'";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$result=mysql_query($query, $database_connection) or die(mysql_error());
if($result){
if(mysql_affected_rows($database_connection)!=0){
while($row = mysql_fetch_object($result)){
?>
<div class="hold-cont">
<div class="holder">
<div class="image-hold" >
<img class="image-icon" src="<? echo $deviceimg.($row->Image); ?>"/>
</div>
</div>
<div class="device-name devicename-txt"><? echo($row->Manufacturer. ' ' .$row->Model); ?></div>
</div>
<?
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
}else {
echo 'Parameter Missing';
}