Returning Html To XMLHttpRequest Object - javascript

I am making an ajax call to a service that returns html as a string with this code..
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "MobileClientService.svc/REST/TestHtmlSend", false);
xhReq.send(null);
xhReq.responseType = "text/html";
var serverResponse = xhReq.responseText;
alert(serverResponse); // Shows "15"
The service creates the html correctly..
<div data-bb-type="item" data-bb-img="Images/imagesBBUI/icons/icon11.png" data-bb-title="Title From Server">
</div>
The problem is "serverResponse" in my code is returning this..
<div data-bb-type=\"item\" data-bb-img=\"Images/imagesBBUI/icons/icon11.png\" data-bb-title=\"Title From Server\">
\u000d\u000a\u000d\u000a
<\/div>
Here is the C# code used to create the html..
public string TestHtmlSend()
{
string moomoo = String.Empty;
// Initialize StringWriter instance.
StringWriter stringWriter = new StringWriter();
// Put HtmlTextWriter in using block because it needs to call Dispose.
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
//start collapse div
writer.AddAttribute("data-bb-type", "item");
writer.AddAttribute("data-bb-img", "Images/imagesBBUI/icons/icon11.png");
writer.AddAttribute("data-bb-title", "Title From Server");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//writer.Write("Some Whatever Description");
writer.RenderEndTag();
}
moomoo = stringWriter.ToString();
How do I change my code to return the html as it is without all the extra "\"?

I've run into weird issues like this before and it usually always boils down to the middleware.
Looks like a variable interpolation issue on the server side.
What is your middleware language and/or framework?
Ensure that you are printing to your output stream in a clean manner:
using only a single variable (where you can easily see quote interpolation)
not escaping on your output, unnecessarily

Related

Converting javascript code to android code - how to add referrer in POST request?

I have this java script code on my website which gets executed when someone subscribes to my newsletter. It is basically nothing but post request. This is the piece of code.
function es_submit_request(url, parameters, es_widget_form) {
http_req = false;
http_req.onreadystatechange = function() {eemail_submitresult(es_widget_form)}; // Passing the form to the submit request
http_req.open('POST', url, true);
http_req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_req.send(parameters);
}
Is is possible to call this post method from my android application code to subscribe someone to my newsletter?
I have tried this code here but it is not working.
When I debug my js code, variable values are coming as
parameters = "es_email=fgnfg#dgd.com&es_name=&es_group=&timestamp=&action=0.9901232281510463"
url = "http://thetechguru.in/?es=subscribe"
I would highly appreciate if someone could help me with the code for this. I rather not use any library for this because I don't want overhead for such small thing. (for only one network call in my app)
This is the piece of code which I am trying but it is not working.
String urlString = "http://www.thetechguru.in/?es=subscribe&es_email=fsdsf#dgd.com&es_name=&es_group=&timestamp=&action=0.9901232281510463";
String resultToDisplay = "";
InputStream in = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (Exception e) {
System.out.println(e.getMessage());
return e.getMessage();
}
try {
resultToDisplay = in.toString();//IOUtils.toString(in, "UTF-8");
//to [convert][1] byte stream to a string
Log.v("Response",resultToDisplay);
} catch (Exception e) {
e.printStackTrace();
}
Code executes, but nothing happens, email id is not added in list
What does you Application Manifest file look like? If your application doesn't have permission to access the internet, it won't. Try adding <uses-permission android:name="android.permission.INTERNET" /> to your AndroidMainfest.xml file (inside the <manifest> tag, but before the <application> tag.
Does anything show up in your log (log.v will only show if set to verbose)? If so, please share what it shows. Log guide
Failing that, is the es_email=fsdsf#dgd.com email already in the list? Make sure you're updating the es_email parameter of your URLstring on the button's
I have finally solved the issue. Even though I was using proper code sending POST request, I was unable to subscribe the email id. I checked the HTTP response for the request and found that it was returning error "unexpected-error". I checked in server code and there was this condition of checking HTTP_REFERER in php code. So did a little research and added REFERER in my java request and voila, success!
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Set to POST
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setDoInput(true);
//Added referer
connection.addRequestProperty("REFERER", "http://thetechguru.in");
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(query);
writer.flush();
writer.close();
I hope it helps someone

How to retrieve data from database and display in jsp using springs mvc?

I am trying to load the data from database and insert into dropdown:
am not able to retrieve the data
My javascript looks like:
<script type="text/javascript">
function getEmployee(row)
{
// $('#brand'+row)[0].options.length = 0;
var xmlhttp;
if (window.XMLHttpRequest)
{//code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var status=xmlhttp.responseText;
var x = document.getElementById("employee"+row);
var option = document.createElement("option");
option.text = "";
x.add(option);
var temp = status.split("#");
for(var i=1;i<temp.length;i++)
{
var temp_val=temp[i].split("//");
$('#employee'+row).append( new Option(temp_val[1],temp_val[0]));
}
}
}
xmlhttp.open("GET","LoadEmployee",true);
xmlhttp.send();
}
function loadEmployee()
{
for(var i=1;i<=10;i++)
{
getEmployee(i)
}
}
I am trying to load data to below dropdown in the same jsp:
<%
int i=1;
{%>
<div class="form-group">
<label class="control-label">
Employees <span class="symbol required"></span>
</label>
<select class="form-control" name="employee<%=i %>" path="employee<%=i %>" >
</select>
</div>
<%} %>
My Controller as follows:
#RequestMapping(value = "/LoadEmployee", method = RequestMethod.GET) public void LoadEmployee(HttpServletRequest request, HttpServletResponse response) throws SQLException, IllegalStateException, IOException
{
System.out.println("In Load Brands");
String employee=homeDao.getEmployee();
response.setContentType("text/plain");
response.getWriter().write(employee);
}
My Implementation as follows:
public class Homeimpl implements HomeDao{
#Override
public String getEmployee() {
String models="";
String query = "SELECT member_name FROM mobike.mst_memberdetail;";
System.out.println(query);
try
{
ResultSet rs = null;
Statement st = null;
Connection con = com.mobike.datasource.DbConnection.getDataSource();
st = con.createStatement();
rs = st.executeQuery(query);
rs.close();
st.close();
con.close();
}
catch (Exception e){System.out.println(e);}
return models;
}
I think you want to think about the architecture of the application, and what should be responsible for each part.
The V in MVC stands for View. Your controller method returns void, so is not returning a view at all. Instead, you are writing directly to the response output stream.
A JSP is a view file. Your controller method should add things to the model (in your case, the Employee), and then return the logical view name. The view (the JSP) would have placeholders to resolve model attributes (eg: ${employee})
Having said this, the above is true for a traditional MVC application, where it is based around a full page request/response.
You are using javascript (some very old-school JS btw, have you considered using a library such as angular or even jquery to simplify this for you?). Anyway, your JS appears to be making an ajax request to get the employee data.
With this in mind, your first page of html can be loaded into the browser without a Spring MVC controller method. It can be a simple static html file with the js (but ideally the js would itself be a separate static file)
When the js makes it's ajax request, you only need it to return the employee representation - you don't need the full jsp view. Your js callback can then interpolate the returned data into the DOM
My use of the phrase representation above is deliberate, as what I've started to describe here is more in line with a RESTful architecture (though there is more to REST than simply returning representations of objects)
I'm guessing you are fairly new to this and are probably following a tutorial or two? I think your best option would be to read around the subject a little more to understand what the different components do, and to find a more up to date tutorial.

Is there a generic way of accessing JSON.parse XMLHTTPRequest.responseText?

I have a simple ASP.NET web application with the following javascript that runs on an input's onblur event:
function checkUserName() {
var request = new XMLHttpRequest();
if (request == null) {
alert("Unable to create request.");
} else {
var theName = document.getElementById("username").value;
var userName = encodeURIComponent(theName);
var url = "Default.aspx/CheckName?name='" + theName + "'";
request.onreadystatechange = createStateChangeCallback(request);
request.open("GET", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send();
}
}
The C# method this calls is the following:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string CheckName(string name)
{
return name + " modified backstage";
}
The javascript callback for the XMLHttpRequest is the following:
function createStateChangeCallback(request) {
return function () {
if (request.readyState == 4) {
var parsed = JSON.parse(request.responseText);
alert(parsed.d);
}
}
}
Although this displays the results of my server-side method, I was wondering about that property "d" I need to access to get the results. I found this only by using Intellisense. Is this property a standard property for accessing the parsed JSON? Should I be going about it some other way? Is "d" arbitrary or is it determined somehow? Is it possible for me to set the name of the property, either client or server -side?
Regarding the following:
var parsed = JSON.parse(request.responseText);
alert(parsed.d);
d is an actual property from the response object sent from the server via the GET request. It's not a special property created from the JSON.parse() method.
The server is likely wrapping the return data object into d. Thus, the response object looks something like { d: stuff } where stuff is the data that is returned.
--EDIT--
After a little digging on this, ASP.NET and WCF endpoints format the JSON object into the d property to prevent CSRF and XSS attacks. For more info, visit http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/.
.d is added by ASP.NET in framework code under the System.Web.Extensions namespace, and it's hardcoded, so no, you can't change it unfortunately. It exists to mitigate XSS attacks. On the plus side, however, you can count on .d always being present.
Nope. Afraid not the standard xmlhttprequest object is designed for XML/HTML so you will need to parse the json from the raw text I'm afraid.
The new XHR2 spec does handle additional response types though (if your browser supports it mimd).
http://www.html5rocks.com/en/tutorials/file/xhr2/

Why Node.js function doesn't return JSDom serializeDocument result?

I have PHP script which acts as a DNode client. Then I have Node.js Dnode server which evaluates code which receives from PHP client and it returns DOM as HTML. However, Node.js acts strangely to me (beeing a Node.js newbie). It doesn't return anything, even though the returning string is not empty. My code is below:
PHP client code using DNode-PHP library:
<?php
require(__DIR__.'/../../vendor/autoload.php');
$loop = new React\EventLoop\StreamSelectLoop();
$dnode = new DNode\DNode($loop);
$dnode->connect(7070, function($remote, $connection) {
$js = 'var a = document.createElement("A");';
$js.= 'document.getElementsByTagName("body")[0].appendChild(a);'
$remote->zing($js, function($n) use ($connection) {
print_r($n);
$connection->end();
});
});
$loop->run();
?>
Node.js server code:
var dnode = require('dnode');
var jsdom = require("jsdom");
var server = dnode({
zing: function (n, cb) {
var document = jsdom.jsdom('<!DOCTYPE html>');
var window = jsdom.parentWindow;
eval(n);
var html = jsdom.serializeDocument(document);
// console.log(html);
cb(html);
}
});
server.listen(7070);
Console.log() clearly outputs <!DOCTYPE html><html><head></head><body><a></a></body></html> what is expected result. But it never gets to PHP client. But what is strange, if I change line cb(html); to cb('test');, PHP outputs "test". So the problem must be somewhere on the Node.js side. But I have no idea where to look for.
Thanks in advance for any hints.
How are you viewing the response? Through a web browser? If so, then you're depending on whatever you're evaluating in eval(n) to change the DOM of the document... If nothing changes, then you won't end up seeing anything because you'll have an empty DOM other than the html/head/body tags. It would be worth your time confirming that you're getting an empty response back and it's not just an empty DOM.
That being said, The eval function has any context of you wanting to execute it on the document/window you declare above. As it is, it is just executing in the context of node itself, not on the page you are attempting to create. To fix this, try using:
window.eval(n)
If you take a look at the example Creating a browser-like window object
on the Github page for jsdom, this will give you a better idea of how exactly to use this package.
https://github.com/tmpvar/jsdom
What you have above should look something like this:
var document = jsdom.jsdom("<!DOCUMENT html>");
var window = document.parentWindow;
window.eval(n);
var html = jsdom.serializeDocument(document);
cb(html);
Now you'll be executing the Javascript on the DOM you were previously creating :-)
Your problem is not in Node. When I use the server code you show in your question and try with this client code, I get the expected result:
var dnode = require("dnode");
var d = dnode();
d.on('remote', function (remote) {
var js = 'var a = document.createElement("A");' +
'document.getElementsByTagName("body")[0].appendChild(a);';
remote.zing(js, function (s) {
console.log(s);
});
});
d.connect('localhost', '7070');
I don't do PHP so I don't know what the problem might be on that side.

checking for URL validity in VB.net

I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :
Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate
Try
Dim uri As New Uri(args.Value)
Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
Dim response As HttpWebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim reader As String = New StreamReader(stream).ReadToEnd()
args.IsValid = True
Catch ex As Exception
args.IsValid = False
End Try
End Sub
I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".
What is wrong with this code ?
Update :
I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)
function testURLValide(sender, args)
{
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open("HEAD", args.Value, false);
xmlhttp.send(null);
if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
I put your code into LINQPad and tested it out and it worked just fine...
The only difference is args.Value.
Dim uri As New Uri("http://www.google.com")
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(uri)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim reader As String = New StreamReader(stream).ReadToEnd()
reader.Dump()
<!doctype html><html><head><meta
http-equiv="content-type"
content="text/html;
charset=ISO-8859-1"><title>Google</title>............
Why not use WebClient.DownloadString() method instead?
Instead of reading the stream, how about testing for the HTTP Status Code? I believe it is response.StatusCode. The value you would look for would be 200, or possibly something in the 300s (redirect).
If you can use javascript, here's one really good way to do it: How to Test a URL in jQuery
Edit: How about one of these approaches then?
Search for "Does a URL exist?" on this page.
How to check if a URL exists in javascript
Javascript to check if URL exist

Categories