I'm new to PHP and javascript and I've run into a problem where I need to edit values in an xml document that is read in. I have an HTML Select that has been dynamically created by PHP code.
function outputTableRow() {
echo "<tr>";
echo "<td>";
echo "<select onchange=\"ValueChange(this);\">";
echo "<option value=\"not value\" selected >No selection</option>";
echo "<option value=\"A\" >A</option>";
echo "<option value=\"B\" >B</option>";
echo "<option value=\"C\" >C</option>";
echo "<option value=\"D\" >D</option>";
echo "</select>";
echo "</td>";
echo "</tr>";
}
The onchange event for the select then calls a javascript function that (as far as my understanding goes) performs an ajax request to the _POST of that same php document.
function ValueChange(obj)
{
var value = obj.value;
$.ajax({
type: "POST",
url: "functions.php",
data: "callFunction=UpdateValue"
});
}
From there I try to check the value set by the ajax request in _POST to call the appropriate function.
if(isset($_POST['callFunction'])){
if($_POST['callFunction'] == 'UpdateValue'){
UpdateValue();
}
}
And finally in the function I'm trying to get to, I'm trying to write a console log when that code is reached but it never get's there. In fact, the _POST is always empty.
function UpdateValue()
{
echo '<script>console.log("VALUE CHANGE")</script>';
}
Any help is much appreciated.
First, a heredoc is how you should be outputting blocks of HTML:
<?php
function outputTableRow() {
echo <<< HTML
<tr>
<td>
<select onchange="ValueChange(this);">
<option value="not value" selected >No selection</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</td>
</tr>
HTML;
}
Then you'll want to add a success callback to your Ajax function:
function ValueChange(obj)
{
var value = obj.value;
$.ajax({
type: "POST",
url: "functions.php",
data: "callFunction=UpdateValue",
success: function(data) {$(body).append(data);}
});
}
Really you should also be using jQuery to bind events instead of using onchange
attribute as well. Assuming you gave the select id="changer"
it would look something like this:
$("select#changer").on("change", function() {ValueChange(this);});
It's posible that the URL in Ajax call is bad, it must contain the server o something like that, you can try with ´URL: "http://localhost/functions.php"´