In my HTML page i have 2 select.
When i change the value into the first select the second select must be change is option value.
Error in console :
Uncaught ReferenceError: Invalid left-hand side in assignment
If i add console.log(result) i see the object in console.
JS code
<script type="text/javascript">
function changeoption() {
$.getJSON('users.php', {nameUser:$('#nameUser').val()}, function(result) {
var select = $('#email');
var options = select.attr('options');
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
}
$(document).ready(function() {
changeoption();
$('#userName').change(function() {
changeoption();
});
});
</script>
PHP code
<?php
$result = array();
if(isset($_GET['userName'])) {
$query = $dbh->prepare("SELECT email FROM tbl_users WHERE username = ? ORDER BY userId");
$query->execute(array($_GET['userName']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($result);
?>
HTML code
<form>
<!-- first select populated by another query inside this page-->
<select name="userName" id="userName">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
<!-- second select -->
<select name="email" id="email">
</select>
</form>
You're trying to assign to a jQuery object. Try creating the new option a different way.
instead of
$('option', select) = new Option(array['email']);
try
$('<option />', {
html: array['email'],
value: array['email']
}).appendTo('#email');
JSFiddle
You might use string append:
$('<option value="new">newOption</option>').appendTo("#email");
$('<option value="'+array['email']'+">'+array['email']+'</option>')
.appendTo("#email");
If you are a more php than jquery guy
you can put the select in a div
<div id='selecthtml'>
<select name="username" id="username">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
</div>
then instead of getjson just use $.get
var url = "users.php?username"+$("#username").val();
$.get( url, function( data ) {
$( "selecthtml" ).html( data );
});
and of course your php users.php should return an html select (not json)
like this
<select name="username" id="username">
<option>New name 1</option>
<option>new name 2</option>
</select>
$('option', select) = new Option(array['email']); // the line error
In this line the $(...) is a function. You may be so used to using jQuery that you have lost sight of this. You cannot perform $(...) = ...; just like you cannot perform alert() = ...;
Change:
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
to:
$(select).html('');
$.each(result, function(index, array) {
$(select).append(new Option(array['email']);
}
Related
I have a <select> with only one option, i want to get the rest of the options from a database using PHP and then populate said <select> with the PHP result using AJAX.
Unfortunately my code is not working, im not surprised as im new to both AJAX and jQuery but i dont get any errors to guide myself through the issue.
The PHP works as expected because its used in another part of the site and i have no issues with it so my error must be in the AJAX (no big surprise here).
Below my HTML:
<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>
Below my AJAX code:
<script type="text/javascript">
$(document).ready(function() {
$("#producto").click(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
$("#producto").append(data);
}
});
});
});
</script>
Below my PHP code:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
As always any kind of help is greatly appreacited and thanks for your time.
IMPORTANT EDIT
<select> has a duplicated id, perhaps i should i have stated this from the start as i know think thats whats causing my issue.
The fact is that in this <form> the selects are created dynamically on user request. They click on Add product and a new select with the products avaiable is created, i know the id/name of said input must have [ ] (id="producto[]") for it to be converted into an array but i dont know how to make the AJAX deal with this dynamically created reapeated selects issue. I apologise for this belated aclaration i realise now it is of the utmost importance.
You have to edit your response from this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
To this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
$response = '';
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
$response .= '<option value="' .$titulo . '">' . $titulo . '</option>'; //Concatenate your response
}
echo $response;
?>
But i suggest to use JSON to get a response and parse it on client side.
You can do this by pushing all values in to response array and use json_encode(). At the end you get straight response from the server with just a values, and append thous values whatever you need on client side.
Update
Also you append data to your existing select options. You can just add thous by editing this:
<script type="text/javascript">
$(document).ready(function() {
$("select#producto").focus(function() { //Change to on Focus event
$.ajax({
url: 'fetch_lista_productos_compra.php',
success: function(data) {
$("select#producto").html(data); //Change all html inside the select tag
}
});
});
});
</script>
Test result:
$('select#options').focus(function(){
alert("Hello this is a select trigger");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="options">
<option value="test">Test</option>
</select>
Please don't construct your html on the server, try to just send the raw data and then construct the html client-side, it's better that way and it leaves room for changing the view later without much coupling.
That said, instead of doing:
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
just do
$rows = [];
while ($row = mysqli_fetch_assoc($sql_query)) {
$rows[] = $row;
}
//this is your best bet when sending data from PHP to JS,
//it sends the rows as JSON-like string,
//which you'll parse to an array in the client
echo json_encode($rows);
then in the client
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: (data /*json-like string*/) => {
const dataAsArray = JSON.parse(data);
$.each(dataAsArray, (index, row) => {
//now HERE you construct your html structure, which is so much easier using jQuery
let option = $('<option>');
option.val(row.titulo).text(row.titulo);
$("#producto").append(option);
});
}
});
Regarding your edit about several selects
I don't have access to your server of course so I'm using a mock service that returns JSON. IDs are dynamically generated and all data loading occurs asynchronously after you click on the button.
Try using your url and modify the success function according to your html.
$(document).ready(function() {
$('#add').click(() => {
//how many so far...?
let selectCount = $('select.producto').length;
const select = $('<select class="producto">');
select.attr('id', `producto${selectCount + 1}`);
//then we fetch from the server and populate select
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'get',
success: function(data) {
data.forEach((d) => {
const option = $('<option>');
option.val(d.id).text(d.title);
select.append(option);
});
}
});
document.body.appendChild(select[0]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add'>Add product</button><br>
<!--<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>-->
HIH
As it turns out the code in the question was actually working properly, the problem was not the code itself but the fact that, as i stated (sadly on a later edit and not right from the start) in the question, there where more than one <select> using the same id, therefore everytime the AJAX was executed the result was appended to the first <select> only, and it was appended over and over again everytime i clicked it, my solution was unifiying both the AJAX that populated the <select> and the jQuery that created the said dynamic <select>'s all in one script thus solving all of my issues at once.
Below my jQuery/AJAX code:
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 0;
$(add_button).click(function(e) {
e.preventDefault();
$.ajax({
url: '/testground/php/fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
if(x < max_fields) {
x++;
var html = '';
html += '<div class="form-group row" id="inputFormRow" style="margin-bottom: 0px;">';
html += '<label class="col-3 col-form-label font-weight-bold">Producto</label>';
html += '<div class="col-7">';
html += '<select class="custom-select my-1 mr-sm-2" id="producto" name="producto[]" required>';
html += '<option disabled selected value>Elegir...</option>';
html += data;
html += '</select>';
html += '</div>';
html += '<div class="col-1 my-auto" style="padding: 0px 0px 0px 0px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$(wrapper).append(html);
}
}
});
});
$(document).on('click', '#removeRow', function () {
$(this).closest('#inputFormRow').remove(); x--;
});
});
</script>
I want to thank everyone that took the time to help me out with this Swati, Serghei Leonenco and Scaramouche, this community is truly amazing.
<script type="text/javascript">
$(document).ready(function() {
$("#producto").change(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
console.log(data)
// $("#producto").append(data);
}
});
});
});
</script>`enter code here`
try run this and check in your console that weather you are receiving the data from your php or not.
<script>
$(document).ready(function(){
$("#region").change(function(){
region = $(this).val()
$.ajax({
type:"POST",
data:{"region":region},
url:"get-city.php",
success:function(data){
alert(data);
//$("#city").html(data);
//$("#state").html(data);
}
});
});
});
</script>
<select name="region" id="region" >
<option value="">Select Region</option>
<?php
$sql = mysqli_query($con, "SELECT * FROM `region`");
while($row = mysqli_fetch_array($sql))
{
?>
<option value="<?php echo $row['heading_text']; ?>"><?php echo $row['heading_text']; ?></option>
<?php
}
?>
</select>
<select name="state" id="state">
<option value="">Select Region State</option>
</select>
<select name="city" id="city">
<option value="">Select Region City</option>
</select>
get-city.php
<?php
error_reporting(0);
include('dbase.php');
$region = $_POST['region'];
$sql = "select * from region_data where heading_text='".$region."'";
$results = mysqli_query($con,$sql);
while($rows = mysqli_fetch_assoc($results))
{
$data[] = array(
'state' => $rows['state'],
'city' => $rows['name']
);
}
echo json_encode($data);
?>
In this code I have created simple dropdown one is for region where I change its value by id as you can see in jquery code. Now, As you can see in get-city.php file I have encode data via json_encode function which work fine. But problem is I am not able to show data in state and city drop down in php. My json_encode data look like:
[{"state":"","city":"delhi"},{"state":"","city":"agra"},{"state":"","city":"varanasi"},{"state":"","city":"haridwar"},{"state":"","city":"dharamshala"},{"state":"","city":"srinagar"},{"state":"","city":"mussoorie"},{"state":"","city":"amritsar"},{"state":"","city":"shimla"},{"state":"","city":"kullu manali"},{"state":"","city":"assam"},{"state":"","city":"meghalaya"},{"state":"","city":"arunachal pradesh"},{"state":"","city":"manipur"},{"state":"","city":"nagaland"},{"state":"","city":"J AND K"},{"state":"38","city":"Saharanpur"}]
So, How can I get value in dropdown? Please help me.
Thank You
You'll have to use parseJSON in jQuery to decode the JSON data and then append() the option values to city and state select tags.
<script>
$(document).ready(function(){
$("#region").change(function(){
region = $(this).val()
$.ajax({
type:"POST",
data:{"region":region},
url:"get-city.php",
success:function(data){
var obj = $.parseJSON(data);
$.each(obj, function() {
$("#city").append('<option value="'+this['city']+'">'+this['city']+'</option>');
$("#state").append('<option value="'+this['state']+'">'+this['state']+'</option>');
});
//$("#city").html(data);
//$("#state").html(data);
}
});
});
});
</script>
If you need to get back a JavaScript object from a JSON string, you are looking for JSON.parse().
I did not got exactly how you want to display data, but as far as I understand you are looking for a way to populate the dropdowns, so I will show you only for the city part...for all the other dropdowns the flow is the same.
Assuming you have all the cities in the cities variable after the AJAX call (and after the JSON.parse call if needed):
let cities = [{"state":"","city":"delhi"},{"state":"","city":"agra"},{"state":"","city":"varanasi"},{"state":"","city":"haridwar"},{"state":"","city":"dharamshala"},{"state":"","city":"srinagar"},{"state":"","city":"mussoorie"},{"state":"","city":"amritsar"},{"state":"","city":"shimla"},{"state":"","city":"kullu manali"},{"state":"","city":"assam"},{"state":"","city":"meghalaya"},{"state":"","city":"arunachal pradesh"},{"state":"","city":"manipur"},{"state":"","city":"nagaland"},{"state":"","city":"J AND K"},{"state":"38","city":"Saharanpur"}];
cities.map(function(item, index) {
// let's build an <option> element
const city = jQuery("<option>", {value: item.city, text: item.city})
// let's add the <option> element to the right <select>
jQuery("#city").append(city);
});
this is one of the solution. You can search more for dependent dropdown
use value.city and vvalue.state as you want, or key as option value , its upto you, i just showed how you get values
$.ajax({
url:"get-city.php",
data:{"region":region},
type: "POST",
success: function(data) {
$('select[name="city"]').empty();
$.each( JSON.parse(data), function(key, value) { // or use data without JSON.parse(data)
$('select[name="city"]').append('<option value="'+ value.state +'">'+ value.city +'</option>');
});
}
});
Inside your success section:
success:function(data){
for(let i = 0; i < data.length; i++){
$('select[name="city"]').append('<option value="'+ data[i].city +'">'+ data[i].city +'</option>');
}
}
This is the language select box.
<select name="lang" id="lang" browser="Indicated by the browser">
<option value="en">English</option>
<option value="fr">French</option>
<option value="ch">Chinese</option>
<option value="sp">Spain</option>`enter code here`
</select>
This is script i have written.
<script type="text/javascript">
jQuery(document).ready(function() {
loadBundles('en');
jQuery('#lang').change(function() {
var selection = jQuery('#lang option:selected').val();
loadBundles(selection != 'browser' ? selection : null);
jQuery('#langBrowser').empty();
if(selection == 'browser') { jQuery('#langBrowser').text('('+jQuery.i18n.browserLang()+')');
}
});
});
function loadBundles(lang) {
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language:lang,
callback: function() {
updateExamples();
}
});
}
function updateExamples() {
var ex1 = 'Firstname';
var ex2 = 'Lastname';
var ex3 = 'Youremail';
var ex4 = 'Reenteremail';
var ex5 = 'Newpassword';
var ex6 = 'Dateofbirth';
var ex7 = 'Signup';
var ex8 = 'Itsfreeandalwayswillbe';
var ex9 = 'Birthlabel';
var ex10 = 'Termslabel';
var ex11 = 'Summarylabel';
var ex12 = 'PersonalLabel';
var ex13 = 'Interestlabel';
var ex14 = 'Addlabel';
var ex15 = 'Editlabel';
var ex16 = 'Deletelabel';
var spreadsheet_label = 'Spreadsheetlabel';
var invite_google_label = 'Invitegooglelabel';
var invite_facebook_label = 'Invitefacebooklabel';
var upload_label = 'Uploadlabel';
var subBut='Submit';
var dialogTitle = 'DTitle';
jQuery("#first_name_label").text(eval(ex1));
jQuery("#first_name_label1").text(eval(ex1));
jQuery("#last_name_label").text(eval(ex2));
jQuery("#last_name_label1").text(eval(ex2));
jQuery("#email_label").text(eval(ex3));
jQuery("#email_label1").text(eval(ex3));
jQuery("#reenter_email_label").text(eval(ex4));
jQuery("#new_password_label").text(eval(ex5));
jQuery("#date_of_birth_label").text(eval(ex6));
jQuery("#date_of_birth_label1").text(eval(ex6));
jQuery("#sign_up").text(eval(ex7));
jQuery("#label1").text(eval(ex8));
jQuery("#button").val(eval(ex7));
jQuery("#birth_label").text(eval(ex9));
jQuery("#terms_label").text(eval(ex10));
jQuery("#summary_label").text(eval(ex11));
jQuery("#personal_label").text(eval(ex12));
jQuery("#interest_label").text(eval(ex13));
jQuery("#add_label").text(eval(ex14));
jQuery("#edit_label").text(eval(ex15));
jQuery("#delete_label").text(eval(ex16));
jQuery("#spreadsheet_label").text(eval(spreadsheet_label));
jQuery("#invite_google_label").text(eval(invite_google_label));
jQuery("#invite_facebook_label").text(eval(invite_facebook_label));
jQuery("#upload_label").val(eval(upload_label));
jQuery("#submit_button").val(eval(subBut));
jQuery("#ui-dialog-title-dialog").text(eval(dialogTitle));
}
</script>
Everything is working fine for the labels. But in the case of dynamic drop down i got problem. How to localize the dynamic drop down data when the user selected the language.
The data in the drop down is coming from the database.
I have a language select drop down box, after selecting one language from dropdown list am able to change the text filed names and all other text in the language that is selected.
At the same time i have another dropdown, in that data is generated dynamically form the database. After the user selecting the language from dropdown list i have to change the data in this drop down list also. please suggest me if u have any idea.
Thank you.
I suggest you to use ajax for this issue.
You can bind ajax to first drop down and then fill secound dropdown by data which you get from back-end.
You can do something like this :
<select name='lang'>
<option value='eng'>Eng</option>
<option value='french'>French</option>
</select>
<!-- below div is another div whose data changes as per the language selected -->
<div id="another_div"></div>
JS:
$("select[name='lang']").live({
change: function(e){
var selected_lang = $("select[name='lang'] option:selected").html();
data = {}
data['selected_lang'] = selected_lang;
$.ajax({
url: "required url",
data: data,
success: function(res){
$("#another_div").text(res); // if result is a direct text sent from server
// or
$("#another_div").text(res.content); //if result is an object with the required content present in the key 'content'
},
error: function(err){
alert("error occured");
}
});
}
});
I would use one of the many Cascading jQuery Dropdowns:
http://www.ryanmwright.com/2010/10/13/cascading-drop-down-in-jquery/
Im trying to trigger an asynchronous JSON request when I select an option from an HTML selector box using mootools.
I have the following form element:
<form method="post" id="sel">
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
</form>
I'm using the following javascriipt/mootools to send a JSON request carrying the form info
window.addEvent('domready', function()
{
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response)
{
$('response').set('html', response.params)
}
}).get($('sel'));
})
});
to the following php script
$result['params'] = $_GET;
echo json_encode($result);
However, I'm told in Chrome's developer tools 'cannot read property "params" of null'
I don't see why request should be 'null' here.
Any ideas would be greatly appreciated
Hey man the answer to your question is in the question itself.
Your triggering the event when you are clicking on the select when like you said "select an option"
Click on the select would be wrong, however so would click on an option with in the select what your looking for is the onChange event the code would be as follows:
HTML
// Notice no form tag needed unless you are serializing other items
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
JAVASCRIPT
window.addEvent('domready', function(){
$('_selecor_id').addEvent('change', function(){
new Request.JSON({ // This must return a valid json object
url: "my_php_script.php",
data: {
'value': this.get('value')
}
onSuccess: function(responseJSON, responseText){
$('response').set('html',responseJSON.params);
}
}).send();
})
});
PHP
$result['params'] = isset($_GET['value']) ? $_GET['value'] : 'Not Set';
echo json_encode($result);
The responseJson variable will now contain something like {"params":"value_b"}
Try this code:
window.addEvent('domready', function(){
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response){
$('response').set('html',(response || this.response || this.responseText || {params: ''}).params)
}
}).get($('sel'));
})
});
I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.
what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).
Problem is that i dont know how to pass my php array to the jquery function, any idea ??
this is how i fill the array:
$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
got my select object:
<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>Acompañante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
and this is my code for the jquery function (it is in the same .php page)
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/
HTML:
<select><option>---</option><option>Hello</option><option>World</option></select>
<script type="text/javascript">
var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
var json = JSON.parse(encoded_json_from_php);
</script>
jQuery:
$(function() {
$("select").change(function() {
$(this).unbind("change");
var val = json[$(this).val()];
var select = $(this);
$(this).empty();
$.each(val, function(i, v) {
select.append("<option>" + v + "</option>");
});
});
});
try this one..
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
my_array = new Array();
<?php foreach($array as $key->val)?>
my_array['<?php echo $key?>'] = '<?php echo $val;?>';
<?php endif; ?>
});
});
</script>