javascript function not called on buttonclick [duplicate] - javascript

This question already has answers here:
add onclick function for submit button
(5 answers)
Closed 7 years ago.
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
</head>
<body style="background-color:red;">
I was just thinking that I could do us a private lil webpage ^^
I love you so much hun! <3
<form name="Wish">
Wish<input type="text" name="wish"/>
<input type="submit" class="button" onclick="sendtoajax(this.form)" />
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function sendtoajax(form){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert('done')
}
}
xmlhttp.open("POST","ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("form.wish.value");
}
</script>
</body>
</html>
I want to execute the function on button click and if I just leave it plain so it executes immidiatelly it work but when I put it into a function and I call it on button click it doesnt at all...

Change type="button" of input. If input has type="submit" it submits the form and hence your function will not be called.
<input type="button" class="button" onclick="sendtoajax(this.form)" />

<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
<script language="javascript">
function sendtoajax(){
var xmlhttp=window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert('done')
}
}
xmlhttp.open("POST","ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( 'wish='+document.querySelectorAll('input[name="wish"]')[0].value );
}
</script>
</head>
<body style="background-color:red;">
I was just thinking that I could do us a private lil webpage ^^ I love you so much hun! <3
<form name='Wish'>
<label>Wish<input type="text" name="wish" /></label>
<input type="button" class="button" value='Wish now' onclick="sendtoajax()" />
<input type="reset" value="Cancel"/>
</form>
</body>
</html>

In your code, the <form> submits and redirects. AJAX forms are not meant to redirect. Either give return false; like this:
<input type="submit" class="button" onclick="sendtoajax(this.form); return false;" />
Or give an event.preventDefault() in your AJAX code:
function sendtoajax(form) {
//----
//----
//----
return false;
}
If you can do with jQuery, it is very easy. Lemme take the same code of yours, and convert it to jQuery in a simple way and explain you:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<title>Login page</title>
</head>
<body style="background-color: red;">
I was just thinking that I could do us a private lil webpage ^^
I love you so much hun! <3
<form name="Wish" id="Wish">
Wish <input type="text" name="wish" />
<input type="submit" class="button" />
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
$(function () {
$("#Wish").submit(function () {
$.post("ajax.php", $(this).serialize(), function () {
alert("Submitted");
});
});
});
</script>
</body>
</html>

Related

Sending data from JavaScript to PHP via XMLHttpRequest

Good day.
I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).
I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:
var read = function(id) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=" + id);
}
In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.
What's the correct way to send the data? Thank you.
Your input is not complete. So I did the full example below that you can follow. I made a function, named readid(id), doing the same thing as you want. Then I call that function from html, when needed.
<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 || this.status === 200){
console.log(this.responseText); // echo from php
}
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>
view.php
<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type: 'POST',
data: id,
url: 'PATH_TO_VIEW.PHP',
success: function(data) {
//do something
},
error: function(data){
console.log('Something went wrong.');
}
});
});
</script>
</body>
</html>
Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two.

JavaScript function doesn't run on click

Although I know a lot about these languages now such as arrays and functions, I'm having a basic problem to getting this JavaScript to run, here's the code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="submit" value="submit" onclick="click()" />
<script>
function click() {
alert("hey");
}
</script>
</body>
</html>
You're running into this problem: javascript function name cannot set as click?
You can fix this by changing the function name to something else like function myClick
<head>
</head>
<body>
<input type="submit" value="submit" onclick="myClick()" />
<script>
function myClick() {
alert("hey");
}
</script>
</body>
</html>
yes,like the comment above. you should use a different name instead of click()
function submit() {
alert("hey"); }
<html>
<head>
</head>
<body>
<input type="submit" value="submit" onclick="submit()" />
</body>
</html>

Ajax code not working to search data

i am using normal ajax to search from data base when form submit but the code is not working . There are two date field i want to search data between two dates if i use separate page the code is working but in ajax it is not working .any help will be appreciate Thank you
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="datepicker/javascript/jquery-1.9.1.min.js"></script>
<link rel="stylesheet" href="datepicker/css/default.css" type="text/css" />
<script type="text/javascript" src="datepicker/javascript/zebra_datepicker.js"></script>
<script>
$(document).ready(function() {
$('input.datepicker').Zebra_DatePicker();
$('#strt_dt').Zebra_DatePicker();
});
$(document).ready(function() {
$('input.datepicker').Zebra_DatePicker();
$('#end_dt').Zebra_DatePicker();
});
</script>
<script>
function showStd(tstfrm) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("replace").innerHTML=xmlhttp.responseText;
}
}
var strt_dt = document.getElementById('strt_dt').innerHTML;
var end_dt = document.getElementById('end_dt').innerHTML;
xmlhttp.open("GET","test2.php?strt_dt="+strt_dt+"&end_dt="+end_dt, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="" method="post" onsubmit="return showStd(this);" name="tstfrm" id="tstfrm">
<fieldset>
<p><label>Start Date:</label><input name="strt_dt" type="text" class="text-long" id="strt_dt" /></p>
<p><label>End Date:</label><input name="end_dt" type="text" class="text-long" id="end_dt" /></p>
<input name="serch" type="submit" id="serch" value="search"/>
</fieldset>
</form>
<div id="replace" style="height:500px; width:1000px; border:1px solid #000;">
</div>
</body>
</html>
and here is the below test2.php for search
<?php
include '../dbconn.php';
$strt_dt=$_REQUEST['strt_dt'];
$end_dt = $_REQUEST['end_dt'];
?>
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td width="137"><b>Name</b></td>
<td width="154"><b>Contact</b></td>
<td width="407" align="center"><b>Action</b></td>
</tr>
<?php
$qry=mysql_query("SELECT * FROM std_register WHERE reg_dt BETWEEN '".$strt_dt."' AND '".$end_dt."'");
while($row=mysql_fetch_array($qry))
{
?>
<tr>
<td><?php echo $row['std_name1']." ".$row['std_name2'];?></td>
<td><?php echo $row['std_phno'];?></td>
</tr>
<?php
}
?>
</table>
Dude i can see in your code that you are using jQuery on the page.
can use jQuery provided methods for Ajax requests.
$.get
$.post
And more verbose method $.ajax for your work you need jQuery to make it cross browser.
$.get('/test2.php?date='+date,function(response){
//use server response to manipulate dom
});

Problems with nginx server

I have the following code in php:
<html>
<head>
<script stype="text/javascript">
function ventanachat(){
var xmlHttp;
if (window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var fetch_unix_timestamp ="";
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById("ventanachat").innerHTML=xmlHttp.responseText;
setTimeout('ventanachat()',10);
}
}
xmlHttp.open("GET","db.php"+"?t="+timestamp,true);
xmlHttp.send(null);
}
window.onload = function startrefresh(){
setTimeout('ventanachat()',1000);
}
</script>
</head>
<body>
<form action="insert.php" method="GET">
<input type="text" name="mensaje" id="enviachat" >
<input type="submit">
</form>
<div id="ventanachat" style="width:200px;height:200px;border:1px solid black;overflow:hidden;">
<script type="text/javascript">
ventanachat();
</script>
</div>
</body>
</html>
It is a very basic chat page that updates every 1 second. (the insert.php and db.php files are just consultations and are good)
It works perfect in Apache but Nginx does not work me. Why?.
(I speak Spanish, sorry if misspelled. use a translator). Thanks

onkeyup event is not working when the textbox has "data-role=tagsinput" specified

Below is the code I have been working on,
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-tagsinput.css" rel="stylesheet">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-tagsinput.min.js"></script>
<script>
var request;
function sendInfo(){
var v=document.main.io.value;
var url="myjsp.jsp?val="+v;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
}catch(e){
alert("Unable to connect to server");
}
}
function getInfo(){
if(request.readyState==4){
var m=request.responseText;
document.getElementById('sam').innerHTML=m;
}
}
</script>
</head>
<body>
<form name="main">
<input type="text" name="io" onkeyup="sendInfo()" data-role="tagsinput"/>
</form>
<div id="sam">
</div>
</body>
I have not included the "myjsp.jsp" file as I'm sure that nothing is wrong with it.
If I create the textbox as follows,
<input type="text" name="io" onkeyup="sendInfo()"/>
then the function "sendInfo()" is called but if I add "data-role='tagsinput'" as,
<input type="text" name="io" onkeyup="sendInfo()" data-role="tagsinput"/>
then the function "sendInfo()" is not called.
I have to write data-role="tagsinput" for generating the bootstrap tags, but I also want the function "sendInfo()" to execute.
Any suggestions on this situation??
Thanks in advance.
you can add the event listener with javascript:
window.attachEvent = function(){
document.querySelector("input[data-role='tagsinput']").onkeyup(function(){
sendInfo();
});
};
window.addEventListener("load", attachEvent);
to make sure for accessibility of your function, define it in window context:
window.sendInfo=function sendInfo(){/.../}
and you can also try body onload attribute:
<body onload="attachEvent();">...</body>

Categories

Resources