issue with ajax send() function - ajax

<!DOCTYPE html>
<html>
<head>
<title>Lesson 18: Making AJAX Calls</title>
</head>
<body>
<h1>Lesson 18: Making AJAX Calls - Plain Text Response</h1>
<div>
<h2 id="myHeader">Click the button to call your data</h2>
<input type="button" value="Click Me!" onclick="getText('test.txt')" />
</div>
<script type="text/javascript">
var myRequest;
function getText(url)
{
if (window.XMLHttpRequest)
{
myRequest = new XMLHttpRequest();
}
else
{
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
myRequest.open("GET", url, true);
myRequest.send(null);
myRequest.onreadystatechange = getData;
}
function getData()
{
var myHeader = document.getElementById("myHeader");
if (myRequest.readyState ===4)
{
if (myRequest.status === 200)
{
var text = myRequest.responseText;
myHeader.firstChild.nodeValue = text;
}
}
}
</script>
</body>
</html>
This code is from this tutorial: http://www.html.net/tutorials/javascript/lesson18.php
Questions:
what does this mean: myRequest.send(null); what is the difference between it and myRequest.send();?

No difference. .send(null) is mean that you are sending "null" content in request body. .send() is mean that you are sending nothing in request body.
In case of GET requst there is no difference, becouse request body is not sending.
In case of POST request there will be none difference too.
See this :Why do we pass null to XMLHttpRequest.send?

Related

MVC4, TinyMCE.MVC, can't set tinymce control content after Ajax call

MVC4, downloaded TinyMCE.MVC : content of tinymce control need to be retrieved by Ajax call and set into that tinymce control. So far my attempts to set html content in tinymce control have failed. I have to use Ajax call. Is there way to do that?
Thank you.
VIEW:
<div id="divTinyMCE">
#Html.EditorFor(model => model.myContent)
</div>
<button type="button" id="btnGetContent" onclick="getContent()">Get Content</button>
#section scripts{
<script type="text/javascript">
function getContent() {
var parm1 = 1;
var parm2 = 2;
$.ajax({
type: "POST",
url: '/Home/GetContent',
data: { parm1: parm1, parm2: parm2},
success: function (data) {
alert("data from ajax = " + data.toString()); // data is html
//tinymce.set(data.toString()); // does not set anything
//tinymce.html(data); // does not set anything
$("#tinymce").html(data); // does not set anything
}
}); // AJAX call
}
</script>
}
CONTROLLER :
public ContentResult GetContent(int parm1, int parm2)
{
string contentFound = findContent(parm1); // contentFound is HTML string
return Content(contentFound);
}
I finally figured it out:
tinyMCE.activeEditor.setContent(data);

Accessing servlet generated objects (JSONObjects) via AJAX and JQuery

I am new to using AJAX and JQuery with Java Servlets. I want to produce a search page that produces a list of search results (like a google page listing). My database query works and returns a JSONObject or a JSONArray.
My code is not working for the JQUERY. I have tried a lot of different versions. The basic error is that the new page after the search just shows the data in the form of an array print. It does not recognise the HTML.
I have shown my code below with the db query removed. The different versions I tried were with various forms of JSON syntax, with and without GSON, and nothing has worked.
The system is Linux.
Any comments would be appreciated, or even a link to a comprehensive example.
search.js
$(document).ready(function(){
$('#searchbutton').submit(function)
{
var inputdata = searchText:$("#searchtext").val();
};
$.ajax({
type:"POST",
datatype: "json",
url:"search",
data:inputdata,
success: function(data){
$("#searchResults").append("<b>data.linkresult</b>")
});
});
});
});
});
search.java
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
// reading the user input
String searchword= request.getParameter("search");
String Tmsg = "";
Map<String, Object> data = new HashMap<String, Object>();
data.put("searchresult", searchword);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data));
search.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Search for a word</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="./js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="./js/search.js"></script>
<script type="text/javascript" src="./js/jquery-1.9.1.min.js"></script>
</head>
<body>
<form action="search">
Search<br>
<div>Word -
<input id="searchtext" type="text" name="search" size="40px">
</div>
<div>
<input id="searchbutton" type="submit" value="Submit">
</div>
</form>
<div id="searchresults">
</div>
Result (just this one line is displayed):
{"searchresult":"search example"}
To parse the Json message received from the servlet, you can achieve this by doing something like this. Lets assume that you have received the following message from the servlet
{"key1":"val1","key2":"val2","key3":"val3"}
And you want it to be displayed in a table.
success: function(data){
var output = '<table>';
for ( var key in data) {
if (data.hasOwnProperty(key)) {
output += "<tr>";
output += "<td>" + key + "</td>";
output += "<td>" + data[key] + "</td>";
output += "</tr>";
}
}
output += "</table>";
$("#searchResults").empty();
$("#searchResults").append(output);
});

mvc3 jquery mobile how to use Html.BeginForm

I have already written an entire site in MVC3. I am trying to build the mobile version with Jquery Mobile. I haven't changed my controller code, except to add a check for whether or not it should return a mobile page. I have the following in the document head of my mobile logon page:
<head>
<title>Mobile Logon</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0-alpha.1/jquery.mobile-1.2.0-alpha.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
$(document).bind("mobileinit", function(){
$.extend( $.mobile , {
ajaxEnabled: false
});
});
<script src="http://code.jquery.com/mobile/1.2.0-alpha.1/jquery.mobile-1.2.0-alpha.1.min.js"></script>
</head>
I have a page with a header and content. In the content, I want to let the user redirect to the register form. the following seems to work:
<form action="Register" method="get" data-ajax="false">
<button type="submit" value="Register for an account"></button>
</form>
This does not work: (the url seems correct in the browser, but all that loads is a blank, white page)
#using(Html.BeginForm("Register", "Account", FormMethod.Get, null ))
{
<button type="submit" value="Register for an account"></button>
}
When I look in the page source, I notice two differences: The first one gives a form tag with
action="Register"
while the second gives a form tag with
action="Account/Register"
The other difference is the "data-ajax=false" in the form tag.
Questions:
Am I able to use #Html.BeginForm() with Jquery Mobile? If not, how do I redirect to a different controller?
How come my code in the head section doesn't turn off the default ajax behavior of Jquery Mobile? (I tried using the form tag above without data-ajax=false, and I got the same blank, white screen as the #Html.BeginForm gave me).
EDIT: here is my logon controller code (Account controller)
public ActionResult LogOn()
{
//return View();
return SelectView("Logon", null);
}
private ActionResult SelectView(string viewName, object model, string outputType = "html")
{
if (outputType.ToLower() == "json")
{
return Json(model, JsonRequestBehavior.AllowGet);
}
else
{
#if MOBILE
return View(viewName + ".Mobile", model);
#else
if (Request.Browser.IsMobileDevice)
{
return View(viewName + ".Mobile", model);
}
else
{
return View(viewName, model);
}
#endif
}
}
here is my Register controller code: (Account controller)
public ActionResult Register(string returnUrl = "")
{
//if no return url supplied, use referrer url.
//Protect against endless loop by checking for empty referrer.
if (String.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null && Request.UrlReferrer.ToString().Length > 0)
{
return RedirectToAction("Register", new { returnUrl = Request.UrlReferrer.ToString() });
}
return View();
}

Ajaxified link in MVC3/JQuery not working in IE8 (missing header)

Consider the following code (it is based on a default EMPTY MVC3 project created in visual web developer express 2010sp1):
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="header">header</div>
<div id="main">#RenderBody()</div>
</body>
</html>
Index method of HomeController:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
ViewBag.Message = "partial";
return PartialView();
}
else
{
ViewBag.Message = "full";
return View();
}
}
Index.cshtml:
<script type="text/javascript">
$(function () {
$('#myLink').click(function () {
$.post(this.href, function (result) {
$('#main').html(result);
alert(result);
});
return false;
//$('#main').load(this.href);
//return false;
});
});
</script>
HomeController index. #ViewBag.Message
#Html.ActionLink("Index", "Index", new { controller = "Home" }, new { id = "myLink" } );
The problem is that in IE8 when the myLink link is clicked, it doesn't update the main div with only the partial html from Index.cshtml but the complete html including the layout. Ofcourse it works fine in FF, I mean why shouldn't it right? It seems Request.IsAjaxRequest() always evaluates to false in IE8. I understand that it is a result of a header X-Requested-With not being attached to a request in IE8. I don't have a lot of experience with web development -- is this a common issue and what is the (best) way to solve this?
UPDATE:
Yesterday I got it working normally in IE8, but when I tried it again this morning, the same problem was back. Now I don't think it has anything to do with the settings in IE8 anymore as I restored the settings to the default values. I tried examining the request with the fiddler tool. In order for me to be able to capture the traffic from localhost with fiddler, I added a period to the address: http://localhost.:3157/. So now the error occurs only when I use http://localhost.:3157/ (with period) and it works normally when I use http://localhost:3157/ (without period). I additionally tested the behavior in Chrome, Opera and Safari -- the ajax link works normally in these browsers. Note that I can get it working normally in IE8 when I attach a query parameter to the ajax link like so:
#Html.ActionLink("Index", "Index", new { controller = "Home", param = "param" }, new { id = "myLink" } )
I don't really want to do this. I'm running low on ideas here. I'm probably missing something that is blatantly obvious to a seasoned web developer =] Anybody recognize these symptoms?
You probably want to use the .live() method instead of .click():
$('#myLink').live('click', function () {
...
return false;
});
because you are replacing the DOM in the AJAX callback (the #main) which contains the link so you are killing the event handler you have assigned.
Also you have a typo in the jquery script inclusion in the <head>. You are missing a closing > after type="text/javascript":
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
So here's a complete working example:
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="header">header</div>
<div id="main">#RenderBody()</div>
</body>
</html>
HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
ViewBag.Message = "partial";
return PartialView();
}
else
{
ViewBag.Message = "full";
return View();
}
}
}
Index.cshtml:
<script type="text/javascript">
$(function () {
$('#myLink').click(function () {
$.post(this.href, function (result) {
$('#main').html(result);
});
return false;
});
});
</script>
HomeController index. #ViewBag.Message
#Html.ActionLink("Index", "Index", new { controller = "Home" }, new { id = "myLink" } )
add
jQuery.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
});
to make sure the correct header is attached.

MVC Scorm sequencing Issue with regards to PartialView

I am working on a Scorm MVC project. Basically I need to update a partial view from a cs class file.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Table of Contents Test</h2>
<br />
<div id="SCONavBar">
<% XElement item = (XElement) Model;
String rootID = (String) ViewData["courseRoot"];
String resource = (String) ViewData["resource"]; %>
<button id="prev" onclick="javascript:NavigationRequest('', '<%: resource %>', 'previous');">Previous</button>
<button id="cont" onclick="javascript:NavigationRequest('', '<%: resource %>', 'continue');">Continue</button>
<button id="start" onclick="javascript:NavigationRequest('', '<%: resource %>', 'start');">Start Course</button>
</div>
<div id="scoContainer">
<div id="treeContainter" style="display:inline-block; outline:black solid 1px; height:600px; width:300px; overflow:scroll; padding:2px;">
<ul id="treeview">
<% Html.RenderPartial("~/Views/Content/ActivityTreeUserControl.ascx", item); %>
</ul>
</div>
<div id="contentContainer" style="vertical-align:top; display:inline-block; outline:black solid 1px;">
<% Html.RenderPartial("~/Views/Content/ContentFrame.ascx"); %>
</div>
</div>
<script type="text/javascript" src="../../Scripts/TreeView/TOCControlScript.js"></script>
<script type="text/javascript" src="../../Scripts/TreeView/resizeFrame.js"></script>
<script type="text/javascript" src="../../Scripts/Scorm/loungeScormMethods.js"></script>
<script type="text/javascript">
$(document).ready(function () {
startTree();
});
</script>
</asp:Content>
Above is the code for my view. On first load it loads a table of contents partial view and an Iframe partial view. When clicking my personal Start, Cont and Prev buttons, an AJAX request goes through a sequencer and returns the link to the next piece of content and updates the source of the iframe in javascript. This works fine.
Javascript
function sendToFrame(source) {
window.frames.SCODisplay.location.href = source;
}
function NavigationRequest(id, resource, type) {
var result = null;
$.ajax({
type: 'POST',
url: '/Content/NavigationRequest/',
data: {type : type},
async: false,
success: function (data) {
result = data;
}
});
if (result != null && result != "") {
var source = "../Content/" + resource + "/" + result;
sendToFrame(source, id)
}
}
Now the content can sometimes be navigated via buttons internally to the content. The content calls an API wrapper which sends to a data model the fact that after it terminates a continue request must be followed. Which works ok.
Now my problem is that on terminate my systems knows that a continue request is needed, it figures out what the next piece of content is and its link. I need to find a way to update the source of iframe from here....
public static String Terminate() {
//set entry to "" or resume, available to next learner session in current learner attempt
//if exit is set to suspend via nav request suspend all then entry set to resume upon next attempt on activity
//if exit anything other than suspend or no value set entry to ""
//when exit = suspend - save cmi.suspend_data to session
//decide whether to persist data
//save info to db using entities then call commit()
cocdType cmi;
try {
cmi = (cocdType)HttpContext.Current.Session["cmi"];
} catch {
return "false";
}
if (cmi.adlNavRequest != "_none_") {
SeqObject seqObj = new SeqObject();
seqObj.currentRequestType = SeqObject.type.Navigation;
seqObj.data.Navigation = cmi.adlNavRequest;
seqObj = loungeScormSeqNavHandler.SequencingProcess(seqObj);
NEED TO FIRE OFF IFRAME CHANGE SOURCE FROM HERE
}
return "true";
}
Does this make sense, any help is appreciated.
I have come up with a work around.
My terminate function returns the full link required for the iframe and in the original ajax call I have a simple if that determines if the result isnt true or false, blank or null then it must be a link then play with it from there. Then set result to true or false after.

Resources