it seems that my script is unable to call PHP functons in ajax_test.php. I am trying to achieve the call for php function when the dropdown box is changed. My html page is index.php. The code is below. Can anyone enlighten me? index.php
<script>
$(document).ready(function(){
$("#cm").change(
function ()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//code goes here
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var test = $.ajax
({
type: "POST",
url: "ajax_test.php",
dataType: "json",
}).done(function(){
document.getElementById("box").innerHTML = xmlhttp.responseText;
});
}
}
xmlhttp.open("POST","ajax_test.php",true);
xmlhttp.send();
});
});
</script>
<div>
<div id="box"><p>a</p></div>
<form>
<select id="cm">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</form>
ajax_test.php
<?php
function hey(){
echo '<p>hey</p>';
}
?>
If you are using jquery, you should stick to jquery functions. Try replacing your change function with below code.
$("#cm").change(
function (){
$.ajax({
type: "POST",
url: "ajax_test.php",
dataType: "json"
}).done(function(data){
$("#box").html(data);
});
}
});
Also make sure, you are sending correct dataType. Check if the server is returning application/json
for response type for the ajax call.
You not only have to define, but also call the function hey()
in your php script.
I think you are missing with the libraries. add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
before the script starts. Here I am using 1.8.3, you can use latest one Just google around it.
Suggestion:
You are trying to mix 2 ways to call ajax. I mean using XMLHttp request object & also jquery ajax. Try either one. I suggest you for jquery ajax. Tell me if you need any programming help.
- Thanks