Getting parseerror when getting response from json_encode using $ .ajax

I am trying to try a fairly simple query and get a response thing using $ .ajax via. JSON I tried a lot to return a simple text phrase from a php file. My piece of js code looks like it calls beemailer.php to get an answer.

$.ajax({ type: 'POST', dataType: "json", contentType: "application/json; charset=utf-8", url: 'beemailer.php', data: { 'name': data_name, 'email': data_email, 'message': data_message, 'subject': data_subject }, success: function (data) { var output = jQuery.parseJSON(data); console.log(output); alert(output); }, error: function (error, x, y) { console.log(error); alert(x, y); } ) }; 

And beemailer.php looks like this:

 <?php $to = " ashish_sharma307@hotmail.com "; $subject = $_POST['subject']; $message =$_POST['message']; $headers = "From:".$_POST['name']."(".$_POST['email'].")"; mail($to,$subject,$message,$headers); $response = "The mail has been sent. Thank You the valid mail."; header("Content-Type: application/json; charset=utf-8", true); echo json_encode($response); ?> 

Now I just need to get this response text of the response. Any help would be appreciated.

+4
source share
4 answers

Take the code below ajax and try:

 contentType: "application/json; charset=utf-8", 

jQuery.parseJSON(data) not required, as Content-Type installed and encoded in json using the lower code:

 header("Content-Type: application/json; charset=utf-8", true); echo json_encode($response); 

Updated code with test data:

Js

 $.ajax({ type: 'POST', dataType: "json", url : 'beemailer.php', data: {name: 'rai', email: ' rai@test.com ', message: 'Test message', subject: 'Test subject'}, success : function(data) { console.log(data); alert(data); }, error: function(error, x, y) { console.log(error); alert(x, y); } }); 

PHP (beemailer.php)

 <?php $to = " ashish_sharma307@hotmail.com "; $subject = $_POST['subject']; $message = $_POST['message']; $headers = "From:" . $_POST['name'] . "(" . $_POST['email'] . ")"; mail($to, $subject, $message, $headers); $response = "The mail has been sent. Thank You the valid mail."; header("Content-Type: application/json; charset=utf-8", true); echo json_encode($response); ?> 

Example object:

 $result = array(); $result['status'] = 'success'; $result['message'] = 'The mail has been sent. Thank You the valid mail.'; header("Content-Type: application/json; charset=utf-8", true); echo json_encode($result); 

JS to access the object:

 $.ajax({ type: 'POST', dataType: "json", url : 'beemailer.php', data: {name: 'rai', email: ' rai@test.com ', message: 'Test message', subject: 'Test subject'}, success : function(data) { alert('status: ' + data.status + '\nmessage: ' + data.message); }, error: function(error, x, y) { console.log(error); alert(x, y); } }); 
+3
source

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> 
+1
source

A notification / warning may have been sent to your server. disable error reporting for testing. error_reporting (0), this works for me in php 5.4.

Hope this helps someone to face the same problems.

0
source

I just found something completely crazy about PHP json_encode and JS AJAX parseerror . If it helps one person who will justify mine, including him here.

I got a completely inexplicable parseerror with returning an object that includes the simplest possible PHP object: just a regular string key and a short string value.

When I put development log messages in my code, I usually put "E" at the beginning of the messages, just to make them easier to find. Suddenly, I put "E" at the beginning of this post to get back to JS AJAX processing ... and it was THIS that caused parseerror !

I personally consider this a mistake ... and am surprised that I will find it in 2017. I have no idea why the lead "E" may have this effect and wonder (naturally) whether other characters (lead or otherwise) can cause the parseerror effect.

I just did a search on this subject and found that one person mentions a problem with the pound symbol here (2011).

When you send SQL queries to mysqli , you need to pass them through the escape function ... this experience makes me wonder if the lines coming from PHP need the JS AJAX handler ...

Any experts can comment?

0
source

Source: https://habr.com/ru/post/1490873/


All Articles