I need to pass in some values to my function
I want the function to run when I press ENTER KEY in PHP
the function is update()
This is my PHP
echo '<input type="text" size="23" id= n'.$row["ContactID"].'
class = "name" placeholder="Contact Name"
value="'.$row["Name"].'
onkeydown="if (event.keyCode == 13) updatename(this,'.$row["ContactID"].') ">';
my javascript
function updatename(item, cid)
{
var varname = $(item).val();
var originaltext = $(item).val();
$.ajax({
url: 'changeContact.php',
type: 'POST',
data:{
varname: varname
},
success:function (data) {
if (data == '1')
{
$("#status")
.addClass("success")
.html("Data saved successfully")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
else
{
$("#status")
.addClass("error")
.html("An error occured, the data could not be saved")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
}
});
}
Why does it don't seem to be working? Nothing have been send to my database, even I change to a simple alert, nothing appear
How can I improve it?
Probably because your HTML is invalid.
...
value="'.$row["Name"].' <--------- " is missing
onkeydown="if (eve...
<input type="text" id="your id" onkeypress="MAGIC(event);" />
function MAGIC(event){
$("#id").keyup(function(event){
if(event.keyCode == 13){
//your code to be executed
}
}
Related
I'm making a dynamic search in jsp.
It begins with Filter.java mapped as filter.json . Using two different methods I correctly save on 2 ArrayList the result of the search on SQL.
This is Filter.java
class Filter() {
...
ArrayList<News> newsListCat = new ArrayList<>();
ArrayList<News> newsListAut = new ArrayList<>();
NewsFactory newsFactory = NewsFactory.getInstance();
String str = request.getParameter("q");
if (str.equals("search")) {
String toSearch = request.getParameter("toSearch");
if (toSearch == null) {
newsListCat = newsFactory.getNews();
} else {
newsListCat = newsFactory.searchNewsbyCat(toSearch);
newsListAut = newsFactory.searchNewsbyAut(toSearch);
//System.out.println(newsListAut);
}
}
request.setAttribute("newsListCat", newsListCat);
request.setAttribute("newsListAut", newsListAut);
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
request.getRequestDispatcher("data.jsp").forward(request, response);
...
}
It send the request in data.jsp that manage json array
<json:array>
<c:forEach var="news" items="${newsListAut}">
<json:object>
<json:property name="type" value="author"/>
<json:property name="newsID" value="${news.getID()}"/>
<json:property name="authorID" value="${news.getAuthor().getID()}"/>
<json:property name="name" value="${news.getAuthor().getName()}"/>
<json:property name="surname" value="${news.getAuthor().getSurname()}"/>
</json:object>
</c:forEach>
<c:forEach var="news" items="${newsListCat}">
<json:object>
<json:property name="type" value="category"/>
<json:property name="authorID" value="${news.getAuthor().getID()}"/>
<json:property name="name" value="${news.getAuthor().getName()}"/>
<json:property name="surname" value="${news.getAuthor().getSurname()}"/>
</json:object>
</c:forEach>
In the end search.js should run the request creating dynamically an unordered list with the result of the query.
The response of request is right, but the jsp page doesn't do anything.
search.js
function stateSuccess(data) {
var ResultCat = $("newsListCat");
$(ResultCat).empty();
var ResultAut = $("newsListAut");
$(ResultAut).empty();
for (var instance in data) {
if (data[instance].type === "category") {
$(ResultCat).append("<li><a href='notizie.html?cat=" + data[instance].category + "'>" + data[instance].category + "</a></li>");
} else if (data[instance].type === "author")
$(ResultAut).append("<a href='profilo.html?id=" + data[instance].authorID + "}'><li>" + data[instance].name + " " + data[instance].surname + "</li></a>");
}
}
function stateFailure(data, state) {
console.log(state);
}
$(document).ready(function () {
$("#search").keyup(function (event) {
//$("input").css("background-color", "rgba(255, 0, 0, 0.8)");
$.ajax({
url: "filter.json",
data: {
q: "search",
toSearch: event.target.value
},
dataType: 'json',
success: function (data, state) {
stateSuccess(data);
},
error: function (data, state) {
stateFailure(data, state);
}
});
});
});
Am I doing anything wrong? I think so but don't know what.
This is how the search request result
By the time you click "search" the jsp page is loaded and is empty.
When you click search, ajax call gets data for you, but the jsp page is not loaded and is still empty.
Use your stateSuccess function to put data in jsp page.
I have written the following code but its not working. Can you please help me.
Though these solutions are available everywhere but still the code is not working.
<div align="center">Registration Form</div>
<script type="text/javascript">
function validate()
{
var name = document.myform.name.value;
var password = document.myform.password.value;
var email = document.myform.email.value;
var mobile = document.myform.mobile.value;
if(name.equals(""))
{
alert("Enter name");
return false;
}
else if(password.equals(""))
{
alert("Enter password");
return false;
}
else if(email.equals(""))
{
alert("Enter email-id");
return false;
}
else if(mobile.equals(""))
{
alert("Enter mobile no.");
return false;
}
else
{
alert("Submitted");
return true;
}
}
</script>
<body>
<form name ="myform" method="post" onsubmit = "return validate()">
JS String does not have method/prototype .equals().
Seems like you have mistaken with Java's String#equals(). Replace your code name.equals("") with name === "" instead or just name.length === 0 and so on for the rest.
For debugging purpose keep open developer console open, from browser press F12, there you will get those errors.
I am trying to take the inputed value from here:
index.html
<form name="ytenter" action="youtbe.html" method="get">
url: <input type="text" id="url"name="url">
stop <input type="text" id="stop" name="stop">
<input type="submit" value="Submit" onclick="ytstop(this.stop)">
</form>
and take the entered value in id=url and id=stop
and run it to youtbe.html here:
<head>
<script>
(function ytstop() {
var stopPlayAt=10; // Stop play at time in seconds
var stopPlayTimer; // Reference to settimeout call
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement("script");
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
window.onYouTubeIframeAPIReady = function () {
player = new YT.Player("player", {
"height": "315",
"width": "560",
"videoId": "L6cVcbkx8l8",
"events": {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
// This automatically starts the video playback when the player is loaded.
function onPlayerReady(event) {
event.target.playVideo();
}
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
var time, rate, remainingTime;
clearTimeout(stopPlayTimer);
if (event.data == YT.PlayerState.PLAYING) {
time = player.getCurrentTime();
// Add .4 of a second to the time in case it's close to the current time
// (The API kept returning ~9.7 when hitting play after stopping at 10s)
if (time + .4 < stopPlayAt) {
rate = player.getPlaybackRate();
remainingTime = (stopPlayAt - time) / rate;
stopPlayTimer = setTimeout(pauseVideo, remainingTime * 1000);
}
}
}
function pauseVideo() {
player.pauseVideo();
}
})();
</script>
</head>
<body>
<div id="player">
</div>
</html>
I need to take the "stop" from the form and put it into stopPlayAt VAR at the top
Then I need to take "url" entered from the form and put it into "videoID":
Thanks for your help. Just want the end product to allow youtube link to be entered and a time to be entered and it runs it until that time entered in seconds.
I would like to refer you to the top answer on this page:
How to get the value from the GET parameters?
This enables you to get the value of the GET-parameters in the URL.
My problem is as follow :
I am making an ajax call to a jsp and its success part is like this :
success: function(msg){
alert(msg);
if(msg.indexOf("false")>=0)
{
var counter=$('#attemptsleft').value+1;
$('#attemptsleft').val(counter);
var left=3-counter;
if(left>=0)
alert("You have "+left+" attemps left");
else
alert("You have no attempts left");
}
else{
alert("success");
}
}
Actually what i want to do is that to provide number of attempts to the user and if he exceeds those then tell that their are no more attempts left.
In html am doing this :
<input type="hidden" id="attemptsleft" value="0"></input>
Where am doing wrong.As am not getting results which were expected.
You aren't checking the condition when deciding whether to give success.
As an aside, you can just store the attempts value in a javascript variable, instead of using an input.
Try this one :
success: function(msg){
alert(msg);
if(msg.indexOf("false")>=0)
{
var counter=parseInt($('#attemptsleft').value)+1;
$('#attemptsleft').val(counter);
var left=3-counter;
if(left>=0)
alert("You have "+left+" attemps left");
else
alert("You have no attempts left");
}
else{
alert("success");
}
}
I just added a parseInt() while increment the attempts left value.
I will try to explain my problem without attaching any code, I think that that is not needed.
Okay, I have a websocket client in JS that connects to my java server. The handshake is done, connected handler is called on the client, so I send a message to server, wich is readed. Then the message is reversed and sended back to the client, but the client messagerecived handler or any other handler are not called.
This is the message that I send to the client:
b[0]=-127;//Its the same of 129?
b[1]=1;
b[2]=18;//any char..
I think that the problem must be on the first byte. I write "b[0] = (byte)129;" but when I read it it returns -127, maybe because, ¿the byte 129 have to be unsigned?
Thanks for help :P
The requested client code:
<html><head><meta charset="utf-8">
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:10637/penise";
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
var msg = String.fromCharCode(1)+ String.fromCharCode(0)+"This is niceeee"
doSend(msg);
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
function char(i) {
return String.fromCharCode(i);
}
</script>
</head><body><h2>WebSocket Test</h2>
<div id="output"><p style="word-wrap: break-word;">CONNECTED</p><p style="word-wrap: break-word;">SENT: This is niceeee</p><p style="word-wrap: break-word;"><span style="color: red;">ERROR:</span> undefined</p><p style="word-wrap: break-word;">DISCONNECTED</p></div>
</body></html>
I would recommend that you use a buffer of unsigned bytes to avoid confusion.
Your main problem is that the first byte indicates that the payload is UTF-8 text, but the single byte value in your payload is 180 which is not a valid UTF-8 character. If you are trying to send a binary value then you need to indicate that in the first byte by setting the opcode to 0x2 rather than 0x1 (e.g. 130 rather than 129).
OK, I have solved the problem. The problem was that, when i sent the header, I putted 2 "\r\n", instead of only one, so one of the \r\n becomes part of the next frame and the connection is broken (because it becomes the opcode of the next frame).
Thanks you for trying to help me <3