user6358161 user6358161 - 6 months ago 32
jQuery Question

SOLVED AJAX not passing values out to PHP

The code below is the correct version following the help of @ below:

1) Select part (unaltered):

<select id="lang" name="lang">
<option value="en" data-reactid=".1.$en">English</option>
<option value="es" data-reactid=".1.$es">Español</option>
<option value="it" data-reactid=".1.$it">Italiano</option>
<option value="sv" data-reactid=".1.$sv">Svenska</option>
</select>
<div class="lang"></div>


2) Ajax function:

$(document).ready(function() {
$('#lang').change(function() {
var language_selection = $(this).val();
$.ajax({
type: 'POST',
url: '/PATH/TO/language_ajax.php',
data: {lang: "Language " + language_selection},
success: function(data) {
//alert('This was sent back: ' + data);
$(".lang").text(data);
},
error: function(msg) {
console.log('error: ' + msg);
}
});
});
});


3) reading 'lang' from within 'language_ajax.php':

if(isSet($_POST["lang"]))
{
$lang = strip_tags($_POST["lang"]);

// register the session and set the cookie
$_SESSION['lang'] = $lang;
}


//Working solution complete.

/*
* The original message with starts here
*/
I am using Ajax to automatically update a $_SESSION value when a select option is used. Specifically, if a user selects a language from a dropdown list, $_SESSION['language'] must be update. This not happening with my implementation but I am not seeing why.

1) Select:

<select id="lang" name="lang">
<option value="en" data-reactid=".1.$en">English</option>
<option value="es" data-reactid=".1.$es">Español</option>
<option value="it" data-reactid=".1.$it">Italiano</option>
<option value="sv" data-reactid=".1.$sv">Svenska</option>
</select>


2) lang is passed to js and Ajax (post_language.js):

$(document).ready(function() {
$('#lang').change(function() {
var language_selection = $(this).val();
$.ajax({
type: 'POST',
url: '../includes/ajax/language_ajax.php',
data: {lang: language_selection},
success:function(data){
alert('This was sent back: ' + language_selection);
$('#lang').html(data);
},
error:function(msg){
console.log('error: '+msg);}
});
});
});


At this point, the ALERT message appears correctly, HOWEVER, 'lang' never reaches $_SESSION echoed from within the url: language_ajax.php. In fact, the url is never even called by ajax.

3) language_ajax.php

if(isset($_POST['lang'])){

$lang = $_POST['lang'];
echo "Language " . $lang;
}


I searched the forums for a few hours with no success. All solutions seem to not apply to the use of 'change' with a select list.

Can anyone help? thanks.

Answer

Text node data : "Language " . $lang echoed from php is not a valid child element of <select> element.

See <select>

Permitted content Zero or more <option> or <optgroup> elements.