I'm new to php and ajax. I want to run simple code of ajax with php but the code is not working as intended. I want load some text in the page when onchange happen
source code ajax.php
<select id='mySelect' onChange="MyFunction()">
<option value='option1'>Option1</option>
<option value='option2'>Option2</option>
<option value='option3'>Option3</option>
</select>
<script>
function MyFunction()
{
var params="myName=2";
var xmlHttp;
if(window.XMLHttpRequest)
xmlHttp=new XMLHttpRequest();
else
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("GET","edittest.php",true);
if(xmlHttp)
{
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200)
{
alert(document.getElementById('mySelect').value);
}
}
}
xmlHttp.send(params);
}
</script>
edittest.php source code
<?php
if(isset($_GET))
{
for($i=0;$i<1000;$i++)
{
echo($_GET['myName']);
}
}
?>
For a much simpler experience, I suggest you use jQuery AJAX. Here is the code. Check the Documentation for more details.
function MyFunction()
{
var myName=2;
$.ajax({
url: "/edittest.php",
data: {
myName: myName
},
type: "GET",
success: function(response){
console.log(response);
}
});
}
Your problem is that you declare var params="myName=2";
, but you never use it. Your script works, but since it is just requesting the edittest.php
, it wont show you anything, since your PHP script only prints out the myName
variable.
You should add the parameters at the end of your request like this:
<select id='mySelect' onChange="MyFunction()">
<option value='option1'>Option1</option>
<option value='option2'>Option2</option>
<option value='option3'>Option3</option>
</select>
<script>
function MyFunction() {
var params = "myName=2";
var xmlHttp;
if (window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
else
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("GET", "edittest.php?" + params, true);
if (xmlHttp) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(document.getElementById('mySelect').value);
}
}
}
xmlHttp.send(params);
}
</script>
(Notice the xmlHttp.open("GET", "edittest.php?" + params, true);
part.)