ajax call checkbox internet explorer - php

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.

Related

Stop page refreshing when pressing HTML button?

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.

Pass the value of a variable from one page to another [PHP]

I would like to pass the value of a variable from one page to another without using a session variable or a cookie, how could I do? Besides this we say that the page must pass the value to another is a page that does not interact with the user as he has only the task of informing him that after a few seconds will be redirected to the next page, to do this I used a Javascript function. I thought then enter the variable value within a field "hidden" But it is not possible to push a button submit do not know how to send data to another page using a form. Could you give me some advice? I am posting my code below:
<?php
if (!mysql_query($sql,$conn)) {
die('Error: ' . mysql_error($conn));
} else {
$PartitaIva = $_POST['PartitaIVA']; echo $PartitaIva;
?>
<form name="passaggiopartitaiva" action="inserimentodati_refaziendale.php" method="post">
<input type="hidden" name="PartitaIva" value="<?= $PartitaIva ?>">
</form>
<p> Modulo inserito a sistema, verrai reindirizzato alla pagina principale </p>
<script>
window.setTimeout ("location.href=('inserimentodati_refaziendale.php')", 1000);
</script>
<?php } ?>
How about setting a timer at load, once your timer runs out, it will submit your form and the user will never know. Try something like this:
$(document).ready(function() {
setTimeout(function() {
$("form").submit();
}, 5000);
});
You can either use some like what CodeGodie posted:
$(document).ready(function() {
setTimeout(function() {
$("form").submit();
}, 5000);
});
or
window.setTimeout ("location.href=('inserimentodati_refaziendale.php?varName=<?= $PartitaIva ?>')", 1000);
And then you could just use $_GET["varName"] on the "inserimentodati_refaziendale" page.
But either way, what is the purpose of doing this? and why do you NOT want to use sessions?
If you're attempting to submit the form after a certain amount of time elapses, you should give the form a name attribute (which you already did, passaggiopartitaiva) and then change:
location.href=('inserimentodati_refaziendale.php')
To:
document.passaggiopartitaiva.submit();
Then the values of your <input> tags will actually be submited, assuming you gave those tags name attributes.
And it would be better to put javascript either in a separate file or in the <head> than to just throw it wherever like you're doing.
If you're using JQuery (which doesn't seem to be the case) then see CodeGodie's answer for a cleaner way to do the Javascript than what you've done.

JQuery keypress without textarea

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();
});
});

Cannot change form action via jquery

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.

performing php post with jquery.ajax

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.

Categories