AJAX call reloads the current page - javascript

I am trying to update a div with information received from a server periodically. The code below will receive the correct information from the server, append it to the divs text, then reload the page/clear out the div.
<?php
session_start();
?>
<!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 content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script type='text/javascript'>
function exec(command){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + "<br/><br/>" + xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "HAS-sync.php", true);
xmlhttp.send()
}
</script>
<style type="text/css">
.auto-style1 {
margin-top: 0px;
}
</style>
</head>
<body>
<table style="width: 100%">
<tr>
<td style="width: 141px; height: 390px">Managers<br /> DHTs</td>
<td name="targetThing" style="height: 390px">
<form onsubmit="exec()">
<input class="auto-style1" name="Text1" type="text">
<input type="submit">
</form>
<br />
<div id="txtHint" style="border:1px solid black;width:50%;height:50%"></div>
</td>
</tr>
</table>
</body>
</html>
How can I get this to simply append the result of the ajax call to the divs text, instead of clearing it completely?

First move the onsubmit to the form tag instead of the input as said in the comment.
<form onsubmit="updateTxt(this.value);return false">
You need to append the response text instead of overwriting what is already in innerhtml.
document.getElementById("txtToUpdate").innerHTML += xmlhttp.responseText;

Right now, you are overwriting the HTML using the = assignment. You need to append it, instead, using +=:
document.getElementById("txtToUpdate").innerHTML += xmlhttp.responseText;

Use
var txtToUpdate = document.getElementById("txtToUpdate");
txtToUpdate.innerHTML = txtToUpdate.innerHTML + xmlhttp.responseText;

You need to return false in your onsubmit handler so the browser knows you've handled the request and it should not proceed. This can be done in a couple ways:
Add return false; after exec() in your binding:
<form onsubmit="exec();return false;"><!-- ... --></form>
or, Modify your binding to be return exec() and have the method return false;:
<script>
function exec(){
/* ... */
return false;
}
</script>
<form onsubmit="return exec()"><!-- ... --></form>
As an aside, you should consider moving away from binding javascript using attributes and start using addEventHandler (and alike) to keep a clear separation of concerns.

Related

XMLHttpRequest does not fire for POST if both required fields are entered

Hello I am trying to sent user id and password to PHP file and echo it back in json. If I have "required" in the input form tags when I enter only one value it returns the json with that value and other one as empty string. But if I enter both it does not go into the XMLHttpRequest at all.
If I remove "required" tho it does not work with only entering one value either. Thank you!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>first assignment</title>
<link rel="stylesheet" href="style.css">
<script>
function curlcheck() {
var user_id = document.getElementById("user_id").value;
var pass = document.getElementById("password").value;
var body = "ucid=" + user_id + "&password=" + pass;
xhr = new XMLHttpRequest();
xhr.open("POST", "front_curl.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.status === 200 && xhr.readyState === 4) {
var response_json = JSON.parse(xhr.responseText);
//checks for json and "success" value from it
console.log("in successfull responce");
console.log(response_json.success);
console.log(response_json);
} else {
//checks when status did not come back successful
console.log("status NOT success");
console.log(xhr.responseText);
}
};
xhr.send(body);
}
</script>
</head>
<body>
<div class="somebox"></div>
<ul>
<h3>Team 1 Online Exam System</h3>
</ul>
<form action="" method="POST">
<div name="form header" class="formhead">
<h1>Welcome</h1>
<p><span id="loginerr" class="err_alert"></span></p>
</div>
<div class="login_box">
<lable for="user_id">User ID</lable>
<input type="text" placeholder="Enter User ID" id="user_id" required>
<label for="password">Password</label>
<input type="password" placeholder="Enter Password" id="password" required>
<button id="but" type="submit" onclick="curlcheck()">Login</button>
</div>
</form>
<div class="footer">
</div>
</body>
</html>
your form is sent by default post method without js if your required conditions are met.
else your form isn't sent as you don't fill required fields, but this doesn't matter for js, so form is sent by js (your xhr)
you can:
1) onclick="curlcheck(); return false"
OR
2) onclick="curlcheck" and make curlcheck return false
OR
3) onclick="curlcheck", function curlcheck(event) { and put event.preventDefault(); inside the function
So you'll prevent default form sending and leave only your xhr working

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.

onclick display the code entered along with database without using iframe( just like when we post a news it appears in facebook)

I am trying to display the content just like in facebook.but i dint get it.i used iframe.can some one help me with this without using iframe.i want it to get independently ..like if user1 post it must be seperated from user2 ..but i didnt get it using iframe ii just got a linebreak ..
i here by attaching two images for idea sake facebook layout
this is my outcome.it would be helpful if u solve ...Thanks in Advance..atleast the working ui would be helpful
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<body>
<div id = "midle">
<div id="posts" >
<h1>WHAT'S UP?</h1>
<tr> <form method="POST" action="tryy.php" target="iframe_a" >
<textarea name="post" rows="5" cols=110" target="iframe_a" ></textarea>
<td><input id="button" type="submit" name="submit" value="POST" ></td>
</form>
<iframe width="100%" height="590" src="tryy.php" name="iframe_a"></iframe>
</div>
</div>
</html>
You can use ajax.
(replace the iframe with a div that for this example has the id "status")
<div id="status"></div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$.get(
'tryy.php',
function(response){
$("#status").html(response);
}
);
</script>
Inserted into your example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
#status {
background:#555;
width: 100%;
height: 590px;
}
</style>
</head>
<body>
<div id="midle">
<div id="posts">
<h1>WHAT'S UP?</h1>
<tr>
<form method="POST" action="tryy.php" target="iframe_a">
<textarea name="post" id="statusBox" rows="5" cols=110 target="iframe_a " ></textarea>
<td><input id="button" type="submit" name="submit " value="POST " ></td>
</form>
<div id="status"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js "></script>
<script>
function updateStatusList(){
$.get(
'tryy.php',
function(response){
$("#status").html(response);
}
);
}
$("#button").click(function(e) {
e.preventDefault();
updateStatusList();
return false;
});
$("#statusBox").keydown(function(e) {
if(e.keyCode == 13){ // when return was pressed
updateStatusList();
}
});
</script>
</body>
</html>
PS:
Since you are new some hints:
You should use <!DOCTYPE html> instead.
Use a closing </body> tag ;)
Don't use td, tr elements without a table element (and you shouldn't actually use tables at all for layouting)

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

Set cursor position in an input text field

After a lot of search I found the following threads:
define cursor position in form input field
jQuery Set Cursor Position in Text Area
Unfortunately in none of the posts a complete form embed code or a real example is given. Now I just don't know how to include nemisj's code (on the first link) or Mark's code (on the second link) into my form:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>
I wonder if someone could kindly help me with this as I'm badly stuck!
Many thanks in advance!
Here's the edited code, but it still doesn't work:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
function setCursor(node,pos){
var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node){
return false;
}else if(node.createTextRange){
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange){
node.setSelectionRange(pos,pos);
return true;
}
return false;
}
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>
Inside your <script></script> tag is where your JavaScript goes (although we prefer putting it in a separate file, so that no JavaScript lives on the HTML page itself).
Inside that, you have a call to $(document).ready(), which passes a function() { ... }. Inside that function is all the code that will be executed when your document has loaded.
Inside that function you have a call to $('#site').focus() which itself provides a function — this time one that will be called whenever the #site element gains focus. And presumably that's where you want to change the cursor position.
So, taking the setCursor function from Set cursor at a length of 14 onfocus of a textbox you can put that anywhere in your <script></script> and then inside that innermost function of yours you can write:
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}
I think I found the error in your setCursor method. The moveStart and moveEnd methods expect two arguments, the first being the unit it should use. Also, the end position appears to be relative to the start position. So I think instead of
textRange.moveEnd(pos);
textRange.moveStart(pos);
you want
textRange.moveStart('character', pos);
textRange.moveEnd('character', 0);
See: http://msdn.microsoft.com/en-us/library/ie/ms536623(v=vs.85).aspx
Oh, this one's easier done than said!
<script>
function setCursorInputPosition(e, pos) {
e.setSelectionRange(pos, pos);
}
</script>
<input onfocus="setCursorInputPosition(this, this.value.length);">

Categories

Resources