Since you said dataType: "json" , jQuery will parse the JSON for you before calling the success function, so what you pass to parseJSON is already an object graph, not a string. Take out this call and instead of using output just use data directly.
However, what you return from your PHP is not a valid JSON document, it is just a JSON fragment (string). A JSON document should always have an object or top-level array ( larger ). Therefore, you need to wrap this string in an object or array.
Also note that you are using the contentType parameter incorrectly. This determines the type of what you are sending , not the type of what you expect to receive.
For instance:
$response = "The mail has been sent. Thank You the valid mail."; header("Content-Type: application/json; charset=utf-8", true); echo json_encode(array(message => $response));
... and then in your success function:
success: function(data) { alert(data.message); }
Notice how the key I used in PHP ( message ) became the key in the resulting deserialized JSON on the client.
This complete example works:
PHP ( test.php ):
<?php $response = 'This is a test message. You sent: ' . $_POST['param']; header('Content-Type: application/json; charset=utf8', true); echo json_encode(array(message => $response)); ?>
HTML and Script:
<!doctype html> <html> <head> <title>Test Page</title> <meta charset="UTF-8"> </head> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script> $.ajax({ type: 'POST', url: 'test.php', data: {param: 'Test param'}, success: function(data) { alert(data.message); } }); </script> </html>
In the comment below you said:
Could you explain ... why I do not get the text as an answer when returning the text.
You are returning JSON , which is a textual representation of a graph of objects.
Absolutely, you can return the text if you want. Do not use JSON for this. Here is an example, but this will not solve the problem that you encounter extraneous HTML output before your message, what happens in your PHP:
PHP ( test.php ):
<?php header('Content-Type: text/plain; charset=utf-8', true); $response = 'This is a test message. You sent: ' . $_POST['param']; echo $response; ?>
HTML and Script:
<!doctype html> <html> <head> <title>Test Page</title> <meta charset="UTF-8"> </head> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script> $.ajax({ type: 'POST', url: 'test.php', data: {param: 'Test param'}, success: function(data) { alert(data); } }); </script> </html>