64202

JSON response opens as a file, but I can't access it with JavaScript

In the code below I make a POST request to a servlet that replies in this way:

response.setContentType("application/json"); json = "{success:true,sessionUid:\""+sessionUid+"\"}"; response.getWriter().write(json);

So Firefox opens it like a file and I can see it's ok. Here you have the JSON:

{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}

The problem is that I can't inspect the JSON object. It seems not to exist inside my callback function (also using Firebug). Take a look to the code and alerts.

<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#loginForm").submit(function(response){ alert("response="+response); //output: "response=[object Object]" var obj = jQuery.parseJSON(response); alert("obj.sessionUid="+obj.sessionUid); //doesn't work, Firebug says "obj is null" if (response.success == true){ //never true document.location.href = 'http://localhost:8080/QuoteroClient/logged.jsp'; }else{ alert("Something went wrong in the login process."); } return false; }); }); </script> </head> <body> <form id="loginForm" action="http://localhost:8080/QuoteroClient/Main?servlet=Security" method="post"> <fieldset><legend>Login to Quotero:</legend> <label>Action:</label><input type="text" name="action" value="login"/><br /> <label>Username:</label><input type="text" name="login-quotero" value="admin"/><br /> <label>Password:</label><input type="text" name="password-quotero" value="admin" /><br /> <label>Domain:</label><input type="text" name="combo-domain" value="Quotero" /><br /> </fieldset> <input type="submit" value="Submit" /> </form> </body> </html>

<strong>EDIT:</strong> I also tried to do the same with an AJAX request, wothout success:

$("#ajaxSubmit").click(function () { $.ajax({ type: "GET", //GET or POST is the same for this servlet url: "http://localhost:8080/QuoteroClient/Main?servlet=Security&action=login&login-quotero=admin&password-quotero=admin&combo-domain=Quotero", dataType: "json", success: function (response) { alert("response=" + response); var obj = jQuery.parseJSON("" + response); alert("obj.sessionUid=" + obj.sessionUid); if (response.success == true) { document.location.href = contextPath + 'http://localhost:8080/QuoteroClient/logged.jsp'; } else { alert("Something went wrong in the login process."); } } }); return false; });

Answer1:

I think you have mixed up ajax with submit. submit is just simply an event, when form is submitted do the following. then you can

$("#loginForm").submit(function(){ var post_data = $(this).serialize(); $.ajax({ url: '',//url of the php file that handles the forms type: 'GET', dataType:'json', data:post_data,//this are the query strings, e.g. ?q=blabla&s=blabla success:function (data){//if page was 200 or successfully loaded alert(data.sessionUid); // do what ever you wish with the data here }, error: function (){ alert('Page failed to load'); } }) return false; });

Answer2:

This is not valid JSON:

{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}

This is valid JSON:

{"success":true,"sessionUid":"D07WC15R7LFRFRGPF4P5"}

In JSON the keys must always be quoted. See DEMO.

Recommend

  • Multiple tags with same authentication manager in Spring Security 3.1
  • The request sent by the client was syntactically incorrect
  • Playframework: InvocationTargetException
  • Django login form in bootstrap popup
  • c# linear regression given 2 sets of data
  • What's an elegant way of accessing parent controller's member from child controller?
  • RabbitMQ java client stops consuming messages
  • Organizing large javascript files [closed]
  • pythonanywhere - How do I use websockets to transmit messages as per the web2py messaging example?
  • What is the use of a session store?
  • Getting different value with placeholder over CPU/GPU
  • Passing “get” parameters doesn't work, parameter not visible in the link
  • Uncaught TypeError: $(…).select2 is not a function
  • How do I display a dialog that asks the user multi-choice questıon using tkInter?
  • Eliminate partial duplicate rows from result set
  • D3 get axis values on zoom event
  • Button click event not firing in jQuery
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • Chart.js Multiple dataset
  • htaccess add www if not subdomain, if subdomain remove www
  • How do I get HTML corresponding to current DOM tree?
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • Custom validator control occupying space even though display set to dynamic
  • JQuery Internet Explorer and ajaxstop
  • Cannot connect to cassandra from Spark
  • req.body is undefined - nodejs
  • Accessing IRQ description array within a module and displaying action names
  • Modifying destination and filename of gulp-svg-sprite
  • MySQL WHERE-condition in procedure ignored
  • Change an a tag attribute in JavaScript based on screen width
  • Importing jscolor library in angular 2
  • Web-crawler for facebook in python
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • trying to dynamically update Highchart column chart but series undefined
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • How do I configure my settings file to work with unit tests?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • Binding checkboxes to object values in AngularJs
  • java string with new operator and a literal