I've been looking around for a while, and can't seem to find this answer. I am new to JQuery, and am more familiar with PHP (though am fully aware that the act is not possible in PHP, thus searching for the answer in JQuery)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#keyboard").keyup(function(e){
var key = e.keyCode ? e.keyCode : e.which;
if (key == 87) {
alert("keyup event occured! The Ascii value of pressed key is: " + event.keyCode);
}
});
});
</script>
For starters, this is what I have as the key press. For now it's just an example, that if the 'w' key is pressed then released, it tells me basically, it's pressed.
My form looks like this:
<form action="URL">
<input type="text" id="keyboard" />
</form>
In every instance I've found, it seems that you need to have a text area or something similar. Is the text area somehow required? I am looking to have the text area removed and just have the page respond to my clicking of the W button, anywhere.
On a side note, how would I get this to submit to php if that's possible?
use $(document).keyup(function(e){ ...
that way you catch the key-events globally
On your sidenote...
the URL you supply in the action-tag, that's the script that will be executed.
In that (php)script you can get the variables from the inputs you send along, with POST[].
JS:
<form action="path/to/script.php">
<input type="text" id="keyboard" name="keyboard" />
</form>
PHP (path/to/script.php):
$variable = $_POST['keyboard']; //this uses the name-tags from the inputs in the form
Although you might want to look into Ajax-requests ($.post and $.get in jQuery), in a lot of cases those have advantages over the traditional form-based php calls..
The following should do it:
$(document).ready(functionn(){
$(document).on('keyup', function() {
//your code here including
//$('form')[0].submit();
});
});
Related
Hello guys I'm new to internet languages and I would like your help explained with apples!
I'm trying to make a webserver controlled robot with a raspberry pi 3b+. I already got that working with some HTML calling some PHP code and then executing Python scripts in order to move the robot. The thing is, when I press a button to move the robot the page refreshes then loads everything again making it really annoying. (HTML and PHP are in the same document)
I've read some post where people say to use <button> tags with type="button", but when I do that nothing happens. Let me share with you the code. Other people say to use AJAX, but I don't really know how to.
HTML:
<form action="" method="post">
<div>
<div>
<button type="button" name="boton7"><img src="imagenes/up.png"></button>
</div>
<div>
<button type="button" name="boton8"><img src="imagenes/left.png"></button><!--
--><button type="button" name="boton10"><img src="imagenes/stop.png"></button><!--
--><button type="button" name="boton9"><img src="imagenes/right.png"></button><!--
-->
</div>
<div>
<button type="button" name="boton6"><img src="imagenes/down.png"></button>
</div>
</div>
</form>
PHP:
<?php
//Primera fila || mover_arriba.py
if(isset($_POST['boton6'])){
exec('python /var/www/html/mover_arriba.py');
}
//Primera fila || mover_abajo.py
if(isset($_POST['boton7'])){
exec('python /var/www/html/mover_abajo.py');
}
?>
I would like to know if it can done without using AJAX or JS (interpreted languages are confusing to me) or if I can modify something on this code to achieve what I want. As you can see I used a form, I don't really understand if a button can do something without a form, why sometimes people use input="submit", I've also seen "onclick=". Please use as clear as possible answers.
If you need anything else please let me know!
EDIT: I forgot to mention that if I remove type="button" from this <button type="button" it works.
The bad news is that you will have to use JavaScript and AJAX to accomplish this. There's simply no (reasonable) way around it.
The good news is that what you want to do is actually quite simple. Since there is no conditional data and no return data to handle, the bar is already pretty low. I also assume that you are not worried about bad actors abusing vulnerabilities in your code, so let's dive in.
First off, let's get a library that can do AJAX calls. While not necessary, this makes everything a lot easier.
Inside your <head> element, put the following line:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Next, add an ID to your <form> element so it is easier for us to access with jQuery.
<form id="robotform" action="" method="post">
Now let's add some JS below the form to handle the form submissions. It has to be placed after because the html elements need to exist before this code is called. Code below is mostly adapted from the answer to this question: Submitting HTML form using Jquery AJAX
<script type='text/javascript'>
/* Get the name of the button that was pressed */
var buttonpressed;
$('button').click(function() {
buttonpressed = $(this).attr('name');
})
/* attach a submit handler to the form */
$("#robotform").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* target url is the current page */
var url = window.location.href;
/* Create the data as a string so the button name is sent properly */
var data = buttonpressed + '=true';
/* Send the data using post with element id name and name2*/
var posting = $.post( url, data );
/* Alerts the results if unsuccessful */
posting.fail(function( xhr, status, error ) {
alert('Error sending the command: ' + error);
});
});
</script>
One possible solution could be that you could have your PHP code return a 'false' value back to the form. This would prevent the page from refreshing.
This way the PHP code will call the python code but the form will not refresh since it has received a false value back from the PHP function.
I'm trying to change my form action to another link during submit using jquery. Please view the following code:
javascript
$(document).ready(function(){
$("form[name='search']").submit(function(e){
var submit=$(this);
submit.attr('action','?search='+submit.find("input[name='tsearch']").val());
});
});
HTML/PHP
<form name="search" method="post">
<input class="inputbox" type="text" name="tsearch" value="<?php echo $text_search; ?>" />
Though i can't seem to get it working. Any help here will be appreciated.
Here's a working example: http://jsfiddle.net/RmKDT/4/
You can see by the alerts that the action is changing. You just need to resubmit the form as well.
Edit: Fixed potential infinite loop
$(function(){
var submitted = false;
$('form').submit(function(e){
if (submitted == true) {
return;
}
e.preventDefault();
var action = $(this).attr('action');
alert(action);
$(this).attr('action', 'two.php');
action = $(this).attr('action');
alert(action);
submitted = true;
// resubmit the form
$(this).submit();
});
});
Your code seems to be fine. There are a few things you can try to get this working.
Be sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file else in the html head section
Be sure that you've included the datatale script after you've included jQuery, as it is most certainly dependant upon that.
Check whether jQuery is included properly and once only.
Watch out for jQuery conflicts. There is some other library which is overridding $, so your code is not working because $ is not an alias for jQuery anymore. You can use jQuery.noConflict() to avoid conflicts with other libraries on the page which use the same variable $.
alert('?search='+submit.find("input[name='tsearch']").val()) see whether you are getting the value you want.
Preapring for a Facebook competition while I have spare time, the Publish function with facebook has a once posted javascript function that you can define.
What I am looking to do is call a function to write a value unto a php form which will then be posted and submitting data into a database. I have tested to the extent that I know the idea is sound just calling a basic alert, I am just not sure how to get from calling the function to writing the value into the form.
This value I need to be able to call on in the page that the data is being posted to, to base an "if function" off, basically if "True/Yes" then I need it to process another php script in addition to the data its posting to the database
What I have now is:
<script type="text/javascript">
function isShared()
{
alert("Yes");
}
</script>
<input class="fieldbox" name='shared' type='hidden' value="value of 'display_alert()'"/>
I know it cannot be an alert, but this is pretty much where my current javascript skills leave me stranded.
<script type="text/javascript">
function isShared()
{
document.getElementById('xshared').value = 'Yes';
}
</script>
<input class="fieldbox" id="xshared" name="shared" type="hidden" value="" />
This will add the value Yes To the hidden field once isShared is called.
Are you looking to have the form automatically posted without the user clicking anything but the share button? The only reason I ask is that it sounds like what you are looking for is AJAX, to post data to the database silently without the need of the user to navigate away from their current page.
I'm still not 100% clear on what you're asking, but are you just looking to emit a server-side PHP variable into client-side JavaScript code? Something like this?:
<?php
// some code, etc.
$myVariable = "foo"; // some value
// more code, etc.
?>
<script type="text/javascript">
var myVariable = '<?php echo $myVariable; ?>';
// more JavaScript code, etc.
</script>
This would emit to the page as:
<script type="text/javascript">
var myVariable = 'foo';
// more JavaScript code, etc.
</script>
Basically anywhere that you need the literal value from the PHP variable, you'd write:
<?php echo $myVariable; ?>
I am not clear how exactly you are aiming to post the form data but you can set the input value using jquery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
$('#input1').val($('#input1').val() + 'more text');
<input id="input1" class="fieldbox" name='shared' type='hidden' value=""/>
I am trying to run this tutorial
i did not implement the validation part yet, but my problem shouldn't be based on this. Here is my code:
<script type="text/javascript">
$("#submitbutton").click(function () {
var content = $.("#contentarea").val();
$.ajax({
type: "POST",
url: "addArticle.php",
data: content,
success: $.("#addArticle").append("<p>ok</p>")
});
return false;
})
</script>
As seen in the demo, it should not refresh the page because of the return false statement and also should do a post instead of get. But neither it does. It will continue to reload the page and also append the given content to the url as an argument. How do i prevent this / where is my failure?
Here is the whole thing
The tutorial you have followed is incorrect. There are more ways to submit a form than just clicking on its submit button (for example, you can press return while in a text field). You need to bind your code to the form's submit() event instead of the button's click() event.
Once you have done this, use your in-browser debugger to check whether the code is actually being run when you submit the form.
Also, the success parameter needs to be a function:
submit: function() { $("#addArticle").append("<p>ok</p>") }
EDIT : also, you have written $.( instead of $( several times. This will cause a runtime error, which may cause the code that blocks the submission to fail.
Well well well...
A few less nerves later, it works.
I decided to use the jquery form plugin
But, and i bet you'll love that, i have no idea why it is working:
<script>
$(document).ready(function() {
$('#addForm').ajaxForm(function() {
alert("ok");
});
});
</script>
<div id="addArticle">
<form id="addForm" method="post" action="addArticle.php">
<textarea id="contentarea" required="required" name="content"> </textarea>
<br />
<input type="submit" id="submitbutton">
</form>
</div>
I guess the author has done pretty good work, just wanted to tell my solution to that future guy who is searching on google for that problem.
I'm having this little problem with internet explorer and ajax.
So first I used just php, and everything, worked, but because I don't want to reload the page, I use ajax.
So I have a form with a checkbox. When someone clicks on the checkbox, my ajaex is called and the input is changed in the db. In firefox there is no problem, but It doesn't work in internet explorer.
Here's a part of my code:
<script language="javascript" type="text/javascript">
function changefield($doss, $display){
$.get("update.php",{dossier: $doss, CSQ_DISPLAY:$display});
alert("test");
}
</script>
echo '<form id="'.$r ['BC_DOSSIER'].'" method="get" action="">
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)">
</form>';
It seems that in explorer, I only get the alert when the checkbox was checked. (Problem because it first reads the db if it must be checked or not, so you can change it later).
Does someone know where I went wrong?
Thank you very much in advance for the answers.
I would prefer to define it like this, I hate using onclick in my HTML:
edit FIXED (registered to change instead of click)
edit Wrapped in $(document).ready()
edit Added a click event as well
<?php
echo '<input class="ajax_check" id="check_'.htmlspecialchars($r['BC_DOSSIER']).'" type="checkbox" name="CSQ_DISPLAY" '.$checked .' />';
?>
<script type="text/javascript">
$(document).ready(function() {
$('input.ajax_check').click(function() {
this.blur();
});
$('input.ajax_check').change(function() {
var dossierId = this.id.slice(6);
var isChecked = (this.checked) ? 1 : 0; // better to explicitly convert bool to int for HTTP requests
$.get('update.php',{
dossier: dossierId,
CSQ_DISPLAY: isChecked
});
alert('test');
});
});
</script>
This will register that handler to all inputs with the className 'ajax_check', without leaving a function cluttering up the window object, and without messing up your HTML. Try it out and see if it fixes the problem - it may not as it does basically the same thing, but it's a better way of doing it IMHO. If you still have a problem, come back to me and we'll debug it.
Note that using this approach, it is important that the <script> is executed after the DOM is ready, so it should either be defined in the body after the checkbox or (better) wrapped inside $(window).load() or (best) $(document).ready().
In your code fallback function value wont passed for IE.
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)">
i.e) in above code onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)" this.checked will not work for IE, so you can pass as this and get the value in four function, this will work for all the browsers. e.g) like this
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this)">
and get the checked attribute inside the function.
I hope this will work.