So here I have two dropdowns:
<select id="CountryId">
<option value="16">UK</option>
<option value="17">Germany</option>
<option value="18">Italy</option>
<option value="19">Spain</option>
</select>
<select id="CityId"> </select>
And in the app I have a php function which returns a list of cities by the country's ID:
{"63":"Rome","65":"Palermo","72":"Torino","73":"Milan"}
What I try to achieve is onChange of the first dropdown to take the country's ID and populate the second list with the returned cities.
I try to achieve it with this AJAX call, and tried to debug it, but nothing seems to work. The var data is being picked up, but nothing else happens. Here is the snippet:
$('#CountryId').change(function(){
var data = $('#EventCustomerId option:selected').val();
$.ajax({
type:'POST',
async: true,
cache: false,
url: <?php echo Router::url(array('controller'=>'projects','action'=>'getbycustomer')) ?>,
success: function(response) {
jQuery('#CityId').html(response);
},
data: data
});
return false;
})
I am not quite secure about the way of filling the second dropdown with the response. The response is returned in plain HTML in JSON.
Any help is much much appreciated.
have you tried with putting async to false?
$('#CountryId').change(function(){
var data = $('#EventCustomerId option:selected').val();
$.ajax({
type:'POST',
async: false,
cache: false,
url: <?php echo Router::url(array('controller'=>'projects','action'=>'getbycustomer')) ?>,
success: function(response) {
jQuery('#CityId').html(response);
},
data: data
});
});
can you post your response here if the call should work now
Related
I have an AJAX request going to my PHP file to pull data from the database that pertains to the users. I want to autofill the form inputs. I was able to fill most of the inputs, but the HTML "select" option is really stumping me. Does anyone know how to autoselect the value in the database?
HTML
<select class="gender-reg" name="gender-reg">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="optout">Rather Not Say</option>
</select>
AJAX REQUEST
$(function () {
$.ajax({
type: 'GET',
url: 'http://localhost:8090/HELPERSITE/src/php/session.php',
dataType: 'json',
data: '',
success: function (response) {
console.log(response);
$(".username-reg").attr("value", (response['username']));
$(".pwd-reg").attr("value", (response['password']));
$(".email-reg").attr("value", (response['email']));
$(".acct-type").text(response['type']);
$(".fname-reg").attr("value", (response['fname']));
$(".lname-reg").attr("value", (response['lname']));
$(".gender-reg").attr("value", (response['gender']));
$(".street-reg").attr("value", (response['street']));
}
})
});
You can simply use .val():
$(".gender-reg").val(response['gender']);
This is my ajax code
<script type="text/javascript">
$('#right_make').change(function() {
var make = document.getElementById('right_make').value;
alert(make);
$.ajax({
url: 'get.php',
async: true,
cache: false,
data: {make:make},
dataType: "html",
type:'post',
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', result);
}
});
});
</script>
I am getting data in form of html reverted from backend php ,I want to append this data in select tag ,given below
<select name="model" id="right_model" class="custom-select c_model right_model">
<option value="">Model</option>
</select>
I tried the above thing but it is producing gaps between the options ,
this is what I am appending from backend
<?php
include 'includes/config.php';
include 'includes/database.php';
$make=$_POST['make'];
$stmt=$db->prepare("SELECT distinct `model` FROM `car` WHERE make=?");
$stmt->bind_param("s",$make);
$stmt->execute();
$stmt->bind_result($model);
while ($stmt->fetch()) {
echo "<option>".$model."<option>";
}
?>
Any idea ow to do that?
Generally, if you want to communicate some data with a php server, you may use JSON.
JSON keeps a very sample solution to traduce javascript or php to a very sample string. After, you can traduce JSON to php, Javascript or what else...
You may do this because php do not understand javascript and javascript do not understand php, of course.
When you pass data with your ajax, you may do like this:
$.ajax({
url: 'get.php',
async: true,
cache: false,
data: {make:JSON.stringify (make)}, // Traduce to simply string.
dataType: "html",
type:'post',
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', result);
}
});
Then, when you get the data in your php, you may do like this:
$make=json_decode ($_POST['make']); // Traduce to php.
When you use echo:
echo json_encode ("<option>".$model."<option>");
And finally in your javascript:
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', JSON.parse (result));
}
Consult the documentation.
Here is where I select my value
Company Name<br />
<select id="company" name="selected">
<option value="">Value 1</option>
<option value="">Value 1</option>
</select>
When I click this one I want it to have a modal like or facebox
<a rel="facebox" id="getitems" href="ordersupply.php" >Order Item</a>
My ajax code here note: when I alert this one it gives the value but cant find it in the ordersupply page
$("#getitems").click(function(){
var x = document.getElementById("company").value;
alert(x);
$.ajax({
url: "ordersupply.php",
type: "POST",
data: {"selected": x},
success: function(response){
console.log(response);
}
});
});
I'll just make a simple php where I can echo in my page the selected value can anyone help me with this one :) It will be very much appreciated
<?php
if(isset($_POST['selected']))
{
$value = $_POST['selected'];
echo $value;
}
?>
Try this :
$.ajax({
url: "ordersupply.php",
type: "POST",
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
data: {"selected": x},
success: function(response){
console.log(response);
}
});
Check in browser (f12) for firefox and chrome in the network section what response you get. There is a good chance for 404 not found error.
I want to update TextBox value on basis of selectChange
HTML:
<select name="abc" id="def">
<option value="1">1st Record</option>
<option value="2">2nd Record</option>
<option value="3">3rd Record</option>
</select>
<input value="" name="final_value" id="final_value" />
JS:
$("#selectboxid").change(function() {
$.ajax({ url: "test.php", data:"value="+$("#def").val() , success: function(){
$("#final_value").val(data);
}});
});
PHP:
<?php
function abc($data){
// Database operations
echo json_encode($response);
}
abc($_GET);
?>
With this approach value is updating very nicely But i have below points:
above approach prints values and one can see in Network Tab. Is it a nice way to do it?
I also tried using return $response in PHP function but then response is null and console.log(data) in ajax shows null array.
So, how to update Input value after Ajax without echoing. I do not want that user shall see any type of response even in Network Tab.
I have seen various websites which does the same and not showing any values in Network tab.
** Is there any different approach to do this?
You can alternatively try like this
All HTTP requests can possible to watch on their own network. You can restrict this
$(document).ready(function(){
var params = {};
params['value'] = $("#def").val();
$.post('test.php', params, function(response){
console.log(response);
alert(response);
});
});
I've not tested this, but immediatly I've spotted a couple of things:
$("#selectboxid").change(function() {
// .val is a function
$.ajax({ url: "test.php", data:"value"+$("def").val() , success: function(data) { //Your success callback needs to take an argument
//data will be either a string or a JSON object, so depending on what you want from it, you'll probably not be able to just pass it to the val() function
$("#final_value").val(data);
}});
});
Not 100% complete I'm sure, but hopefully will give you a good starting point
It should be like this
$("#selectboxid").change(function() {
$.ajax({
url: "test.php",
data:{
"value": $("def").val()
},
success: function(){
$("#final_value").val(data);
}
});
});
I have a problem with submiting my "form" with json. Its not form in traditional way, i will post a code now:
$('#select').on('change', function() {
document.getElementById("info").setAttribute("data-info", this.value);
})
$('#info').on('click', function() {
var id = $(this).data('info');
add(info);
});
function add(info) {
$.ajax({
type: 'get',
cache: false,
contentType: content_type,
beforeSend: function(xhr) {xhr.overrideMimeType(content_type);},
data: {'action': 'info_add', 'info': info },
url: sitepath + 'info/all',
success: function() { update(); }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="select">
<option value="1">data1</option>
<option value="2">data2</option>
<option value="3">data3</option>
<option value="4">data4</option>
</select>
<div id="info">Button</div>
So as you see, when select is changed it adds "data-info" attribute to div. And when div is pressed it send data-info to php script. And the problem is that it always send the same value. But after refresh it sends fine only once and than again the same value as first. Its hard to explain but here is example:lets say that i change select to "data2" and press on div. It sends "2". But then when i change it to "data3", and press on div, it still sends "2", not "3". There is no cache set or something. Sorry for bad english and thanks in advance :)
Use jQuery for setting if you are also going to be reading it with jQuery
Change
document.getElementById("info").setAttribute("data-info", this.value);
to
$"#info").data("info", this.value);
Still wondering why you are using data atrrbutes when you are not just reading the value on demand.
add($('#select').val());
You are using confusing code, you can achieve the same using:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="select">
<option value="1">data1</option>
<option value="2">data2</option>
<option value="3">data3</option>
<option value="4">data4</option>
</select>
<div id="info">Button</div>
<script>
$('.product__cart, .stock-product__cart').on('click', function() {
var info = $('#select').val();
$.ajax({
type: 'get',
cache: false,
data: {'action': 'info_add', 'info': info },
url: sitepath + 'info/all',
success: function() { update(); }
});
});
</script>