JQuery $.post is not working - javascript

This is my Index.cshtml file (I'm learning MVC .NET), and when I click on the Add button to add a new user, this user is not added when I go and check my Api.
I know that both the route (api/users) and the Json object are correct, and the script is being rendered.
I'am using Visual Studio 2017 for Mac and my Api service is Service Stack.
#model dynamic
 #{
ViewBag.Title = "Protein Tracker";
Layout = "../Shared/_Layout.cshtml";
}
#section scripts
{
<script type="text/javascript">
function AddNewUser(){
var goal = $('#goal').val();
var name = $('#name ').val();
$.post("api/users", { 'Name' : name, 'Goal' : goal });
}
</script>
}
<h2>Protein Tracker</h2>
<div>
<label for="select-user">Select a user</label>
<select id="select-uder"></select>
</div>
<hr /> <!-- horizontal rule -->
<div>
<h2>Add new user</h2>
<label for="name">Name</label>
<input id="name" type="text" /><br />
<label for="goal">Goal</label>
<input id="goal" type="text" /><br />
<input id="add-new-user-button" type="button" value="Add" onclick="AddNewUser()" />
</div>

Thank you for the help guys, I tried everything everyone suggested, but when I used the Chrome WebInspector (like #mythz suggested) I discovered that "$" was not defined, so I understood that my code was not being recognized as JQuery or something like that. And when I added the following line of code it worked as expected:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

Related

In this HTML file I want to call another HTML file

{%extends "layout.html"%}
{%block content%}
<form action="{{ url_for("plot")}}" method="post">
<label for="CompanyCode">Stock Symbol:</label>
<input type="text" id="CompanyCode" name="ccode" placeholder="Stock Symbol">
<label for="start_date">Start Date: </label>
<input type="date" id="start_date" name="start_date">
<label for="end_date">End Date:</label>
<input type="date" id="end_date" name="end_date">
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<script type="text/javascript" src="{{cdn_js | safe}}" integrity="sha384-T2yuo9Oe71Cz/I4X9Ac5+gpEa5a8PpJCDlqKYO0CfAuEszu1JrXLl8YugMqYe3sM" crossorigin="anonymous"></script>
<div class = "plot">
<h1> This is the plot page </h1>
</div>
</script>
{{script1 | safe}}
{{div1 | safe}}
1) <div data-include="C:/Users/saiyyam/Stocks_site/Demo/template/plotdata.html"></div>
2) <div class="xyz">
</div>
{%endblock%}
<script type="text/javascript">
$(function(){
$(class="xyz").load("plotdata.html");
});
</script>
I have tried using 2 methods but none of them worked would appreciate if you can help me out. The code above the two methods is plotting some graphs so that is no way related to importing files in HTML. And yes i hav used both the methods separately but they didn't work
If you want to just move to a new html page, then using javascript, you can add an onclick attribute to your button <button onclick="window.location.href='./layout.html'" type="submit">Submit</button> it might work im not sure just proposing another way :)
It works but not with this setup.. thank you CORS >:{
Check out my repl for an example since it only loads pages with same origin as it
function htmlLoader(path,element){
var xhr=new XMLHttpRequest()
xhr.open('GET',path,true)
xhr.send()
xhr.onload=function(){
element.innerHTML=xhr.response
console.log("Page Successfully Loaded from",path)
}
xhr.onerror=function(err){console.error("Either due to this being a sandbox(meaning CORS blocked) or the path itself is invalid/rejects returning the call, the request has FAILED")}
}
<input id="addPath" />
<button onclick="htmlLoader(document.getElementById('addPath').value,document.getElementById('placeHTML'))">Add HTML from Path</button>
<div id="placeHTML"></div>

Put method with Ajax (the script isn't triggered)

I am implementing Put method with Ajax:
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitPut').click( function () {
console.log("click");
var sendName = $('#name').val();
var sendDescription = $('#description').val();
$.ajax({
url: '/musicalstyle', //Your api url
type: 'PUT', //type is any HTTP method
data: {
name: sendName,
description: sendDescription,
}, //Data as js object
success: function () {
}
})
;
});
});
</script>
</head>
<body>
<form>
<label for="name">Nombre</label>
<input type="text" id="name" />
<label for="description">Descripción</label>
<input type="text" name="description" id="description"/>
<input id="submitPut" type="button" value="SubmitPut">
</form>
</body>
</html>
This form is working fine but when introduce it on real environment the script isn't called (my view in production environment is using Thymeleaf and Boostrap). It's like <button class="btn btn-primary" id="submitPut" type="button">Actualizar</button> isn't triggering the submitPut function.
Here form of production environment:
<form>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Nombre</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="name">
</div>
</div>
<div class="form-group row">
<label for="description" class="col-sm-2 col-form-label">Descripción</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="description">
</div>
</div>
<br>
<button class="btn btn-primary" id="submitPut" type="button">Actualizar</button>
</form>
How can I force to button call ajax function?
Thanks,
Your id of input is submit while you called onclick function on query, submitPut.
So,
<input id="submitPut" type="button" value="SubmitDelete"/>
#Biplove I have eddited my comment. Id of input is equal than name of onclick function.
After import JQuery with
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>window.jQuery || document.write('<script src="../js/jquery.slim.min.js"> <\/script>')</script><script src="../js/bootstrap.bundle.js"></script></body>
Ajax is executed.
My method Put in Controller should redirect to another view and seems to be redirecting. The Spring logs show:
2020-05-21 16:04:15.367 DEBUG 552 --- [nio-8182-exec-9] o.s.web.servlet.DispatcherServlet : PUT "/musicalstyle", parameters={masked}
2020-05-21 16:04:15.368 DEBUG 552 --- [nio-8182-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.musicnet.springboot.controller.SystemAdministratorController#updateStyle(Style, Model)
2020-05-21 16:04:15.558 DEBUG 552 --- [nio-8182-exec-9] o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/*' given [*/*]
2020-05-21 16:04:15.632 DEBUG 552 --- [nio-8182-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK
Here the style is updated so put method is working fine but the view isn't showed on browser. I suspect that Spring doesn't have any problem in order to redirect view, the problem is that ajax script isn't redirecting to the returned view.
How can I modify the ajax script to process the view returned by Spring?
Edit
In fact, I get the redirect putting in ajax script:
success: function () {
window.location.reload();
}

How to give custom validation error messages for HTML validations?

When I use default HTML validation it shows the default error messages which is not I want to show to my clients. I need to customize the message and give different massages for each validations such as min, max, type and require. For Example:
The field is required, The value does not match
Refer the tradition HTML Code:
<input type="text" required>
I want something like this:
<input type="text" validation="required|my_message,min:5|my_message">
It's totally possible with custom libraries in jQuery which I would suggest - https://github.com/aslamanver/abvalidate
Custom Message - jQuery Form Validation - abValidate.js
ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name"
Use this library by adding these CDNs
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- abValidate Library -->
<script type="text/javascript" src="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.min.js">
<link rel="stylesheet" href="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.css">
Initialize the library
$(document).ready(function () {
//.ab-form is your form class
$(".ab-form").abValidate();
});
There you go, now you can use your custom validation using jQuery abValidate library
<form class="ab-form" action="your_action_url">
<!-- Input and error message should be in a div class -->
<div class="my-form-group">
<input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name" class="ab-validation-i" />
<div class="error"></div>
</div><br>
<div class="my-form-group">
<input type="submit" name="submit" value="Submit">
</div>
</form>
Try this one, its better and tested:
HTML:
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
JAVASCRIPT:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
Demo:
http://jsfiddle.net/patelriki13/Sqq8e/

Typeahead doesn't work with Bootstrap 3

I cannot make it work. I don't have any error on the console. The list doesn't appear at all.
Here is my html code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/typeahead.jquery.js"></script>
<form method="POST" class="search-form" name="search-form">
<input id="keywords" name = "searchtext" type="text" class="search-input" placeholder="Enter your text..." autocomplete="off">
<button type="submit" class="search-submit">Search Now</button>
</form>
<script type="text/javascript">
$(function(){
// applied typeahead to the text input box
$('#keywords').typeahead({
name: 'keywords',
// data source
local: ['pattern recognition', 'supervised learning', 'support vector machines'],
// max item numbers list in the dropdown
limit: 10
});
});
</script>
The problem is that Bootstrap 3 does not include a typeahead library like 2.3 and earlier did. The typeahead.js library you are including works much differently, and there are some great examples on how to use it here and here.

jQuery exception with document.ready() - Object doesn't support this property or method

I'm trying to perform some simple validation, and I'm following some instructions in the book JavaScript & jQuery, The Missing Manual. My code is simply this:
<script src="~/Scripts/jquery-1.6.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<form> form code here </form>
<script>
$(document).ready(function() {
$('#vaporizerForm').validate();
});
</script>
And I'm getting this error:
Unhandled exception at line 1039, column 15 in /Scripts/jquery-1.6.2.js
0x800a01b6 - Microsoft JScript runtime error: Object doesn't support this property or method
If I remove the $(document).ready part, and just do this, it works:
<script>
$('#vaporizerForm').validate();
</script>
Any idea why the $(document).ready() part isn't working?
EDIT -- jQuery call stack and code
EDIT - Entire code in the view
#model IEnumerable<DistributorManagement.Models.Vaporizer>
#{
ViewBag.Title = "Vaporizer";
}
#{
var grid = new #WebGrid(
source: Model,
rowsPerPage: 10);
}
<script src="~/Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#vaporizerForm').validate();
});
</script>
<form action="#" method="post" name="vaporizerForm" id="vaporizerForm">
<div>
<label>Manufacturer</label>
<input name="manufacturer" type="text" class="required" />
<label>BuildDate</label>
<input name="buildDate" type="text" class="required date" />
<label>Rating</label>
<input name="rating" type="text" class="required number" />
</div>
<div>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
<br />
<h1>Vaporizer Info</h1>
<div class="webgrid-wrapper">
<div id="grid">
#grid.GetHtml(
tableStyle: "webgrid",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-rows",
columns: grid.Columns(
grid.Column("Id", "ID"),
grid.Column("Manufacturer"),
grid.Column("Status"),
grid.Column("BuildDate", "Build Date"),
grid.Column("Rating")))
</div>
</div>
I'll go for the obvious answer, are you sure the file at ~/Scripts/jQuery/jquery.validate.js is ok? It is acting like that file is empty, or broken.
To check if the file is ok, navigate to that directory observe the file and open it in the editor, does it have any content.
If you take out the document ready stuff you probably need the following code to see an error:
try {
$('#vaporizerForm').validate();
}
catch () {
alert('still have error');
}
Put your validation script before the <form>.
<script src="~/Scripts/jquery-1.6.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$('#vaporizeForm').validate();
});
</script>
<form> form code here </form>
Here is a fiddle as an example.
Try with this:
<script type="text/javascript" src="~/Scripts/jquery.validate.js"></script>
-- EDITED --
And put the $(document).ready(.......) in the bottom of your page.
This happens with some versions of IE, when your page is too long.... put it before the body !

Categories

Resources