I am trying to communicate back and forth with the server with the help of jQuery.
This is my simple scenario:
Now my problem is that php is returning source html code with tags, instead of data that has been received ? So if I type "Hello" in the form field on the client side, php is returning whole html source from the page. Why is that ?
Html:
<form action="#">
<textarea name="content" id="content" rows="8" cols="40"></textarea>
<p><button>Click to submit</button></p>
</form>
jquery:
(function(){
$("form").on("submit",function(e){
$.post("save.php",$(this).serialize(),function(data){
alert(data);
})
e.preventDefault();
})
}());
PHP:
<!DOCTYPE HTML>
<html charset="utf-8">
<head>
<title>Index</title>
<link rel="stylesheet" href="path-to-stylesheet.css" type="text/css"/>
</head>
<body>
<?php
echo $_POST['content'];
?>
<script src=""></script>
</body>
</html>
You are sending a complete html page back to the browser, that's why you don't receive only the data. Change your php file to the following and it should work as expected:
<?php
echo $_POST['content'];
?>
<?php ?>
tags, the whole content is left untouched and will be sent to the browser as it is<?php ?>
tags the parser interprets the code and outputs it in the same placesave.php
<!DOCTYPE HTML>
<html charset="utf-8">
<head>
<title>Index</title>
<link rel="stylesheet" href="path-to-stylesheet.css" type="text/css"/>
</head>
<body>
<?php
echo $_POST['content'];
?>
<script src=""></script>
</body>
</html>
The parser finds one <?php ?>
tag:
<?php
echo $_POST['content'];
?>
And interprets it: (simply assuming that $_POST['content'] == 'john smith'
)
john smith
Now, the interpreted code gets inserted and replaces the php tag in the original content:
<!DOCTYPE HTML>
<html charset="utf-8">
<head>
<title>Index</title>
<link rel="stylesheet" href="path-to-stylesheet.css" type="text/css"/>
</head>
<body>
john smith
<script src=""></script>
</body>
</html>
Finally, this is sent to the browser and gets processed by the jQuery Ajax callback.
Assuming this is your save.php :
<!DOCTYPE HTML>
<html charset="utf-8">
<head>
<title>Index</title>
<link rel="stylesheet" href="path-to-stylesheet.css" type="text/css"/>
</head>
<body>
<?php
echo $_POST['content'];
?>
<script src=""></script>
</body>
</html>
Just do a json_encode and parse jSON with your ajax call :
save.php
<?php
echo json_encode($_POST['content']);
?>
jQuery
$.post("save.php",
$(this).serialize(),
function(data){
alert(data);
}, 'json');