Iam getting a value to the text box id using AJAX which is working fine.
<input type='text' id='selectuser_id' />
Javascript
$( "#customers" ).autocomplete({
source: function( request, response ) {
var countrycode = '<?php echo $agencyid; ?>';
$.ajax({
url: "http://localhost:8000/core/country/fetch_customers.php",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#customers').val(ui.item.label); // display the selected text
$('#selectuser_id').val(ui.item.value); // save selected id to input
var customerid = $("#selectuser_id").val(); //equals $q6[$t2] exactly
return false;
}
});
Now how will i pick this value to my PHP
<?php echo $selectuser_id; ?>
I tried many ways but not getting the result. Can someone help me on this?
Since you don't show us where you hold the data of the input field i will give you an example.
Javascript side (since you are also using jQuery) you can get the value of the input field by id like:
let myValue = $( "#selectuser_id" ).val();
Then inside your ajax call you can include your data just like you did for the search:
data: {
search: request.term,
myValue: myValue
}
In your fetch_customers.php file you should be able to access your post data like:
$_POST['myValue'];
Related
I am trying to return multiple values from a php process.
Here is the jQuery function
$.ajax({
url: 'shopping_cart_add.php',
data: 'item_id='+subscription_id+'&item_name='+subscription_name+'&item_price='+subscription_price,
type: 'POST',
dataType: 'json',
success: function(response, statusText) {
var qty = response.item_quantity;
$("#shopping-cart-quantity").html(qty);
}
});
The above seems to work except I can't retrieve the specific field values from the returned JSON.
When I try this...
var qty = response.item_quantity;
$("#shopping-cart-quantity").html(qty);
Nothing happens.
If I change...
$("#shopping-cart-quantity").html(qty);
to
$("#shopping-cart-quantity").html(response);
I get the following...
{ 'account_id': '1', 'item_id' : 'cce3d2a017f6f1870ce8480a32506bed', 'item_name' : 'CE', 'item_quantity' : '1', 'item_price' : '1' }
Please make sure that you are using json_encode() for returning result array
/*** PHP ***/
echo json_encode($resultArr); exit ;
And in AJAX try with eval() to access response text value .
/*** AJAX ***/
var qty = eval(response.item_quantity);
I have this code I'm working on. The drop down in JSP looks like this:
<td>Product</td>
<td><select id="productCode" name="productCode" onchange="getSubProduct();" >
<option value="">-Select-</option>
</select></td>
The Loading of this particular drop down happens from a getProduct() function as follows:
function getProduct(){
var i=0;
$("#productCode")
.find('option')
.remove()
.end()
.append('<option Style="color:red;" value="">loading...</option>')
.val('');
$("#productCode").attr('style', 'color:red;');
$.ajax({
url: 'getProducts',
data: {ppID:$('#ppId').val(),region:$('#regionCode').val(),branch:$('#legalVehicleCode').val()},
type: 'GET',
dataType: 'json',
success: function(data, textStatus, xhr) {
var temp = new Array;
temp = data;
$("#productCode")
.find('option')
.remove()
.end()
.append('<option value="">-Select-</option>')
.val('');
$("#productCode").attr('style', 'color:black;');
for(i=0;i<temp.length; i++){
$("#productCode").append('<option value='+temp[i].productCode+'>'+temp[i].productShortDescription+'</option>');
}
},
error: function(xhr, textStatus, errorThrown) {
//getProduct();
alert(error);
}
});
}
Now my requirement is that, after I click search(shown below), I am supposed to be retaining the Search filter values in the next page(the search results page with a grid). This page has this form too.
<button class="btn btn-primary" type="button" onclick="javascript:buttonClicked1('search');retainSearch();"> Search</button>
Things I have tried:
1. Sending values of those ajax called fields from the controller and attempted to fill it up.
2. Running jquery code
$("#searchForm #productCode").val("${replayMessageBean.productCode}");
Nothing has worked. Kindly help me :(
Try removing double quotes from,
$("#searchForm #productCode").val("${replayMessageBean.productCode}");
OR save the value of ${replayMessageBean.productCode} into some hidden field like,
<input type="hidden" id="prodCode" value="${replayMessageBean.productCode}">
And access this value $('prodCode')
Did you try something more simple and useful as JQuery autocomplete?.
Using autocomplete you can add an ajax call and save the return values to be used in the search after that, even using a dropdown/input. Take a look:
http://jqueryui.com/autocomplete/
Here some code of mine.
function initialize(){
$( "#contactDetails_contactKeyForTenderingParty" ).autocomplete({
source: function(request, response) {
$.ajax({
url: 'contacts/organization/name/'+request.term + ".do",
dataType: "json",
success: function(data) {
response(data);
}
});
},
messages: {
noResults:'',
results: function() {}
},
minLength: 2,
select: function( event, ui ) {
update(ui.item);
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.legalName +"</a>" )
.appendTo( ul );
}
}
function update(governmentContact){
$('#a').val(governmentContact.basicAddress.houseNumber);
$('#b').val(governmentContact.basicAddress.city);
$('#c').val(governmentContact.contact.phoneNumber);
$('#d').val(governmentContact.contact.fax);
$('#e').val(governmentContact.basicAddress.zipCode);
$('#f').val(governmentContact.contact.email);
}
function expandDropdown(){
$("#dropdown").autocomplete('search', 'all');
}
I just sent 2 beans, one with the selected option and another with all the options.Basically 1 is a list and another is a single string. Then i froze the value with that string as "Selected" and the rest i popuated on the list normally. This solved my problem.
I have a one-page structured website. I am trying to use Ajax to update my data on user demand.
I am trying to figure out how to structure my ajax code, so that it will be flexible to my in and outputs = I want to run different function depending on the clicked link, and I want to return the right output to the right div.
HTML links:
<a href="#page-a" class="dbLink" data-variable="funcA">
<a href="#page-b" class="dbLink" data-variable="funcB">
<div id="page-a">
<div id="a-result"></div>
</div>
<div id="page-b">
<div id="b-result"></div>
</div>
JS, ajax (I am passing a data-variable along the link to controle the action):
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
dataType: 'json',
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
});
});
functions.php:
include 'dbconnect.php';
function funcA($mysqli){
$result = $mysqli->query("select * from database");
$row = mysqli_fetch_assoc($result);
echo $row['column'];
}
function funcB($mysqli){
$result = $mysqli->query("select * from database2");
$row = mysqli_fetch_assoc($result);
return $row['column'];
}
if (isset($_POST['action'])) {
$resp = null;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#page-a";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#page-b";
break;
default:
break;
}
echo json_encode($resp);
}
add another data-* variable set to the id of the place you want to output the data. To control the format of the returned data provide the dataType option in the ajax options, and of course make sure the pointed to url actually outputs that type of data. dataType It will tell jQuery how to parse the incoming data.
var theContainer = $(this).attr("data-container");
...
dataType:"json" //or text, or xml etc etc
success: function(data){
//if data is upposed to be json
//and datType is set to json
//data will be an object, same with xml
//process data how you need to
$("#"+theContainer).html(whateverYouHaveDone);
}
If you need to control the target of the returned data within your php script then turn your returned data into json and send the selector for the target to it
$resp = new stdClass;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#someContainer";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#someContainer";
break;
default:
break;
}
echo json_encode($resp);
Then in your ajax success
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
And of course set dataType:"json"
To return just the mysql row, do the same thing as above but in the ajax success resp.data will be an object. So just access the properties of resp.data with the column names of the row
success: function(resp){
if(resp.data){
//if say you have a column named "username"
var username = resp.data.username;
}
}
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var target = $(this).attr('href');
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(data){
$(target).html(data);
}
});
});
there are many ways to do this.
I see you have understood the custom data-* attributes. I would add one more attribute: data-target=""
<a href="#page-a" class="dbLink" data-variable="funcA" data-target="a-result">
<a href="#page-b" class="dbLink" data-variable="funcB" data-target="b-result">
<div id="page-a">
<div class="a-result"></div>
</div>
<div id="page-b">
<div class="b-result"></div>
</div>
Then inside your JQuery, you do like you do with your data-variable, only that you add the new data-* attribute:
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var theTarget = $( this ).attr("data-target");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(){
/* Here you have to change the data[] to match the JSON return from your PHP-script. You can of course do it without JSON, but I would use http://www.php.net/manual/en/function.json-encode.php on an array from PHP.*/
$("input[class="+ theTarget +"]").html( data["foo"][0]["bar"] );
}
});
});
If you want to play with a real life example, I made this fiddle for another guy on stack overflow a while back: http://jsfiddle.net/Olavxxx/Mu66h/
Put a number in the left box (like 5006), it's postal codes. The target then is the postal adress in the right input box. The concept is very much the same as you are after, with data-targets.
I have a 5x5 grid of div boxes (25 of them) and I am using jQuery UI to register when I drop a item in it. It will receive the title of the box it was dropped in and the name of the item, that part works.
I want to pass the title and name to PHP without refreshing the page (because then the items will reset). I get a "success!" but it seems like it doesn't pass the data.
index.php
<script>
$(function() {
$( "li img" ).draggable({
snap: ".grid",
start: function (event, ui ) {
item = $(this).attr('title');
}
});
$( "li .grid" ).droppable({
drop: function( event, ui ) {
box = $(this).attr('title');
$.ajax({
type: "POST",
url: 'index.php',
data: { box : 'box' },
success: function(data){
alert("success!");
}
});
}
});
});
</script>
sessions.php
<?php
session_start();
if(isset($_POST['box']))
{
// store session data
$_SESSION['box'] = $_POST['box'];
}
//retrieve session data
echo $_SESSION[box];
?>
How do I pass the title and name to PHP without refreshing the page?
Try to change the url and your data from this:
url: 'index.php',
data: { box : 'box' }
to this:
url: 'sessions.php',
data: { box : box }
Given that you're doing this...
box = $(this).attr('title');
I assume you want to pass that variable to the server. However, you're just passing the literal string "box", not the variable box.
In your code, you've written this...
data: { box : 'box' },
which needs to be this, to pass the value in box:
data: { box : box },
As an aside, you've created a global variable box. Instead of box = $(this).attr('title');, you should use var box = $(this).attr('title'); to create a variable local to the function.
I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/