I have a form that asks the user to enter their Google Analytics code in a textarea. I then pass this string into ajax post and receive an error saying that I am passing an invalid object. (I am not pasting the whole error message here as it is quite long..)
The Google Analytics code, as expected, is in the form of following;
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'some_number']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
And I use this to post to server:
$.ajax({
type: "POST",
url: "Settings.aspx/setStats",
data: "{'skey': 'ga_code', 'sval':'" + el.val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8"
}); // el.val() being the google analytics code..
How can I post this without the error? Also, I will need to get it as well, when the user needs to update it.. Will the same problem arise when receiving it too?
Your object as it stands is not so; it is a string, you are passing a string as an object.. try the following:
Usually objects are converted into query strings, as is said on the documentation page, but since you are passing a string to the converter, I believe it is not going to work.
Update:
It would appear I was a bit wrong; the above is not valid json, the following should work, as a correction to the above:
Keys and values must be double-quoted, from what I am reading, though I’m a bit confused, as I have used json like I first gave you with no problems what-so-ever. Lastly, I would recommend this site to test if your JSON is valid.
If that still doesn’t work, then I would recommend changing your contentType to the following: