how to post the database value to next page using ajax - javascript

i am trying to post the database retrieved value to next page using ajax.i tried but it not posting, can any one guide me how to do it
php
connected with database
$sql = "SELECT * FROM `billingdatainputandexport` WHERE id='1'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
//print $sql;
$billingmonth=$rows['billingmonth'];
i want to pass this billing month to selectsuppliercostprice.php.
javascript
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='$billingmonth';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
selectsuppliercostprice.php.
$billingmonth=$_POST['billingmonth'];

Can you try this,
PHP
$billingmonth=$rows['billingmonth'];
echo '<input type="hidden" id="billingmonth" name="billingmonth" value="'.$billingmonth.'">'; // added hidden input
Javascript:
$("#supplier").on("change", function() {
var billingmonth= $('#billingmonth').val();
...
});

The post variable is $_POST not $POST so ... that should be right:
$billingmonth = $_POST['billingmonth'];
Also in Javascript you have to print the billingmonth variable. Javascript can't handle php-variables:
var billingmonth='$billingmonth';
to
var billingmonth='<?php echo $billingmonth; ?>';

Here is the latest code : u missed i guess the php tag inside ur script tag now try :)
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='<?php echo $billingmonth ?>';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});

make hidden field and store your value in that and read that value in javascaript and pass it with ajax
<input type="hidden" name="some_name" value="<?php echo $billingmonth?>" id="some_name"/>
javascript code
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=document.getElementById('billingmonth').value;
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
if you don't want to use it anyother place than
var billingmonth= '<?php echo $billingmonth?>';

Just Try.
Store $billingmonth value into any hidden input.
<input type="hidden" name="billing_month" id="billing_month" value="<?php echo $billingmonth; ?>"/>
Retrieve $billingmonth value in jQuery ready function using Hidden input id.
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=$("#billing_month").val();
var supplier = $("#supplier").val();
var mcc = $("#mcc").val();
var mnc =$("#mnc").val();
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});

Related

Getting updated input value for further update in jQuery

I use an Ajax form (with JQuery Validation Plugin) on my site. It works except for the following problem: if I enter something in a text field and then click on the send button, the value is updated. With each next update, however, the old value is always used. I already understand that I may have to work with .on or .keyup, but I understand how to properly integrate it into the code, after the click or outside ...
Update:
I have several fields in the form. Here is simplified code. I also noticed that after the first update of the form, no fields can be updated with newly entered values. All values remain old.
HTML:
<form id="org-684" class="org">
<input class="org-name" type="text" name="name" value="" required>
<button type="submit" class="updateOrg">Update</button>
</form>
JS:
$(document).ready(function(){
$('.updateOrg').click(function() {
var id = $(this).closest(".org").attr("id");
id = id.split('-');
id = id[1];
var org_id_attr = "#org-"+id;
var org_name = $(org_id_attr).find(".org-name").val();
$(org_id_attr).validate({
submitHandler: function() {
$.ajax({
type: "POST",
url: "update.php",
data: ({
id: id,
org_name: org_name
}),
success: function(response){
var result = jQuery.parseJSON(response);
$(org_id_attr).find(".org-name").val(result.name);
},
error: function() {
},
cache: false
});
return false;
}
});
});
})
PHP:
<?php
$orgId = $_POST['id'];
$orgName = $_POST['org_name'];
$select = "
SELECT
name
FROM
org
WHERE
id = $orgId
";
$result = $mysqli->query($select);
$row = $result->fetch_row();
$res = array(
'name' => $row[0]
);
echo json_encode($res);
I solved the problem. You just have to put the variables from the form behind the "SubmitHandler".
$(org_id_attr).validate({
submitHandler: function() {
var org_name = $(org_id_attr).find(".org-name").val();
$.ajax({
type: "POST",

autocomplete in codeigniter not displaying anything

Hy, i am making an autocomplete search field in codeigniter,I tried to do autocomplete in codeignter using the below code .But it is not working for me.Not displaying anything in the autocomplete text field.Can anyone find the problem
success function of data displaying as undefined
Here is my view:
View
<script >
$(document).ready(function() {
$("#trackerid").change(function(){
var var_locoid= $("#trackerid option:selected").val();
alert(var_locoid);
$( "#deliverylocation" ).autocomplete({
source: function(request, response) {
var auto_data= $("#deliverylocation").val();
alert(auto_data);
//alert(var_locoid);
$.ajax({
url:"http://localhost/testcontroller/test/lookup",
type:"POST",
datatype:'json',
data:{'var_locoid' :var_locoid,'auto_data':auto_data},
success: function(data){
response(data);
alert(data);
}
});
},
minLength: 1
});
});});
</script>
<input type="text" name="deliverylocation" id="deliverylocation" placeholder="Enter your area " >
Controller
function lookup()
{
$citys = $this->input->post('var_locoid');
$auto_text = $this->input->post('auto_data');
//var_dump($citys);
//$data['response'] = 'false';
$place = $this->Demo_model->load_places($citys,array('keyword' => $auto_text));
$json_array = array();
foreach ($place as $row){
array_push($json_array, $row->locationtext);
}
//echo json_encode($place);
echo json_encode($json_array);
}
Model
function load_places($citys,$auto_text)
{
//$this->db->select('locationtext');
$this->db->select('locationtext');
$this->db->like('locationtext', $auto_text);
$this->db->from('tbl_location');
$array = array('cityautocode' => $citys);
$this->db->where($array);
//$this->db->->where('cityautcode', $place);
$query= $this->db->get();
//echo $this->db->last_query();
return $query->result();
}
I am using an autocomplete pattern from https://www.devbridge.com/sourcery/components/jquery-autocomplete/
Here is my controller:
$arrayData = $this->CRUD_model->getSelect("id as data, name as value, purchase_price","articles")->result_array();
echo json_encode($arrayData);
And my views:
$(document).ready(function(){
// $("body").addClass("sidebar-collapse");
var dataArticles = $.parseJSON(getArticles());
$("input[name='articles_name']").devbridgeAutocomplete({
lookup: dataArticles,
onSelect: function(suggestion) {
$("input[name='articles_id']").val(suggestion.data);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Barang tidak ditemukan',
noCache: true,
minChars: 2,
})
})
function getArticles(){
result = null;
$.ajax({url: '<?= base_url();?>panel/purchasing/request/getArticles',type: 'get',dataType: 'html',async: false,success: function(data) {result = data;} });
return result;
}
For this example I use lookup, so all autocomplete values loaded when I open the page, note that id must be named "data" and label must be named "value".

got all values of input box are same

I am creating a update form. In this when i click on update button i got same values every time that's why update functionality is not working. I already tried to get values using ID attribute of input box but not working. I am new in this field and this task take lots of time. Thanks in advance.
$(document).ready(function() {
$(".update").click(function() {
var id = $(this).data('id');
var uname = $(".name1").val();
var email = $(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});
for($i = 0; $i < $num_of_records; $i++)
{
echo "<tr><td>";
echo "<input type='text' value=".mysql_result($all_records, $i,"name")." class='name1' id='name' placeholder='Name'><input type='text' value=".mysql_result($all_records, $i,"email")." class='email1' id='email' placeholder='Email'><input type='submit' data-id=".mysql_result($all_records, $i,"id")." class='delete' name='delete' id='delete' value='Delete'><input type='submit' data-id=".mysql_result($all_records, $i,"id")." class='update' name='update' id='update' value='Update'>";echo "</td></tr>";
}
The Javascript needs to select the inputs from the same row as the button that was clicked.
$(document).ready(function() {
$(".update").click(function() {
var row = $(this).closest("tr");
var id = $(this).data('id');
var uname = row.find(".name1").val();
var email = row.find(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});
A better solution do it like this,
I am giving you a small example as your code is bit tidy.
<?php
foreach($answers as $a)
{
?>
<a href="javascript:void(0)" data-answerid="<?php echo $a->id;?>" class="upvote_link" />Edit</a>
<?php
}
?>
jquery Onclick to get clicked value
$('.upvote_link').click(function(){
var unique_id = $(this).data('answerid');
console.log(unique_id);
});
Shoot a comment if you have any issue executing this.You should always write unique id in html elements. Javascript should be knowing that particular link is been clicked.
That's because your ids are same, so jQuery stops searching as soon as it matches the first element with that ID.
To prevent this from happening, use the .siblings() function, like so:
$(document).ready(function() {
$(".update").click(function() {
var id = $(this).data('id');
var uname = $(this).siblings(".name1").val();
var email = $(this).siblings(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});

How can I use a GET from my php file, to get a variable that I declared in my .js file?

I made some variables that contain the answers that are selected in my dropdown menu's. Now I want to use those variables in my .php file so i can make a query of them. But I can't figure out what I'm doing wrong, so here is my code.
This my main.js file:
$("#slctTable").change(function(){
var table = document.getElementById("slctTable");
var tableSelected = table.value;
console.log(tableSelected);
});
$("#slctField").change(function(){
var field = document.getElementById("slctField");
var fieldSelected = field.value;
console.log(fieldSelected);
});
$("#slctAttribute").change(function(){
var attribute = document.getElementById("slctAttribute");
var attributeSelected = attribute.value;
console.log(attributeSelected);
});
And this my getData.php file:
<?php
include "connect.php";
$test1 = $_GET['tableSelected'];
$test2 = $_GET['fieldSelected'];
$test3 = $_GET['attributeSelected'];
echo ($test1);
echo ($test2);
echo ($test3);
?>
You will have to redirect the user to a page with the variables in the URL. PHP runs a script on the server then sends the output of that script to the client. JavaScript only runs on the client. You can do this:
$('#slctTable').change(function(){
var table = document.getElementById("slctTable");
var tableSelected = table.value;
console.log(tableSelected);
window.location.href = "?tableSelected=" + tableSelected
});
Alternatively you can make an Ajax request to make a call to the server without refreshing the page. You can use this:
$('#slctTable, #slctField, #slctAttribute').change(function ()
{
var tableSelected = document.getElementById("slctTable").value;
var fieldSelected = document.getElementById("slctField").value;
var attributeSelected = document.getElementById("slctAttribute").value;
$.ajax({
"url": "getData.php",
"type": "GET",
"data": {
tableSelected: tableSelected,
fieldSelected: fieldSelected,
attributeSelected: attributeSelected
}
})
.done(function (response)
{
console.log(response);
});
});
Using Jquery, you could use Ajax to accomplish that:
$("#slctTable").change(function(){
var table = document.getElementById("slctTable");
var tableSelected = table.value;
console.log(tableSelected);
});
$("#slctField").change(function(){
var field = document.getElementById("slctField");
var fieldSelected = field.value;
console.log(fieldSelected);
});
$("#slctAttribute").change(function(){
var tableSelected = slctTable.val();
var fieldSelected= slctField.val();
var attributeSelected = $(this).val();
$.get( "getData.php?tableSelected="+tableSelected+"&fieldSelected="+fieldSelected+"&attributeSelected="+attributeSelected )
.fail(function(data){
alert('Ajax Call Error');
})
.done(function(){
alert('Success');
});
});
});

How to do the ajax + json using zf2?

i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)

Categories

Resources