I've successfully wrote a working Ajax code, but the problem is that i can add an input field only once. I have a submit input, that calls Ajax script, everything works, the input text field appears, but after this if i want to add another text field by clicking on the submit input, it does not work. You only load once (YOLO). How do i write more awesome code that lets me add as many text fields as needed? Thanks for every reply. Here is my code:
index.php:
<head>
<script>
function ajaxobj(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('asd').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajaxAddInput.php',true);
xmlhttp.send();
}
</script></script>
</head>
<body>
<input type="submit" onclick="ajaxobj();">
<div id="asd"></div>
</body>
the php file:
<?php
echo '<input type=\"text\">';
?>
Simply use a standardized library, just like jQuery. With this in mind, you might use the following code:
$("#asd").on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
Alternatively, you can use the library with classes as well:
$('input[type=text]').on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
Related
I am doing a blog with PHP, AJAX, MySQL, etc. As usual, each post has its ID and inside the posts you can see the comments.
What I am trying to do is refresh the comment's div by calling the comments.php document with AJAX and putting it in the div with $('#comments').html(data);.
Doing this every 5 seconds for maintaining the comments like in real time, but the problem is that when the div does the first refreshing, the div loses the ID of the post and say that is undefined.
How can I refresh any div without losing the ID of the post?
If I call the comments.php file with the typical include(file.php) inside of the post file, I have no problem, but using this way I just can't refresh the content.
Here's the code:
post.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'support/comments.php',
success: function(data) {
$('#comments').html(data);
}
});
});
</script>
div where the result is going to be showed:
<div id="comments">
</div>
Script for refreshing the div:
<script language="Javascript" type="text/javascript">
function refreshDivs(divid, secs, url) {
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("your browser doesn't support ajax.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function () {
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
window.onload = function startrefresh () {
//update content on real time
refreshDivs('comments',10,'support/comments.php');
}
</script>
You can pass the post id in the URL, like so:
url: 'support/comments.php?id=<?= $post_id ?>'
Then wrap the call with a setTimeout, like so:
window.setInterval(function(){
$.ajax({
url: 'support/comments.php?id=<?= $post_id ?>',
success: function(data) {
$('#comments').html(data);
}
});
}, 5000);
And discard refreshDiv.
This is assuming that comments.php retrieves the comments, and some other code posts them.
ok guys I solved it... I am gonna leave the code here in case of somebody could has the same problem... what I did was build a hidden input and put this input to use its value like the id of the post, then I sent the value of this input to the script with #('div').val and finally I sent that value to the comments.php file, once there.... I used the value in the query sentence for doing the comparative and finally can get the comments in the right post
Here's the code
<script>
$(document).ready(function() {
window.setInterval(function(){
//Comentarios
var id = $("#idcomment").val();
$.get("support/comments.php", { idpost: id }, function(LoadPage){
$("#comment").html(LoadPage);
});
}, 5000);
});
</script>
I am writing a program that gets information from forms using AJAX, and I was wondering if there was a way to make a button that clears the form and sort of resets the form. Right now if you press a button, the text won't disappear, but Im hoping to make a home button that would make the text disappear. I am just going to post my .html file because I think thats all we need. Let me know if there is more code you need. I tried making a reset button but it didn't seem to work.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + "period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<button type="reset" value="Reset"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
Your reset-button should already do this, if its within the <form></form> or has the "form"-attribute, see here
You can either use the default reset button, if it is in between the form tag or you can use jquery to do this for you.
You just have to add an event on the click event of the home button and u can achieve what you want.
this is a reference which u can take
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], input[type="password"], textarea").val("");
});
Add all other fields which u want to clear on click of the home button
I am trying to load a php file after a while by using ajax. What I am trying to do is kind of a quiz. I want an image screen to be seen by user for 3 seconds and then the answer choices to be seen. I want to do this for 3 or 4 times in a row. For example;
1)The question image
after a few seconds
2)Answer Choices
After click on an answer
3)Second question image
... and go on with this order.
I can do this with below code:
<script type="text/javascript">
var content = [
"<a href='resim1a.php'> link 1 </a>",
"<a href='resim2a.php'> link 2 </a>",
"insert html content"
];
var msgPtr = 0;
var stopAction = null;
function change() {
var newMsg = content[msgPtr];
document.getElementById('change').innerHTML = 'Message: '+msgPtr+'<p>'+newMsg;
msgPtr++;
if(msgPtr==2)
clearInterval(stopAction);
}
function startFunction() { change(); stopAction = setInterval(change, 500); }
window.onload = startFunction;
</script>
<div id="change" style="border:5px solid red;width:300px; height:200px;background-Color:yellow"> </div>
But, when this file is included by another file, this script does not work. How can I make it work?
<script type="text/javascript">
function load(thediv, thefile){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile , true);
xmlhttp.send();
}
</script>
The previous page script is above. I use this script with the below code:
<div id="anotherdiv" >
<input type="image" onclick="load('anotherdiv' , 'include.php');"src="buton1.png">
</div>
The reason is because you are expecting the window to fire onload event:
window.onload = startFunction;
Window is loaded when the ajax is running, so why not call the function directly?
startFunction();
If you need some DOM elements before the script, just put the script below the DOM elements and the script will run after the DOM is ready.
you need to remove change(); from function startFunction()
here is the full example click here
I hope it will help for you.
I am a beginner and I am trying to learn how to add, delete, retrieve and update a database using PHP and Ajax.
At this time I have accomplished how to retrieve and delete so I am trying to update some values. For retrieving data, I just pass the selected ID I want, so I can retrieve the data. Same goes for delete, I just assign which ID I want to delete. Now to update there are more things going on, its where I cant find the solution.
This is my Form:
<form onsubmit="updateuser()">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="Submit" value="Update">
</form>
and this is my javascript:
function updateuser() {
var str = $('.ud_id').attr('value');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?q=" + str, true);
xmlhttp.send();
}
I think the problem comes because my form ajaxupdate.php file doesn't retrieve the First and Last name values from the form. It's like I am not passing them (?).
Here is my ajaxupdate.php file:
<?php include("connection.php");
$id=$_GET['ud_id'];
$first=$_GET['ud_first'];
$last=$_GET['ud_last'];
$query="UPDATE contacts SET first='$first', last='$last' WHERE id='$id'";
mysql_query($query);
mysql_close();
?>
What I'm I doing wrong so that I can update the value first and last of database for a specific ID ?
Try this code
<script type="text/javascript">
function updateuser() {
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
</script>
HTML
<form name="test">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="button" onClick="updateuser()" value="Update">
</form>
In your javascript, do this
function updateuser() {
var ud_id = $('input[name="ud_id"]').val();
var ud_first = $('input[name="ud_first"]').val();
var ud_last = $('input[name="ud_last"]').val();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
If you want to use the updateuser() function on submit, then it must prevent the form from actually submitting. Make it return false, otherwise the form gets submitted by the browser before the function has time to execute.
The browser runs the function before submitting the form (that's how on submit works). If the function doesn't return false, then it interprets that as "everything is OK, you can safely submit the form". The form then gets submitted as usual.
In the mean time, the function initiates the asynchronous request. But since the browser has already submitted the form, now you're on a totally different page, thus the connection and the asynchronous request get disconnected and most likely ignored (unless of course the request made it before the page was changed, in which case both requests are processed).
As an alternative, you could execute the function without placing it in the on submit event. See sam_13's answer.
Check this it will work as expected
ud_id = document.getElementById('ud_id').value;
ud_first = document.getElementById('ud_first').value;
ud_last = document.getElementById('ud_last').value;
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id +"&ud_first=" +ud_first+ "ud_last="+ud_last, true);
<form onsubmit="updateuser()">
ID Number: <input name="ud_id" id="ud_id"><br>
First Name: <input type="text" name="ud_first" id="ud_first"><br>
Last Name: <input type="text" name="ud_last" id="ud_last"><br>
<input type="Submit" value="Update">
</form>
I came accross this example because i am also running into a similar issue. however I couldnt help but notice that you do not specify a method for your form and your AJAX is assuming it should use the GET method. just food for thought... cheers
This code is tested and works. I needed to do the same thing, update MySql with ajax and combining the above with a wider research I got this to work.
The php file is called ajaxupdate.php:
<?php
$id= $_GET['ud_id'];
$first= $_GET['ud_first'];
$last= $_GET['ud_last'];
require_once ('mysqli_connect.php'); //connection to the database
$sql = "UPDATE contacts SET FirstName ='$first', LastName='$last' WHERE id='$id'";
$result = mysqli_query($dbc,$sql);
mysqli_close($dbc);
?>
The Html file called anyNameYouWish.html:
<html>
<head>
</SCRIPT>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
function MsgBox (textstring) {
alert (textstring) }
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
var queryString = "?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last;
ajaxRequest.open("GET", "ajaxupdate.php" + queryString + "&random=" + Math.random(), true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" name="test" onsubmit="ajaxFunction()">
ID Number: <input id="ud_id" name="ud_id"><br>
First Name: <input id="ud_first" type="text" name="ud_first"><br>
Last Name: <input id="ud_last" type="text" name="ud_last"><br>
<input type="submit" value="Update">
</form>
</body>
</html>
This is a Google suggestion-like script.
I rewrote the AJAX Call code by splitting it up into multiple functions and seems this is a better cross-browser/usability approach. Now I need to pass the input variable that I read from the input #search_text to a php file where I actually fetch the data from database.
For moment all I need is to pass search_text and display it with echo $_GET['search_text'];
Can someone help me?
Here is the script
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php");
}
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and the php file is:
<?php
echo 'Something';//'while typing it displays Something in result div
//echo $_GET['search_text'];
?>
Thanks
The issue is that you're not actually passing in any data to the PHP script. In this case, you need to stick the 'search_text' parameter on the end of the URL, since you're expecting it to be a GET request.
startRequest("ajax-submit.php");
should be
startRequest("ajax-submit.php?search_text="+document.search.search_text.value);
this jQuery Solution is way easier and Cross-Browser compatible:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$('#search_text').keydown(function(){ // Bind event to KeyDown
var search_text = $(this).val(); // get value of input field
$.ajax({ // fire Ajax Request
url: "ajax-submit.php?search_text=" + search_text,
success: function(result){
$("#results").html(result); // on success show result.
}
});
});
});
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" />
</form>
<div id="results" style="background:yellow"></div>
</body>