1

I am creating a Javasript object:

var obj= new Object();
obj.Message = $(".textarea").val();

and posting this object via JSON stringify:

$.ajax({
    type: "POST",
    contentType: "application/json",
    dataType: "json",
    url: 'xx/yy',
    data: JSON.stringify(obj),
    success: function (html) {
        // ...
    },
    error: function (request, status, error) {
        // ...           
    }
});

I am getting:

SyntaxError: unterminated string literal in console

What should I replace?

EDIT:

This issue is specific to data the user enters in plain text area (not rich text area)

4
  • You can click the error and it will lead you to the error source line. Commented Jan 11, 2017 at 5:14
  • this code does not seems to have any issue. is this all of your code ? Commented Jan 11, 2017 at 5:18
  • not your issue, but: dataType: "json", with data: JSON.stringify(obj), is wrong ... dataType: "json", data:obj, and you're golden Commented Jan 11, 2017 at 5:18
  • Hi thanks for your reply issue seems to be in data. I am using plan textarea for getting value user has input some character due to that its breaking. Commented Jan 11, 2017 at 5:19

2 Answers 2

1

This may be your value of have some line breaks or some invalid string literals. You can replaces line breaks of your textarea's value like this.

var str = $('#textarea1').val();
str = str.replace(/(?:\r\n|\r|\n)/g, ''); 

This is full code snippet, so that u can check. Hopefully you can escape from "SyntaxError: unterminated string literal" when executing JSON.stringify(obj).

<!DOCTYPE html>
<html>
	<head>
		<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
	</head>
	<body>
		<textarea id="textarea1" rows="4" cols="50">
		</textarea>
		<input type="button" value="Check" id="btnCheck"/>
		
		<script>
			$(document).ready(function(){
			
				$('#btnCheck').on('click',function(){
				
					var str = $('#textarea1').val();
					str = str.replace(/(?:\r\n|\r|\n)/g, ''); 
					var obj= new Object();
					obj.Message = str;
					
					console.log(JSON.stringify(obj));
					
				});
			});
		</script>
	</body>
	
	
</html>

Sign up to request clarification or add additional context in comments.

Comments

0

use template literals ``, which are supported in ECMAScript 2015 environments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.