C# - Sending a XML over to Action result via JavaScript in cshtml - javascript

I have a .cshtml file which contains JavaScript function to perform a POST action to my controller class.
<input type="text" placeholder="Username" id="username" />
<button type="submit" onclick="sendResult()">Submit</button>
<script type="text/javascript">
function sendResult() {
let username = document.getElementById('username').value;
try {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Test/Test");
xmlhttp.setRequestHeader('Content-Type', 'text/html');
let xml = `<?xml version="1.0"?><query><Username>${username}</Username></query>`;
console.log(xml)
xmlhttp.send(xml);
let xmlResponse;
xmlhttp.onreadystatechange = async function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
xmlResponse = await xmlhttp.responseXML;
console.log(xmlResponse)
}
}
} catch (error) {
console.log(error)
}
}
</script>
In my controller class, I did not manage to receive the xml string (myXML) after clicking on the submit button. Why is that so?
// TestController.cs
public ActionResult Test()
{
return View();
}
[HttpPost]
public ActionResult Test(string myXML)
{
Service1Client o = new Service1Client();
o.Test(myXML);
return View();
}

Related

Stop submitting form if user doesn't exist in Database

I am developing a code in JSP using Ajax to verify the user in DB (means there is one input box where user provides the email id then code checks whether user exists or not using ajax), if user doesn't exist on DB then user should not be able to submit the form. In below code, Ajax is working. It shows true/false according to returning from JSP user check file (user_exist_function.jsp) but I am not able to control to user to stop submitting if user doesn't exist on DB. Please help.
js
var MyApp = {};
function check() {
xmlHttp = GetXmlHttpObject()
var url = "user_exist_function.jsp";
value = document.getElementById('email1').value;
url = url + "?username=" + value;
xmlHttp.onreadystatechange = stateChanged
xmlHttp.open("GET", url, true)
xmlHttp.send(null)
}
function stateChanged() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
var showdata = xmlHttp.responseText;
document.getElementById("mydiv").innerHTML = showdata;
MyApp.status = showdata;
}
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function check_submit() {
var var1 = MyApp.status.valueOf().toLocaleString();
if (var1 == 'true') {
return false;
} else {
return true;
}
}
html
<form name="form" onsubmit="return check_submit();">
Email Id: <input type="text" name="email" id="email1" onkeyup="check();">
<font color="red">
<div id="mydiv"></div>
</font>
<input type="submit">
</form>
user_exist_function.jsp
<%#page import="java.sql.*" %>
<%#include file="Database_connectivity.jsp" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
try{
String username = request.getParameter("username").toString();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM V_USER_DATA WHERE " +
"EMAIL = ?");
ps.setString(1,username);
ResultSet res = ps.executeQuery();
if(res.next())
{
out.println("false");
}
else
{
out.println("true");
}
}catch (Exception e){
out.println(e);
}
%>
<input id="Mysubmit" type="submit">
<span id="msgNotInDB" style="display:none">You are not in the database</span>
if(res.next())
{
$("#Mysubmit").hide();
$("#msgNotInDB").show();
}
else
{
$("#Mysubmit").show();
$("#msgNotInDB").hide();
}
Note: this answer using jQuery, because any sensible attempt to use AJAX on a webpage would use jQuery (or at least a similar library). What I showed can be done without it (using document.getElementById()) but there's really not much sense in it.
UPDATE:
I noticed that I put the jQuery code in the server-side code. SO, let's expand our rewrite. This should replace all of the given Javascript:
function check()
{
$.get("user_exist_function.jsp", {username: $("email").val()},
function(data) {
if (data) {
$("#Mysubmit").show();
$("#msgNotInDB").hide();
} else {
$("#Mysubmit").hide();
$("#msgNotInDB").show();
} );
}

How to and retrieving JSON data from a server

I am taking an online course and one of the things we have to do is print out the JSON entries from localhost:8080/tasks. when i go to localhost:8080, it is supposed to run this code below. However, when i run it i get this response:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Dec 03 19:04:16 EST 2016
There was an unexpected error (type=Internal Server Error, status=500).
Exception parsing document: template="tasks", line 28 - column 42
column 42 is
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8" />
</head>
<body>
<h2>Tasks</h2>
<!-- TODO: add the ability to list tasks -->
<ul id="tasks">
</ul>
<form>
<input type="text" name="name" id="name"/>
<input type="button" onclick="addTask();" value="Add!"/>
</form>
<!-- the javascript has been embedded to the same site -->
<script th:inline="javascript">
// The URL to the application server that holds the tasks.
var url = "localhost:8080/tasks";
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
var liElement = document.createElement("li");
liElement.appendChild(document.createTextNode(response.name));
document.querySelector("#tasks").appendChild(liElement);
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function loadTasks() {
}
function addTask() {
var name = document.querySelector("#name").value;
if (!name) {
return;
}
console.log(name);
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json");
var data = new Object();
data.name = name;
http.onreadystatechange = function () {
if (http.readyState === 4) {
if (http.status === 200) {
addTaskToList(JSON.parse(http.responseText));
}
}
}
http.send(JSON.stringify(data));
}
function addTaskToList(task) {
var liElement = document.createElement("li");
liElement.appendChild(document.createTextNode(task.name));
document.querySelector("#tasks").appendChild(liElement);
}
window.onload = function () {
loadTasks();
};
</script>
</body>
why is this happening?
Tasks:
package sec.domain;
import java.util.UUID;
public class Task {
private String id;
private String name;
public Task() {
this.id = UUID.randomUUID().toString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Tasks controller:
package sec.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sec.domain.Task;
#RestController
#RequestMapping("/tasks")
public class TaskController {
private List<Task> tasks;
public TaskController() {
this.tasks = new ArrayList<>();
Task fixme = new Task();
fixme.setName("Fix me.");
this.tasks.add(fixme);
}
#RequestMapping(method = RequestMethod.GET)
public List<Task> list() {
return this.tasks;
}
#RequestMapping(method = RequestMethod.POST)
public Task add(#RequestBody Task task) {
this.tasks.add(task);
return task;
}
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Task delete(#PathVariable String id) {
Task t = this.tasks.stream().filter(task -> task.getId().equals(id)).findFirst().get();
this.tasks.remove(t);
return t;
}
}
Thymeleaf requires valid XML, and on the line you posted you have:
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
The & isn't a valid XML character, so you need to either surround your javascript with CDATA like this:
<script>
// <![CDATA[
... javascript here ...
// ]]>
</script>
Or else replace them with &&
Looks like you missed ';' at the end of
http.onreadystatechange = function () {
if (http.readyState === 4) {
if (http.status === 200) {
addTaskToList(JSON.parse(http.responseText));
}
}
}

Controller not receiving data?

i'm trying to send data from a view to a controller using POST but i doesn't seems to work.
Here's my code (javascript function) :
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
var titre = str;
xmlhttp.open("POST", "CheckReturn", true);
//xmlhttp.send(titre);
xmlhttp.send({"titre":titre});
}
}
the html triggering it :
<div id="check-name" class="form-row">
<input id="name" type="text" name="name" placeholder="Titre de l'événement" onkeyup="showHint(this.value)">
<span id="txtHint"></span>
</div>
and finally, the controller SUPPOSED to get it :
[HttpPost]
public ActionResult CheckReturn(string titre)
{
var contexte = new intranetEntities();
var ajax = contexte.evenementiel.SqlQuery("Somequery" + titre);
ViewBag.ajax = ajax;
return PartialView();
}
i checked bit firebug, the data is sent, but with visual studio's debugger, i see that "titre" always stay null.
What can i do ?
I've run into something similar in the past with asp.net but I never really tried to understand what's happening. What fixed it for me was the following:
make a new class somewhere in your back-end (anywhere, doesn't matter for now)
class TitreWrapper {
public string titre {get; set;}
}
then in your controller
[HttpPost]
public ActionResult CheckReturn(TitreWrapper titreWrap)
{
string titre = titreWrap.titre;
}
this should work according to my previous experience
the top answer is wrong (but right in other circumstances I think)
for this problem the following worked:
xmlhttp.open("POST", "/CheckReturn?titre=" + titre, true);
and then just
xmlhttp.send();
OR
xmlhttp.open("POST", "CheckReturn", true);
then
xmlhttp.send("titre=" + titre);

How to get server time using javascript

I am changing my question What is missing or wrong in this code When user type something in the textboxt onother texbox supposed to get server time But nothing happens.I am so inexperience with programming.Can you plase help
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
Response.Write(DateTime.Now.ToShortTimeString());
Response.End();
}
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
}
else {
document.getElementById("label").innerHTML = "wait";
}
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}
}
</script>
<title></title>
</head>
<body>
<input id="user" type="text" onkeyup="ajaxFunction()"/>
<p>
<input id="time" type="text" /></p>
<div id="label">
</div>
<p>
</p>
</body>
</html>
You misplaced the call to actually start the request
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
} // closes the if
else {
document.getElementById("label").innerHTML = "wait";
} // closes the else
} // closes the function() for onreadystatechange
// call the stuff
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}

AJAX call to struts action not working

Hi i have a requirement in which i have to check something from struts action class and then send the result back to the browser using ajax call called in a JS fx'.The issue is im not able to hit the action class and console is throwing the following error:
org.apache.struts.action.RequestProcessor processActionCreate No action instance for path /ChangePwdAjax could be created
java.lang.ClassNotFoundException:test.ChangePwdAjaxAction.java
The class is compiled and the package context is valid test.ChangePwdAjaxAction.java
Any ideas what and where im doing it wrong?
Here is what i have written so far.
JS code
function checkError()
{
var valuePassword="test";
var url = "/test/ChangePwdAjax.do?newPass="+valuePassword;
var xmlHTTP = getXMLHTTPRequest();
xmlHTTP.onreadystatechange = function() {
handleResponse(xmlHTTP); }
xmlHTTP.open("GET",url,true);
xmlHTTP.send();
}
function handleResponse(xmlHTTP){
alert("handleResponse");
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
alert("handleResponse");
var xmlDoc = xmlHTTP.responseXML;
alert(xmlDoc.documentElement.getElementsByTagName("pwdFlag")[0].text);
}
}
function getXMLHTTPRequest(){
alert("getXMLHTTPRequest");
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("XMLHttpRequest is not supported!");
}
}
Action class code
public class ChangePwdAjaxAction extends Action {
public ActionForward execute(final ActionMapping mapping, final ActionForm form,
final HttpServletRequest request,final HttpServletResponse response)
{
System.out.println("----IN--AJAX ACTION----------");
final HttpSession session= request.getSession(false);
if(session==null || session.getAttribute("user_id")==null){
return mapping.findForward("sessionexpired");
}
final String user_id=(String)session.getAttribute("user_id");
try{
final BusinessDelegate busdel=new BusinessDelegate(user_id,session.getId());
String newpwd = (String)request.getParameter("newPass");
boolean b=busdel.checkOldPWd(user_id, newpwd);
//checking return values from bus delegate
response.setContentType("text/xml");
PrintWriter printwriter = response.getWriter();
printwriter.println("<?xml version=\"1.0\"?>");
printwriter.println("<Root>");
if(b)
{
System.err.println("----New password Failed--Y--------");
printwriter.println("<pwdFlag>"+"Y"+"</pwdFlag>");
}
else
{
System.out.println("----New password OK---N-------");
printwriter.println("<pwdFlag>"+"N"+"</pwdFlag>");
}
printwriter.println("</Root>");
}catch(Exception e){
logger.logCommon("Login Action : Login Process in Action : ", "EXCEPTION");
logger.logError(e);
}
return null;
}
}
Struts-config entry
<action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>
OOps this had to be
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction"/>
rather than
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>

Categories

Resources