Assume that I have 2 .php files : index.php and ajax.php
This is index.php:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Website title</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
ajax_register = function(){
$.ajax({
type: "post",
url: 'ajax.php',
dataType: 'json',
data: "act=register",
success: function(data){
//var json = $.parseJSON(data);
//alert(json);
alert(data.result);
},
error: function(e){
alert("Error : " + e);
}
});
};
</script>
<form name="myForm" id="myForm" method="post">
Your name :
<input type="text" name="name" id="name" />
<a href="javascript:void(0)" onclick="ajax_register()">Register</a>
</form>
</body>
</html>
And this is ajax.php:
<?php
$result = array("result"=>"Success");
echo json_encode($result);
exit;
But I always have “Error” alert dialog.
Look in Firebug, I see that the response data contains all html elements instead of only json data.
Try to send header as “json” by edit ajax.php :
<?php
header("Content-type: application/json");
$result = array("result"=>"Success");
echo json_encode($result);
exit;
But it doesnt work. The response header is always : Content-Type:text/html;
UPDATE
This is what ajax.php response:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Website title</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
ajax_register = function(){
$.ajax({
type: "post",
url: 'ajax.php',
dataType: 'json',
data: "act=register",
success: function(data){
//var json = $.parseJSON(data);
//alert(json);
alert(data.result);
},
error: function(e){
alert("Error : " + e);
}
});
};
</script>
<form name="myForm" id="myForm" method="post">
Your name :
<input type="text" name="name" id="name" />
<a href="javascript:void(0)" onclick="ajax_register()">Register</a>
</form>
{"result":"Success"}
What do I wrong here?
Thanks for your time!
I only changed this LOC
<script type="text/javascript" src="jquery.js"></script>toto check your code and its all working fine at my end ..check JS errors may be a case of JS conflicts. (Alerting Success for me). Let me know if problem still persist
index.phpCODE —ajax.phpCODE —Alerting
Successon clicking at register.