What I'm trying to do:
I made an alert function by spring which gives alert to user when the predetermined condition is fullfilled. This functions works well on Spring.
User can set several alerts on their own.
So when User presses "start alert" button in html, javascript sends get request using ajax depending on "idx" of alert on html.
Problem :
Seems like function is not working well on browser.
I did debug by using F12, I found out that Javascript is not getting any "idx" value..
So Nothing happens when I try to get alert.
All I wanna do is request by Alert id when button is pressed.
Here are my full code.
Controller
#GetMapping("/alerts/{id}")
#ResponseBody
public void AlertUser(#PathVariable Long id) {
alertService.AlertUser(id);
}
Service
public void AlertUser(Long id) {
Alert alert = alertRepository.findById(id).orElseThrow(() -> new NoSuchElementException());
double SetPrice = alert.getPrice();
String ticker = alert.getTicker();
JSONParser jsonParser = new JSONParser();
final NotificationRequest build = NotificationRequest.builder()
.title(ticker + " alert")
.message(SetPrice + "broke down")
.token(notificationService.getToken(userDetailService.returnUser().getEmail()))
.build();
try {
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint();
Session session = clientEndPoint.connect(new URI("wss://ws.coincap.io/prices?assets=" + ticker));
WebsocketClientEndpoint.MessageHandler handler = new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) throws ParseException, IOException {
Object obj = jsonParser.parse(message);
JSONObject jsonObject = (JSONObject) obj;
double price = Double.parseDouble(jsonObject.get(ticker).toString());
System.out.println("가격 : " + price);
if (price < SetPrice) {
System.out.println("끝");
notificationService.sendNotification(build);
session.close();
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
}
}
};
clientEndPoint.addMessageHandler(handler);
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
}
**alert.mustache : {{#alerts}} ~ {{/alerts}} part is where problem occurs **
{{>layout/header}}
<form method="post" action="submitform" id="tickerSubmit">
<select name="contact" id="contact">
{{#tickers}}
<option value="{{.}}">{{.}}</option>
{{/tickers}}
</select>
<!-- <button type="submit" name="submit">Choose Ticker</button>-->
</form>
<div>
<input type="number" id = "price" placeholder="하한 금액을 입력하세요">
<input type="number" id = "percentage" placeholder="하한 퍼센트를 입력하세요">
<button type="button" class="btn btn-primary" id="alert-save-btn">알림 등록</button>
</div>
{{#alerts}}
<tr>
<div id = "idx">{{id}}</div>
<td><input type="submit" value="알림시작" id="alert-start"/></td>
<td>티커 : {{ticker}}</td>
<td>가격 : {{price}}</td>
</tr>
{{/alerts}}
<script src="https://www.gstatic.com/firebasejs/5.9.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.2/firebase-messaging.js"></script>
<script src="/js/app/notification.js"></script>
{{>layout/footer}}
part of index.js encrypted in layout/footer
$('#alert-start').on('click', function() {
_this.alertStart();
});
},
alertStart : function() {
var idx = $('#idx').val();
$.ajax({
type: 'GET',
url: '/alerts/'+idx,
}).done(function() {
alert('알림이 시작됩니다.');
}).fail(function (error) {
alert(JSON.stringify('이거' + error));
});
},
Thanks in advance. any help or tip would be very helpful..
Related
I'm currently trying to write a mailto form which has the body already created. For the moment I'm keeping it simple and trying to just put an email, address and name into the body of the email to be sent. When I do this it returns the error
System.InvalidOperationException: Unexpected new line
Here's the HTML:
<form method='post' enctype="text/plain">
<b>Name:</b><br>
<input type="text" name="personsName" id="personsName"><br>
<b>E-mail:</b><br>
<input type="text" name="mail" id ="mail"><br>
<b>Address:</b><br>
<input type="text" name="address" id ="address"><br>
<input type="submit" value="Send" id="send">
</form>
And here's the relevant JavaScript:
$(function(){ EGf20a6658.Init(); });
var EGf20a6658 = {
Init: function() {
if (typeof(OEConfEGf20a6658) === undefined) return;
var allElements = OEConfEGf20a6658;
for(var ID in allElements) {
var $el = $('#'+ID); // The element's main <div> tag
var properties = allElements[ID]; // element's available properties for JS
this.InitElement(ID, $el, properties);
}
},
InitElement: function(ID, $el, properties) {
var name = $('#personsName').val();
var mail = $('#mail').val();
var address = $('#address').val();
var message = "Hey " + " How are you? You still at " + " with the email " + "?";
var mailtolink = 'mailto:me#domain.com?subject=Regret Permission Form&body=' + encodeURIComponent(message);
$( '#send' ).on( 'click', function(event) {
$(this).attr('href', mailtolink);
});
}
};
I noticed that the error always returns the value for name.
Here's the full error code:
500 - Unexpected new line: k [CRLF].
System.InvalidOperationException: Unexpected new line: k
[CRLF].
at HttpServer.Tools.StringReader.ReadToEnd(String delimiters)
at HttpServer.Tools.UrlParser.Parse2(ITextReader reader, Boolean urlDecode)
at HttpServer.Tools.UrlParser.Parse2(String queryString, Boolean urlDecode)
at HttpServer.RequestEventArgs.FixPostData(IRequest request)
at HttpServer.RequestEventArgs..ctor(IHttpContext context, IRequest request, IResponse response)
at HttpServer.HttpContext.OnRequest(Object sender, FactoryRequestEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at HttpServer.Messages.MessageFactoryContext.OnMessageComplete(Object sender, EventArgs e)
at System.EventHandler.Invoke(Object sender, EventArgs e)
at HttpServer.Messages.Parser.HttpParser.OnComplete()
at HttpServer.Messages.Parser.HttpParser.GetBody()
at HttpServer.Messages.Parser.HttpParser.Parse(Byte[] buffer, Int32 offset, Int32 count)
at HttpServer.HttpContext.ParseBuffer(Int32 bytesLeft)
at HttpServer.HttpContext.OnReceive(IAsyncResult ar)
So, I managed to fix the issue. I realized I had made the issue too complicated and fixed it using some simple code from Aitor in this Anwser . I basically just rewrote it to fit the way Aitor had his laid out.
I want to enter values to my table "Categories" so as not to reload the page and keep the user always in sight, for this I want to use Ajax + Jquery, the exercise seems simple but it has me crazy, you enter category names in an input and you want to show a <div> for your confirmation (success) or failure (danger) depending on the case, something like that ....
The problem is that my Javascript code does not do anything, it is not even entering the Create method
I enclose my view create.html:
<head>
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
</head>
<body>
<div id="div-alerta">
<label id="mensaje-alerta"></label>
</div>
<hr />
#Html.LabelFor(model => model.v_Nombre, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input class="form-control" type="text" id="txtNombre" />
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Crear" id="btnCrearCategoria" class="btn btn-outline-success btn-lg" />
</div>
</div>
</body>
</html>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
$(function () {
$("#btnCrearCategoria").click(function () {
var url = "#Url.Action("Create", "Categorias")";
var nombre = $("#txtNombre").val();
var data = { v_Nombre: nombre };
$.post(url, data).done(function (data) {
if (data.Ok) {
$("#div-alerta").removeClass("alert-danger").addClass("alert-success").slideDown(100);
}
else {
$("div-alerta").removeClass("alert-success").addClass("alert-danger").slideDown(100);
}
$("#mensaje-alerta").html(data.Mensaje)
})
})
})
</script>
}
This is my object category.cs:
public class Categoria
{
[Key]
public int Kn_CodigoCategoria { get; set; }
[Required(ErrorMessage = "El campo {0} es obligatorio")]
[MaxLength(40, ErrorMessage = "El campo {0} debe tener un máximo de {0} caracteres")]
[Column(TypeName = "VARCHAR")]
[Index("Categoria_v_Nombre_Index", IsUnique = true)]
[Display(Name = "Nombre Categoria")]
public string v_Nombre { get; set; }
}
and this is my create method that returns a Json:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create(Categoria categoria)
{
var resultado = new BaseRespuesta();
try
{
db.Categorias.Add(categoria);
db.SaveChanges();
resultado.Mensaje = "Categoria creada correctamente";
resultado.Ok = true;
}
catch (Exception ex)
{
resultado.Mensaje = ex.Message;
resultado.Ok = false;
}
return Json(resultado);
}
I occupy a class called BaseResponse to see messages of success or failure of my operation:
public class BaseRespuesta
{
public bool Ok { get; set; }
public string Mensaje { get; set; }
}
My expected behavior: When entering a value in the text box, show me a div (success or failure) with the corresponding message
My behavior obtained: entering a value in the input does nothing
what am I doing wrong? I'm missing something in my code? it's the first time I work with Ajax calls ... should I load a partial view? any help for me?
It looks like this might be wrong:
var url = "#Url.Action("Create", "Categorias")";
To pass in the string "Categorias" to the action "Create", it would be something like the following where you would create an 'anonymous' type. Maybe try:
var url = "#Url.Action("Create", new { categoria = "Categorias"})";
You have double quotes that aren't being escaped:
<script>
$(function () {
$("#btnCrearCategoria").click(function () {
**var url = "#Url.Action("Create", "Categorias")";**
var nombre = $("#txtNombre").val();
var data = {
v_Nombre: nombre
};
$.post(url, data).done(function (data) {
if (data.Ok) {
$("#div-alerta").removeClass("alert-danger").addClass("alert-success").slideDown(
100);
} else {
$("div-alerta").removeClass("alert-success").addClass("alert-danger").slideDown(
100);
}
$("#mensaje-alerta").html(data.Mensaje)
})
})
})
</script>
You need to either escape them or use single quotes around the whole string:
var url = '#Url.Action("Create", "Categorias")';
or
var url = "#Url.Action(\"Create\", \"Categorias\")";
The second option can get tricky trying to manage all of the "\" backslashes so I would recommend the first option.
The element [ValidateAntiForgeryToken] as decoration of my JsonResult blocked my Javascript action, eliminating this decoration and leaving only [HttpPost] worked for me !!
I am trying to get data from database when i click button.
I have one dropdownlist,one textbox and one button.
when i click button it should get input value from drop down list and return one value from database and put it into text box.
output window image
dropdown has account number.
this is my ajax code its inside of head tag
<script type="text/javascript">
$(document).ready(function()
{
alert("Entering");
$('#btnBalance').click(function(){
var accountNo = $('#DropDownListFromWhichAccount').val();
$.ajax({
url:'BalanceService.asmx/getBalance',
data:{acc:accountNo},
method:'post',
dataType: 'xml',
success:function(data)
{
console.log(data);
var jqueryXml=$(data);
$('#txtBalance').val(jqueryXml.find('balance').text())
//$('#txtBalance').val("ok")
alert(jqueryXml.find('balance').text());
},
error:function(err)
{
alert(err);
}
})
})
});
</script>
html code:
<div class="row content-padding-top">
<div class="col-lg-3">
<label for="DropDownListFromWhichAccount" class="content-label control-label">Debit (From)</label>
</div>
<div class="col-lg-3">
<asp:DropDownList ID="DropDownListFromWhichAccount" runat="server" class="form-control text-box-border" >
<asp:ListItem>Cash</asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-lg-2">
<asp:TextBox ID="txtBalance" runat="server" class="form-control text-box-border" placeholder="Balance" ></asp:TextBox>
</div>
<div class="col-lg-1">
<asp:Button ID="btnBalance" type="button" runat="server" class="btn btn-default" Text="Check" />
</div>
</div>
asmx file:
namespace NibrassProject
{
/// <summary>
/// Summary description for BalanceService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class BalanceService : System.Web.Services.WebService
{
[WebMethod]
public BalanceChecking getBalance(string accountNo)
{
BalanceChecking bc = new BalanceChecking();
bc.balance=bc.checkBalance(accountNo);
bc.balance = "faisal";
return bc;
}
}
}
BalanceChecking.cs file
namespace NibrassProject
{
public class BalanceChecking
{
public string balance { get; set; }
string cs = ConfigurationManager.ConnectionStrings["Nibrass_DBConnectionString"].ConnectionString;
public string checkBalance(string acc)
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Balance FROM Account_Balance_tb WHERE Account_Card_Number=" + acc + " ORDER BY Id DESC";
// cmd.Parameters.AddWithValue("#Account_Number",accountNo);
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
balance = rd["Balance"].ToString();
break;
}
rd.Close();
}
return balance;
}
}
Error message:
uncaught exception: out of memory
This is my C# code for Jumbling the data.
protected void Button1_Click1(object sender, EventArgs e)
{
ScrambleData("dsafdsfsd");
}
public static string ScrambleData(string data)
{
//string BaseAddress = "http://localhost/";
string BaseAddress = "http://abcd/"; //Calling by Computer Name.
string uri = "ScramblerService/Scrambler?value=" + data;
string CompleteRequestURL = BaseAddress + uri;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(CompleteRequestURL);
//webrequest.Method = "GET";
webrequest.ContentType = "application/json";
string result;
using (WebResponse response = webrequest.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
return result;
}
}
}
This is my Java Script code for User selected Data.
<script type="text/javascript">
function disp()
{
var txtArea = document.getElementById('MainContent_TextArea1');
var start = txtArea.selectionStart;
var finish = txtArea.selectionEnd;
var sel = txtArea.value.substring(start, finish);
document.getElementById("MainContent_Textarea2").value = sel;
}
</script>
<div>
<asp:TextBox id="TextArea1" runat="server" TextMode="MultiLine" CssClass="form-control" Height="300px"></asp:TextBox>
<INPUT type="button" onclick= "disp()" visible="true" value="Show" class="btn btn-primary"/>
<input id="Textarea2" runat="server" type="text"/>
</div>
Here I am trying to display the user selected data. While displaying the user selected data I need to jumble the words and has to display in Text area2. But I need to call this action through "Show" button Only.
Any Help Please..???
Any Suggestions Please...???
You are referencing an id of "MainContent_Textarea2" but you don't have any element with that ID. You do, however, have one called "Textarea2", have you tried using that?
document.getElementById("Textarea2").value = sel;
<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
Hi I have this code but I cant do postback for it, im not sure how to?
is it:
<script type="text/javascript">
function CallServer() {
__doPostBack('not sure what goes here','or here');
}
</script>
Then:
<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/CallServer()/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
My other script:
<script type="text/javascript">
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
</script>
EDIT:
On the server side i dynamically add a div to my page with content from my database for each content there is a new div will be added, each div is then refrenced with idWallPosting (so i can call my delete function)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.IO;
public partial class UserProfileWall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//btn.Visible = false;
string theUserId = Session["UserID"].ToString();
PopulateWallPosts(theUserId);
}
private void PopulateWallPosts(string userId)
{
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting, wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
{
//("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
using (OdbcDataReader reader = cmd.ExecuteReader())
{
test1.Controls.Clear();
while (reader.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.Attributes["class"] = "test";
div.ID = String.Format("{0}", reader.GetString(0));
// this line is responsible, problem here and my sqlsntax, im trying to set the SELECT idWallPosting for the div ID
Image img = new Image();
img.ImageUrl = String.Format("{0}", reader.GetString(2));
img.AlternateText = "Test image";
div.Controls.Add(img);
div.Controls.Add(ParseControl(String.Format("   " + "{0}", reader.GetString(1))));
div.Attributes.Add("onclick", "return confirm_delete();");
div.Style["clear"] = "both";
test1.Controls.Add(div);
}
}
}
}
}
//protected void btnDelete_Click(object sender, EventArgs e)
//{
// string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
// string[] idFragments = id.Split('_');
// id = idFragments[idFragments.Length - 1];
// //serverside code if confirm was pressed.
// using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
// {
// cn.Open();
// using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
// {
// cmd.ExecuteNonQuery();
// }
// }
// //PopulateWallPosts();
//}
protected void Button1_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
{
cmd.ExecuteNonQuery();
}
}
PopulateWallPosts(theUserId);
}
protected void btn_Click(object sender, EventArgs e)
{
string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
string[] idFragments = id.Split('_');
id = idFragments[idFragments.Length - 1];
//serverside code if confirm was pressed.
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
{
cmd.ExecuteNonQuery();
}
}
//PopulateWallPosts();
}
}
On my asp.net html side i have:
<script type="text/javascript">
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
</script>
<p>
<asp:Button ID="btn" OnClientClick="return confirm_delete();" runat="server"
CssClass="Btn" Text="delete" onclick="btn_Click"/>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"
Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px"
onclick="Button1_Click" />
</p>
<p>
</p>
<style type="text/css">
img {border-width:0px; width:100px; height:100px;}
</style>
<div id="test1" runat="server" />
</div>
</asp:Content>
If you notice in my server side code I added this line:
div.Attributes.Add("onclick", "return confirm_delete();")
This works any time I click on my div the confirm_delete is called.
What I was trying to do with my asp.net button was when the div was clicked I could then call the onclick btnDelete_click.
OnClientClick="return confirm_delete();"
That's it...
Edit: __doPostBack works also...
OnClientClick="if(confirm('delete?'))__doPostBack('btn',''); else return false;"
If you really are wanting to manually call __doPostBack(), the first parameter is the .NET generated name for the control. This can be gotten on the server side using Control.ClientID. The second parameter is any extra data that should be passed along in the request. Most of the time I see this field is an empty string.
__doPostBack('ctl100$controlName$id','');
The controlName is the .NET class name of the control I believe, id is the ID you gave the control. To be sure, view the source of the page after it has been rendered in the browser and search for calls to __doPostBack and see how they are formatted.
By a postback in this case do you want to just refresh the page? If so then it would just be:
location.reload();
in your case:
<script type="text/javascript">
function CallServer()
{
location.reload();
}
</script>
Demo (A button click prompts the user to confirm - if they choose Yes, a post back occurs)
See demo here!
One method, not the best for sure:
Add a button into an update panel and set it invisble.
Then call click() method of the button.
Somthing like this:
document.getElementById('button').click();