I try to do a submit ajax with ASP .net and jquery but he never fire d«the event, I already try with this two examples and he never fire the event alert.
<form id="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m.VatNumber,new { #class = "form-control", #id="VatNumber"})
#Html.ValidationMessage("VatNumber")
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Check VAT" />
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#form').submit(function () {
alert("cheguei");
$.ajax({
url: '#Url.Action("CheckVat")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
VatNumber: $('#VatNumber').val(),
}),
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
return false;
});
});
$(function () {
$('#form').submit(function (event) {
alert("cheguei");
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function (data) {
// Optionally alert the user of success here...
}).fail(function (data) {
// Optionally alert the user of an error here...
});
});
});
</script>
I figure out : I have to include the scripts in the Head section and the problem is fixed.
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/bootstrap.min.css")
#*#Styles.Render("~/Content/css")*#
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-3.1.0.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</head>
Related
I have implemented the JQuery Autocomplete in the following format:
AddApplication.cshtml
#page
#model AddApplicationModel
#{
}
<div>
<form>
<div>
<input type="text" name="appName" placeholder="Enter Application Name">
<select asp-items="Model.ministryItems">
<option>Select Ministry</option>
</select>
</div>
<div>
<input type="text" name="url" id="url" placeholder="Search for a URL" autocomplete="on">
</div>
</form>
</div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#url").autocomplete({
source: function (request, response) {
console.log("in funct");
$.ajax({
url: "#Url.Action("GetURL","AddApplication")",
data: ({ term: request.term}),
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
Console.log("success");
response($.map(data, function (item) {
Console.log("response"+item)
return item;
}))
}
});
},
select: function (e, i) {
$("#url").val(i.item.val);
},
minLength: 0
}).focus(function () {
$(this).autocomplete("search");
});
});
</script>
When i type something into my textbox nothing happens at all. After some debugging i know for a fact that the function $("url").autocomplete is being called, but the success: function()data{} is not being hit
Backend razor code:
AddApplication.cshtml
[System.Web.Mvc.HttpGet]
public System.Web.Mvc.JsonResult GetURL(string term)
{
Console.WriteLine("===============IN GETURL====================");
System.Web.Mvc.JsonResult result = new System.Web.Mvc.JsonResult();
var list = (from c in db.Url
where c.UrlName.Contains(term)
select c.UrlName).ToList();
Console.WriteLine(list.Count());
result.Data = list;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
Console.WriteLine("---------"+result.Data.ToString());
return result;
}
GetURL I have tested this function with calling it from OnGet just to see if it was actually working, and it is successfully querying the data, im not 100% sure if its properly returning the JSONResult. However it is not being called by autocomplete.
I am not sure if this is a path issue, i don't believe it is as i had that resolved beforehand
I have also tried using the following JQuery snippet, and it yields the same results
<script type="text/javascript">
$(function () {
console.log("function");
$("#url").autocomplete({
source: "#Url.Action("GetURL","AddApplication")",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
console.log("-----"+ui.item);
$("#url").val(ui.item.value);
$("form").submit();
}
}
});
});
</script>
Response tab for textbox search
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title> - LookupTool</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="/css/site.css" />
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=dLGP40S79Xnx6GqUthRF6NWvjvhQ1nOvdVSwaNcgG18"></script>
</head>
<body>
<!-- <nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a asp-page="/Index" class="navbar-brand">LookupTool</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-page="/Index">Home</a></li>
<li><a asp-page="/About">About</a></li>
<li><a asp-page="/Contact">Contact</a></li>
</ul>
</div>
</div>
</nav> -->
<div class="container-fluid body-content">
<div style="margin-left: 5%; margin-right: 5%">
<div>
<form>
<div>
<input type="text" name="appName" placeholder="Enter Application Name">
<select>
<option>Select Ministry</option>
<options> - cant display this information
</select>
</div>
<div>
<input type="text" name="url" id="url" placeholder="Search for a URL" autocomplete="on">
</div>
</form>
</div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#url").autocomplete({
source: function (request, response) {
console.log("in funct");
$.ajax({
url: "/AddApplication?action=GetURL&controller=AddApplication",
data: ({ term: request.term}),
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
Console.log("success");
response($.map(data, function (item) {
Console.log("response"+item)
return item;
}))
}
});
},
select: function (e, i) {
$("#url").val(i.item.val);
},
minLength: 0
}).focus(function () {
$(this).autocomplete("search");
});
});
</script>
<hr />
<footer>
footer
</footer>
</div>
</div>
</body>
</html>
Modify the ajax request to correctly include the query string parameters:
$.ajax({
url: "AddApplication/GetURL",
data: ({ term: request.term}),
dataType: "json",
type: "GET",
success: function (data) {
response($.map(data, function (item) {
return item;
Console.log("response"+item)
}))
}
});
I was able to finally get it working after more searches. Adding the anti forgery token may have been the underlying issue as i did not have it added before. Notice the URL, according to multiple sources this is the correct way to reference a URL in razor.
Although its working for some reason only the completed function is called, it never goes into success. This isnt causing issues at the moment.
AddApplication.cshtml
<script>
$(document).ready(function(){
$("#UrlQueBtn").click(function(e)
{
e.preventDefault();
var url = $('#urlSelect').val();
console.log(url);
$.ajax({
url: "AddApplication?handler=AddUrlToQue",
type: "POST",
dataType: "json",
data: { urlSelect: url },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
alert("success");
},
complete: function () {
alert("complete")
},
failure: function () {
alert("failure");
}
})
});
});
</script>
Need to add the anti forgery token to startup class
startup.cs
under ConfigureServices
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
This is simple but my JS is a bit rusty..
I am trying to trigger a get request by pressing a JQuery Mobile element.
I can see the button but failing to do an actual Get Request
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<p><input type="checkbox" data-role="flipswitch" name="flip-checkbox-1" id="generator_button"></p>
</form>
</body>
<script>
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
</script>
Please, note: in your markup there is a Flip switch of type checkbox, not a button, so I believe you may better check the state of the underlying checkbox instead of stick to a tap event.
Reference: jQuery Mobile Flip switch
Moreover, you it would be nice to provide a JQM page structure to the whole stuff.
Here is an example:
function sendRequest() {
$.ajax({
'url': '192.168.8.110:5000/generator_on',
'type': 'GET',
'success': function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
}
$(document).on("change", "#generator_button", function() {
var state = $("#generator_button").prop("checked");
if (state === true) {
// Flip switch is on
console.log("Request sent.");
//sendRequest(); // uncomment
} else {
// Flip switch is off
//...endpoint _off
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="page-one" data-role="page">
<div data-role="header" data-position="fixed">
<h1>Header</h1>
</div>
<div role="main" class="ui-content">
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<input type="checkbox" data-role="flipswitch" name="generator_button" id="generator_button">
</div>
<div data-role="footer" data-position="fixed">
<h1>Footer</h1>
</div>
</div>
</body>
</html>
You are missing }); on last line of your javascript.
Your javascript code should look like this
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
});
Ok, so I had to change the url to: 'http://192.168.8.110:5000/generator_on and tested it on a browser without an adblock I mentioned to make it work!
I tried to do that when I'm pressing the turn on button it calls the turnon() function which opens the JSON file named light.json and writes there {"light" : "on"} but it doesn't work for me and I don't know why. Can anybody help me?
<?php
$light = $_GET['light'];
$file = fopen("light.json", "w") or die("can't open file");
if($light == "on") {
fwrite($file, '{"light": "on"}');
}
else if ($light == "off") {
fwrite($file, '{"light": "off"}');
}
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LED for ESP8266</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
</head>
<body>
<div class="row" style="margin-top: 20px;">
<div class="col-md-8 col-md-offset-2">
<form>
<input type="button" id="StartButton" value="Turn On" onClick="turnOn()">
</form>
<!--<button onclick="turnOn()">Turn On</button>
<button onclick="turnOff()">Turn Off</button>-->
<div class="light-status well" style="margin-top: 5px; text-align:center">
<script type="text/javascript">
function turnOn() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://192.168.1.108/test/light.json",
data: {"light": "on"},
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
}
</script>
</div>
</div>
</div>
</body>
</html>
Thanks!
You use POST method to send AJAX request, but try to get it by using GET method from PHP.
Simply change AJAX method from POST to GET can solve the problem.
You are sending an AJAX request directly to light.json instead of PHP page. Moreover you're using type: "POST" on AJAX but reading from $_GET on PHP.
If the PHP script is on the same page, you won't need to specify url in your AJAX request
<?php
if (isset($_GET['light'])) {
$light = $_GET['light'];
$file = fopen("light.json", "w") or die("can't open file");
if($light == "on") {
fwrite($file, '{"light": "on"}');
} else if ($light == "off") {
fwrite($file, '{"light": "off"}');
}
echo fread($file, filesize($file));
}
?>
$.ajax({
type: "GET",
data: {"light": "on"},
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
Be sure that light.json is in the same directory, otherwise specify the correct path on fopen().
I try to access login service from some web service for user validation directly to html page using jquery, but it seems not working, even when I access the web service with browser the web service work perfectly. Here is the html code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script type="text/javascript">
$("#login").click(function(){
var username=$("#username").val();
var password=$("#password").val();
var dataString="username="+username+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "some url here",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data.success=="true")
{
localStorage.login="true";
localStorage.username=username;
window.location.href = "index.html";
}
else if(data.success="false")
{
alert("Login error");
$("#login").html('Login');
}
}
});
} return false;
});
</script>
</head>
<body>
<div class="bar bar-header bar-positive" style="margin-bottom:80px;">
Home
<h1 class="title">Login</h1>
</div>
<br/><br/>
<input id="username" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="login">Login</button>
</body>
Even the "beforeSend" code is not working, I mean when I click on Login button the text on it doesn't change to Connecting. How can I make it work?
Replace
$.trim(email).length
To
$.trim(username).length
One more problem in code in success function;
/* Now */
}else if(data.success="false"){
/* should be == because here we are comparing not assigning */
}else if(data.success=="false"){
/* OR we can remove if part completely because we don't need any comparison if not success */
}else{
One more thing if we are getting the response as true or false i don't thing it would be string value, it would be Boolean so update code for success function like following:
success: function(data){
if(data.success){
localStorage.login = "true";
localStorage.username = username;
window.location.href = "index.html";
}else{
alert("Login error");
$("#login").html('Login');
}
}
And one more problem your code won't execute because here you are trying to reference element that not loaded that is login button;
Use following code with all fixes;
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.css">
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/1.2.4/css/ionic.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.2.min.js"></script>
<script type="text/javascript">
/* code wrapped in $(function(){ to make sure the all elemtents loaded before we make use them */
$(function(){
$("#login").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var dataString = "username=" + username + "&password=" + password + "&login=";
if($.trim(password).length > 0 & $.trim(password).length > 0){
$.ajax({
type: "POST",
url: "some url here",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){
$("#login").html('Connecting...');
},
success: function(data){
if(data.success){
localStorage.login = "true";
localStorage.username = username;
window.location.href = "index.html";
}else{
alert("Login error");
$("#login").html('Login');
}
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="bar bar-header bar-positive" style="margin-bottom:80px;">
Home
<h1 class="title">Login</h1>
</div>
<br/><br/>
<input id="username" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="login">Login</button>
</body>
</html>
email is not defined before
$.trim(email)
Change it to and the connecting... will appear
$.trim(username)
change $.trim(email).length
To
$.trim(username).length
So after I start my server, go to my local host, and either click the sign up or login button, I get an error popping up in my console saying
"Uncaught ReferenceError: Handlebars is not defined" I don't know what exactly the issue is. I tried re- npm installing it because maybe I didn't have it installed. The error that immediately pops up in the console before I actually click the buttons is this:
http://s23.postimg.org/bgbykf3qh/Screen_Shot_2015_12_16_at_10_02_14_AM.png
I also thought maybe it was because I put the script in the wrong section of my HTML file. However, I keep getting the same error.
Here is what my index.html file looks like.
<html>
<head>
<title>Wishes Project</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css">
<link rel="stylesheet" type="text/css" href="style.css">
<link href='https://fonts.googleapis.com/css?family=Anton' rel='stylesheet' type='text/css'>
</head>
<body>
<h1>Wish List</h1>
<button id="sign-up">Sign Up</button><br>
<button id="login">Log In</button><br>
<template id="status-template">
<h3 id="status"></h3>
</template>
<div id="form-container"></div>
<!-- LOGIN ===================== -->
<template id="login-template">
<div id="login-container" data-id="{{_id}}">
<input type="text" id="username" placeholder="username"/><br>
<input type="text" id="password" placeholder="password"/><br>
<button id="login-button" data-id="{{_id}}">Log In!</button>
</div>
</template>
<!-- NEW USER ===================== -->
<template id="signup-template">
<div id="signup-container" data-id="{{_id}}">
<input type-"text" id="username" placeholder="username"/></br>
<input type="text" id="password" placeholder="password"/></br>
<input type="text" data-id="{{_id}}">Register!</button>
</div>
</template>
<!-- NEW WISH ======================= -->
<template id="new-wish-template">
<div id="new_wish-container" data-id="{{_id}}">
<input type="text" id="wish" placeholder="make a wish"/><br>
<button id="make-wish" data-id="{{_id}}">Create Wish!</button>
</div>
</template>
<button id="logout">Logout</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0 4/handlebars.js"></script>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.0.4/js.cookie.js"></script>
</body>
</html>
Here is what my app.js file looks like.
console.log('app.js');
$(function() {
$('#sign-up').click(signUpForm);
$('#login').click(loginForm);
$('#logout').click(delCookie).hide();
if( Cookies.get('loggedinId') != undefined ) {
wishForm();
};
});
var formContainer = $('#form-container');
//LOGIN ==============================
var loginForm = function() {
console.log('showing login form');
$('#sign-up').hide();
$('#login').hide();
var template = Handlebars.compile($('#login-template').html());
formContainer.append(template);
$('#login-button').click(function() {
console.log('clicked');
loginPost()
});
};
var loginPost = function() {
user = {
username: $('#username').val(),
password: $('#password').val(),
};
$.ajax({
url: 'http://localhost:3000/login',
method: "POST",
dataType: 'json',
data: user
}).done(function(data) {
console.log(data.username+"login successful");
user = Cookies.get("loggedinId");
wishForm()
});
};
//LOG OUT =========================
var delCookie = function() {
Cookies.remove('loggedinId');
loginForm();
};
//NEW USER =========================
var signUpForm = function() {
console.log('showing sign up form');
$('#sign-up').hide();
var template = Handlebars.compile($('#signup-template').html());
formContainer.append(template);
$('#register').click(function(){
console.log('clicked register');
newUser();
});
};
var newUser = function() {
user = {
username: $('#username').val(),
password: $('#password').val(),
};
console.log(user);
$.ajax({
url: "http://localhost:3000/users",
method: "POST",
data: user
}).done(function(data){
wishForm();
});
user = Cookies.get(user.username);
};
var wishForm = function() {
console.log('showing wish form');
$('#sign-up').hide();
$('#login').hide();
$('#logout').show();
formContainer.empty();
var template = Handlebars.compile($('#new-wish-template').html());
formContainer.append(template);
$('#make-wish').click(function() {
console.log('clicked make wish');
newWish();
});
};
var newWish = function() {
console.log('showing wish form');
var wish = {
content: $('#wish').
Can anybody help? Thank you.
Typo.
Try:
https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.js
Instead of:
https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0 4/handlebars.js
You are loading .js which path is error 404. Do:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.0.4/js.cookie.js"></script>
More information about Handlebars CDN