Changing div content with time - php

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.

Related

Unable to execute PHP code from extenal file with GET request

While learning JQuery and AJAX, I came across some exercises with GET requests to external files. (https://www.w3schools.com/xml/ajax_php.asp)
My JQuery script is as follows:
function displaySuggestions(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("suggestions").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText)
document.getElementById("suggestions").innerHTML = this.responseText;
}
}
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
Code is executed with following HTML code:
<div>
<h2>Display sugestions while typing</h2>
<div>
<form>
Fill in employee: <input onkeyup="displaySuggestions(this.value)">
</form>
Suggestions: <span id="suggestions"></span>
</div>
</div>
The output of the alert function is the whole PHP file as text.
Not sure if I am doing something wrong with the PHP file itself as I get the same result with an exact copy of the example code from the link above. I have created a file "gethint.php" with an exact copy of the PHP example code displayed at the bottom of the page from the link above

Ajax add input more than once

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

How to create a button that clears my form

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

PHP load data in modal

I need to load data from a database table using an ID that is sent to a modal window.
Basically, when the grid loads, there are multiple columns. Two in particular are called CONTAINER_ID and WORKFLOW.
Whatever is returned for WORKFLOW will be a link that opens up a MODAL popup called #mySVCModal. Here is the sample code:
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE)
{
echo "<tr";
echo "<td style=\"width: 50px;\">{$Row[CONTAINER_ID]}</td>";
echo "<td style=\"width: 50px;\"><a class=\"open-container\"
data-toggle=\"modal\" href="#mySVCModal\"
data-cont=\"{$Row[CONTAINER_ID]}\">{$Row[WORKFLOW]}</a></td>";
echo "</tr>";
}
When the user clicks on {$Row[WORKFLOW]}, a modal window opens up with the CONTAINER_ID from the same row.
Here is the javascript that makes that happen:
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
});
</script>";
At this point, the modal window is open, and I can display the CONTAINER_ID. Here is the code that displays the CONTAINER_ID:
<div id="mySVCModal">
<form action="" method="POST">
<input type="text" name="containerID" id="containerID" class="containerID" />
*** more code here ***
</form>
</div>
So no problem. The CONTAINER_ID is displayed in an INPUT field called "containerID".
What I need to make happen now is when the modal window opens, "containerID" is sent to a PHP variable that will retrieve the WORKFLOW information from a database table called WORKFLOW_TABLE.
When I try to convert containerID into a PHP variable and echo it out, nothing is displayed:
<?php
$containerID = $_POST['containerID'];
echo "this is containerID " . $containerID; // only displays the text, not the $containerID
?>
I know that once I can get the code directly above to display the containerID in an ECHO, I can run a query off of it.
So basically, what I need to do is when the modal window opens, PHP will take containerID and run a " SELECT * FROM WORKFLOW_TABLE where CONTAINER_ID = 'containerID' ";
The contents from WORKFLOW_TABLE should automatically be displayed in various INPUT fields. I'm just using INPUT fields for now. That's beside the point.
So all in all, I need the modal to open up with the contents from WORKFLOW_TABLE displayed using the containerID.
I hope I worded this clearly.
Please help.
Sounds like you need an AJAX query.
<script>
function loadData()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "db_query.php?containerID = " + document.getElementById('containerID').getAttribute('value'), true);
xmlhttp.send();
}
window.onload = loadData;
</script>
<div id="myDiv"></div>
Sorry in advance for any possible flaws, I didn't actually run this.
It looks like you're not actually submitting your form to the server when you're loading the modal.
Since you probably don't want to reload the entire page to display the modal, you should request the modal content on demand using an asynchronous request. Since your sample code uses jQuery, I've used the same here. (see the jQuery.load() documentation for more info)
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
$('.modal-body').load(
'yourPHPscript.php',
{ containerID: $('#containerID').val()}
);
});
</script>";
Then your PHP script should resemble this (notice the change from POST to GET):
<?php
$containerID = $_GET['containerID'];
echo "this is containerID " . $containerID;
?>

AJAX not working with text box

I'm learning AJAX and created this simple code. I type in something in the text box and it should return with the word something pop up on screen. This was able to work when I clicked on a button but now that I changed it to a text box it no longer works. Here is the first file that contains the XML HTTP Request data and HTML code.
<html>
<head>
<script type="text/javascript">
function load() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('results').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'test_ajax_return.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="search" name="search">Type a name:
<br>
<input type="text" name="search_text" onkeydown="load();">
</form>
<div id="results"></div>
</body>
</html>
And here is the second file that I want to open when the user types in something in the text box.
<?php
echo 'something';
?>
[SOLVED] : Thanks to Matt for Javascript Console. Found out some comments that I edited out effected the code after all. I didn't think HTML comments could do that. Lesson learned.
Open up your javascript console (F12 in Chrome) and see if there are any errors (indicated by a red X on the bottom of the popup).
You most likely have javascript errors that you're not catching.
I just copied the code to my machine, it works perfectly.
As an idea though, maybe your browser's being funny about onkeydown. Try onKeyDown instead.

Categories