Hi regarding https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/function-declarations.html I define my JS function like this
<script language="javascript">
var clearMessage = function ClearMessage() {
$("#result").html("");
};
</script>
And I try to call it in OnBegin method from MVC ajax,
#using (Ajax.BeginForm(new AjaxOptions() { HttpMethod = "post", OnBegin = "ClearMessage" }))
But I getting error that function not exit,
how to call my function that described by this best practice ? (without var clearMessage evering working correct)
Never seen such syntax. Don't even know if it is valid javascript.
Try defining your function like this:
<script type="text/javascript">
var ClearMessage = function() {
$("#result").html("");
};
</script>
or like this (which is pretty much the same):
<script type="text/javascript">
function ClearMessage() {
$("#result").html("");
};
</script>
Related
I have the following script in my HTML, however I get a Question mark instead of the actual IP:
<script type="application/javascript">
var myButton = document.getElementById("clickButton");
var myText = document.getElementById("helloText");
myButton.addEventListener('click A', doSomething(), false);
function doSomething(json) {
myText.textContent = (json.ip);
}
function getIP(json) {
return json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
The problem is that doSomething doesn't receive the JSON as an argument. You need getIP to put the returned IP into a global variable, and then doSomething can display it.
var myButton = document.getElementById("clickButton");
var myText = document.getElementById("helloText");
myButton.addEventListener('click', doSomething, false);
function doSomething() {
myText.textContent = IP;
}
<script type="application/javascript">
var IP;
function getIP(json) {
IP = json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
<button id="clickButton">Show IP</button>
<div id="helloText"></div>
Also, the second argument to addEventListener should just be the function name, not a call to the function. And the first argument should just be the name of the event. There's no click A event, just click.
The function getIP() gets called when the //api.ipify.org script is loaded. Your getIP() function just returns the ip address. Other than that it does not do anything. Try doing something like this:
<div id="mydiv"></div>
<script>
var getIP = function(json) {
document.getElementById("mydiv").innerHTML = json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
I'm having a problem changing the string content of a particular DIV tag when using AJAX.
For some reason I can change string content when using an onclick function. This works;
<div id="demo">Will change on click? </div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Yes, Successfully changes" ;
}
</script>
However this does not;
<div id="demo2">Will this change?</div>
<script>
window.onload = function() {
document.getElementById("demo2").innerHTML = "Yes, Successfully changes" ;
}
</script>
Both approaches work on the page itself, but import that page using AJAX, and only the onclick method works. This issue persists when trying both JavaScript and JQuery. What am I missing?
Try registering an event handler using jQuery's .ajaxcomplete http://api.jquery.com/ajaxcomplete/ . This event gets fired when an AJAX request finishes which is probably what you are looking for.
User the following way to update the content using Ajax
<div id="demo">Let AJAX change this text</div>
<button type="button" onclick="loadDoc()">Try it</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
Go to following link for more ajax examples.
Ajax Examples
<script>
$(document).ready(function(){
$.ajax({
url: "ajax_info.txt"
}).done(function( data ) {
$("#demo").html(data);
});
});
</script>
on ready function you can call ajax and change the content
Use jquery ready function and call your function inside ready function.
like this :
$(document).ready(function(){
myFunction();
});
/* jQuery Onload String Replace OR jQuery Onload String Change */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var strNewString = $('body').html().replace(/\On hold/g,'Processing');
$('body').html(strNewString);
});
</script>
I have several Ajax.BeginForm on my MVC website. Meanwhile I need to handle the beforeSend event of my Ajax calls.
So the below code works for my manual jquery ajax calls, but it doesn't work with the Ajax.BeginForm helpers:
$.ajaxSetup({
'beforeSend': function (xhr) {
alert('');
}
});
Is there anyway to handle the beforeSend event on the MVC Ajax.BeginForm?
-------------------------------------------EDIT -------------------------------------
I need the before send event since I want to change the request headers :
'beforeSend': function (xhr) {
securityToken = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', securityToken);
}
Thanks
I think you are following samples from http://richiban.wordpress.com/2013/02/06/validating-net-mvc-4-anti-forgery-tokens-in-ajax-requests/ This post does not address the support of Ajax form integration. I did some tests and found the solution.
I assume you use MVC4 with jquery-1.9.1.js, jquery.validate.unobtrusive.js and jquery.unobtrusive-ajax.js referenced.
Following is my code
#model WebApplication1.Models.DummyModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<body>
<div id="Parent">
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", OnBegin = "BeginClient" }))
{
#Html.AntiForgeryToken();
<div>First Name</div><div>#Html.TextAreaFor(m => m.FirstName)</div>
<div>Last Name</div><div>#Html.TextAreaFor(m => m.LastName)</div>
<input type="submit" value="Submit" />
}
</div>
<script type="text/javascript">
function BeginClient(xhr) {
alert("posting...");
securityToken = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', securityToken);
}
$.ajaxSetup({
'beforeSend': function (xhr) {
securityToken = $('[name=__RequestVerificationToken]').val();
alert(securityToken);
xhr.setRequestHeader("__RequestVerificationToken", securityToken);
}
});
</script>
</body>
</html>
Basically you need to leverage onBegin event, see http://johnculviner.com/ajax-beginform-ajaxoptions-custom-arguments-for-oncomplete-onsuccess-onfailure-and-onbegin/ there is clear explanation what is the parameters for each event.
Then in your global attribute class, your code looks like
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ValidateAntiForgeryTokenOnAllPostsAttribute : AuthorizeAttribute
{
/// <summary>
/// Executes authorization based on anti-forge token.
/// </summary>
/// <param name="filterContext">MVC pipeline filter context.</param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
}
else
{
new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
}
}
}
}
By doing this way you can still force to use anti-forgery token with Ajax form.
Hope this helps.
For Ajax.BeginForm you can use AjaxOptions.OnBegin:
#using (Ajax.BeginForm("actionName", "controllerName", new AjaxOptions() {
OnBegin = "requestBeginHandler"})) {
...markup here...
}
Update. To add new request header you can do something like this:
function requestBeginHandler(ajaxContext) {
var request = ajaxCOntext.get_request();
securityToken = $('[name=__RequestVerificationToken]').val();
request.get_headers()['__RequestVerificationToken'] = securityToken;
}
I can't for the life of me figure out what I'm doing wrong.
This is my HTML/JS:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="handlebars-v1.1.2.js"></script>
<script>
$(document).ready(function(){
var jsonString = null;
$.getJSON("data.json", function(data) {
jsonString = data;
});
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
});
</script>
</head>
<body>
<script id="items" type="text/x-handlebars-template">
<span>{{Title}} : {{CSCI}}</span>
</script>
<ul>
</ul>
</body>
</html>
And this is my data.json file:
{
"Title":"I am a thing",
"CSCI":" "
}
The only output I get is the ":" so it's doing something properly. The console shows nothing (as in completely empty so I assume there's no syntactical errors anywhere?).
I don't like posting questions like this as it's usually because of a small mistake on my part somewhere, but I know you guys love this stuff ;)
As getJSON is an async function call you need to compile Handlebars in success callback function
$(document).ready(function(){
var jsonString = null;
$.getJSON("data.json", function(data) {
jsonString = data;
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
});
});
getJSON is async, and so
var source = $("#items").html();
var template = Handlebars.compile(source);
$("ul").append(template(jsonString));
should all be inside of the callback as well
For jQuery template:
http://api.jquery.com/category/plugins/templates/
I want to be able to dynamically load the templates from a server, rather than predefining it on the page.
The demos I saw on the projects are using predefined templates. After some research I found out that it is possible.
I try doing this and it doesn't work:
<script src="child.html" type="text/x-jquery-tmpl"></script>
I tried doing this and it doesn't work:
$(function () {
$.get("child.html", function (data) {
//Add template
$.template("tmplChild", data);
});
//template binds before async call is done
$.tmpl("tmplChild").appendTo("body");
});
And finally, I have get it down to the following hack:
so.html (This is the main page):
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script type="text/javascript" src="so.js"></script>
<script type="text/javascript">
$(function () {
initTemplates(templateReady);
});
function templateReady() {
$.tmpl("tmplChild").appendTo("body");
}
</script>
</body>
</html>
child.html (This is the child template)
<h1>Child Loaded</h1>
so.js (This is my hack for ajaxly loading the js templates)
function initTemplates(callback) {
var templateUrl = "child.html";
var templateName = "tmplChild";
initTemplate(templateUrl, templateName, callback);
}
function initTemplate(url, name, callback) {
var opts =
{
type: "GET",
url: url,
dataType: ($.browser.msie) ? "text" : "xml",
success: function (data) {
xmlCallback(data, name, callback);
},
error: function (x) {
xmlCallback(x.responseText, name, callback);
}
}
$.ajax(opts);
}
function xmlCallback(data, name, callback) {
if (typeof data != "string") {
if (window.ActiveXObject) {
var str = data.xml;
data = str;
}
// code for Mozilla, Firefox, Opera, etc.
else {
var str = (new XMLSerializer()).serializeToString(data);
data = str;
}
}
//only takes strings!
$.template(name, data);
callback();
}
And here's what I don't like about it.
This doesn't work on Chrome
It seems like a lot of code just to load some template
I lost the ability to use $(document).ready(). I must now put all my code in this templateReady() method to be "template safe".
Is there a way around this?
Thanks,
Chi
Just load the template body as simple text and forget about putting it in a dummy <script> block. You can use $.tmpl(body, params) to populate the template and turn it into a string for appending to the DOM.
The whole thing with "not really script" <script> blocks is just a convenience useful in some situations.
edit — example:
$.get("/some/url/for/a/template", function(templateBody) {
var expandedTemplate = $.tmpl(templateBody, { param1: 0, param2: "Hello World" });
});
If the goal is to fetch a unique template each time you get data via ajax, then you might try fetching the template at the same time and include it in your data, that is if you have the luxury of modifying the returned object (anonymous object in .Net). Then you can store the template anywhere you want and you only need 1 ajax call for both the data and the template.
Refer here:
https://www.npmjs.com/package/jlate
use CDN:
<script src="https://cdn.jsdelivr.net/combine/npm/lodash,npm/jlate#0.0.2/jlate/JLate.min.js"></script>
HTML Code:
<body>
<div>
<jlate id="my_temp" src="template/jlate_title.html" type="template">
Loading...
</jlate>
</div>
</body>
Javascript:
$$("#my_temp").jlate({ title: "sample title"});