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>
Related
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
}
});
});
Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>
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
I use the following code to output a table with FAQ.
// get faq
global $wpdb;
$faq = $wpdb->get_results("SELECT ID, q, a, cat, quality, active FROM ce_faq");
foreach ($faq as $i) {
echo
'<div>
<a id="'.$i->ID.'" class="question" href="#">'.$i->q.'</a>
</div>
<div id="a'.$i->ID.'" class="answer">
<p>'.$i->a.'</p>
<form method="POST" id="form'.$i->ID.'">
<input type="hidden" value="'.$i->ID.'" name="faq_id"></input>
<input type="hidden" name="action" value="ce_faq_quality"/>'
.wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ).
'<p><b> Was this answer usefull? <input type="radio" name="quality" value="1" class="quality_radio"> yes </input><input type="radio" name="quality" value="-1" class="quality_radio"> No </input> </b></p>
</form>
</div>';
}
echo '<div id="feedback">feedback</div>';
I use jQuery().slidetoggle to toggle the answers when somebody clicks on the question. I want to enable end-users to give feedback on the questions with a simple yes or no question. The form should be submitted when one of the radio buttons is selected. the trigger jQuery('.quality_radio').click is working and also the formid is correctly fetched.
problem: The function ce_faq_quality(); is unfortunately not responding, when i use console.log(qu) i get for example 'faq_id=1&action=ce_faq_quality&name_of_nonce_field=7dd1d930af&_wp_http_referer=%2Ffaq%2F&quality=1', which seems to be correct to me. I also get the alert 'this is working'. The php handler doesn't seem to work however. the div feedback turns 0 (instead of 'success php function') and also the query isn't performed (while I know it works for 120%). I am at a loss here...
solved: the handler wasn't accessible from the page i was working on...
jQuery('.question').click(
function(){
var id = this.id;
jQuery('#a'+id).slideToggle(350);
});
jQuery('.quality_radio').click(
function(){
var formid = jQuery(this).closest('form').attr('id');
var formid = '#'+formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formid){
var qu = jQuery(formid).serialize();
console.log(qu);
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success:function(data){
jQuery("#feedback").html(data);
alert('this is working');
}
});
return false;
}
This is the php function i use to process the form.
add_action('wp_ajax_ce_faq_quality', 'ce_faq_quality');
add_action('wp_ajax_nopriv_ce_faq_quality', 'ce_faq_quality');
function ce_faq_quality(){
$quality = 1; //$_POST['quality'];
$faq_id = 1; //$_POST['faq_id'];
global $wpdb;
$wpdb->query($wpdb->prepare("UPDATE `ce_faq` SET `quality`= `quality` + $quality WHERE id = $faq_id"));
echo 'succes php function ';
die();
}
Your formid variable falls out of scope in the ajaxSubmit function. You should instead try:
jQuery('.quality_radio').click(
function() {
var formid = jQuery(this).closest('form').attr('id')
var formid = '#' + formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formId) {
var qu = jQuery(formid).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success: function(data) {
jQuery("#feedback").html(data);
}
});
return false;
}
So that you pass the formid to the ajaxSubmit function.
I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});