Call Javascript function after AJAX load - javascript

I know that these kind of questions pop up a lot on here. I usually am not the type to ask questions but this time I could not find a solution through searching.
I have boiled down my problem to a very small and simple environment:
I have 3 files:
Index.php:
<html>
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="javascript.js"></script>
<head>
<title>Test</title>
</head>
<body>
<div>
<input type="button" value="Show" onclick="show('content','content.php');">
<script type="javascript/text">
show('content','content.php');
</script>
<br>
<div id="content"></div>
</div>
content.php
<div>CONTENT</div>
<input type="checkbox" id="checkbox" onclick="checkbox();">
<input type="text" id="textfield">
And javascript.js
function show(divcontainer,file){
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(divcontainer).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", file);
xmlhttp.send();
}
function checkbox(){
if(document.getElementById('checkbox').checked){
document.getElementById('textfield').value = "checked";
}
else{
document.getElementById('textfield').value = "unchecked";
}
}
When I press the button in index.php it loads the file content.php into the div container "content" via an ajax call. The file content.php has a checkbox and a textfield. When the checkbox is checked and unchecked it executes a javascript function that puts checked/unchecked in the textfield.
Simple enough and everything works fine.
Now what I want to do is to call the function checkbox() the moment that content.php is loaded. In this example it would mean that the textbox would already have the value "unchecked" and not only after the checkbox has been checked and unchecked again.
Putting the javascript code into the file content.php didn't do anything.
Somehow I feel that there must be a simple solution to this. I'm still pretty new to javascript though so I don't know the in and outs yet.
Any help would be greatly appreciated
Many thanks!

Try this
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(divcontainer).innerHTML=xmlhttp.responseText;
checkbox();
}

if you´re new to JS you should definitely have a look at jQuery. Makes AJAX alot simpler.
$.ajax({
url: youURL,
success: function (){
//or whatever function you want to be called after success :)
}
});

Related

Bring over php variable through ajax into html tag

So i'd like to auto check the boxes based on the data from my database, whenever i click a table row. I'm currently using an AJAX script for this table row click, however, i can't figure out how to bring over the php variable value onto my main file's php variable and replace the value, from my other php file where i'm performing the AJAX php codes.
this is my main file's check box.
<input type="checkbox" name="skincareinuse[]" value="Lotion" <?php if(in_array("Lotion",$skincareinuse)) { ?> checked="checked" <?php } ?>/>Lotion<br>
this is my other php file where my AJAX script is drawing values from. I've done an explode and stored them in a php variable.
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
The problem is that in the php file where my AJAX script is drawing values from, the variable $skincareinuse could not be updated into $skincareinuse on my main php file.
Let's say even if i am able to use JSON to bring the value over, how do i go about storing it since JSON is being encoded into javascript?
Sorry if I didn't explain it right, please help!
#Iceman, is it possible to run .ajax function in an ajax script?
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
var xmlhttp;
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
$.ajax({
url: "BAConsultRecordsAJAX.php"
})
.done(function(data) {
console.log(data);
selectTestAnswer(data.key + "[]", data.value)
})
.fail(function() {
alert("error");
})
}
}
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
EXAMPLE:
$('#mybutton').click(function() {
$.ajax({
//sample json, replace with your data
url: "http://echo.jsontest.com/key/skincareinuse/value/Lotion"
})
//if data retrieval was successfull
.done(function(data) {
console.log(data);
//got data as json from server. NOw lets update the page(DOM).
selectTestAnswer(data.key + "[]", data.value)
})
//if data retrieval was a failure
.fail(function() {
alert("error");
})
});
//a simple function that if called with say with skincareinuse[] and Lotion marks the corresponding checkbox.
var selectTestAnswer = function(chkbox, value) {
$("[name='" + chkbox + "']").each(function() {
if ($(this).val() == value)
$(this).attr('checked', true);
else
if ($(this).attr('checked') == true)
$(this).attr('checked', false);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id="myinput" type="checkbox" name="skincareinuse[]" value="Lotion" />Lotion
<br>
<input id="myinput" type="checkbox" name="skincareinuse[]" value="Talcum" />Talcum
<br>
<script>
</script>
<br>
<br>
<button id="mybutton">RUN AJAX</button>
<br>
<br>this ajax calls this url : "http://echo.jsontest.com/key/skincareinuse/value/Lotion" returns this sample json:
<pre>
{
"value": "Lotion",
"key": "skincareinuse"
}
</pre>
</body>
</html>
I have demo-ed an example where the ajax reads the data from the server (here a test url) then update (ie. check the boxes) correspondingly.
This an example on how to do updation from AJAX. I suggest you read on how AJAX works.

Do script from another file

im today stared learning some ajax technology and im done that when im pressing the button im getting text from another file with functions but they dont working.
My main file
<html>
<head>
<script>
function showHint(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "request/testa.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button id="inp" style="background-color: #0000FF; color: #ffffff" onclick="showHint(this.value)">
Just do it!
</button>
<p><span id="txtHint"></span></p>
</html>
and in file which send me text (request/testa.php) is
test 2
<script>
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
</script>
and tekst working fine, i got text "test 2" and script but that not works.
Writing javascript code into your page using innerHTML will not execute the script.
The easiest way around this is to use jQuery's load, which will execute the scripts for you.
You have to change something in testa.php. Put everything in a function or just remove the script tag.
function MyScript(){
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
}
or
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
After that you can replace the innerHTML in your showHint function for the eval function.
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
for
eval(xmlhttp.responseText);
but have in mind that the eval function opens the door for bugs or hacks.

javascript with XMLHttpRequest not working

I have tried everything suggested in questions of similar nature but this very basic code is just not working. I just want to receive the message from the php code in the same file using XMLHttpRequest.
<!DOCTYPE html>
<head></head>
<body>
<div id="qwer" style="height:50px;width:40px"></div>
<script type="text/javascript">
function check() {
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://'my-domain-name'/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null);
resu.innerHTML="CHECKING...";
}
}
</script>
<?php if(isset($_GET['username'])) {
$u=$_GET['username'];
echo $u;
exit();
} ?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
</body>
</html>
The browser (Google Chrome) isn't showing anything for the onclick event.
It finally worked. I made the following edits.
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function check()
{
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://www.websamaj.in/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200)
{
var return_data = hm.responseText;
resu.innerHTML=return_data;
}
}
hm.send(null);
resu.innerHTML="wait...";
}
</script>
<?php
if(isset($_GET['username']))
{
$u=$_GET['username'];
echo $u.",you are finally here!:)";
exit();
}
?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
<div id="qwer" style="height:50px;width:100px;background-color:#CCC;"></div>
</body>
</html>
Apparently, the else condition there in onreadystatechange function was causing a problem. I would love it if anybody could tell me why exactly was that creating a problem. As far as i know, onreadystatechange event is called each time the state changes. So in my previous code, "error" should be overwritten thrice on the div and then, when the state changes to 4 and 200, the responseText should be overwritten, since i didnt use append. So, an explanation would be highly acknowledged. Thank you!
In your original code, hm.send(null) and resu.innerHTML="CHECKING" lines are actually INSIDE the onreadystatechange callback:
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null); // <-- wrong place!
resu.innerHTML="CHECKING...";
}
In your edited version, you moved them out of there (fixed indention):
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
}
hm.send(null);
resu.innerHTML="wait...";
The reason you didn't notice this is because in your edited version, you didn't indent your blocks correctly. Recommend always keeping your code formatted consistently, even when hacking around, so you can see the code blocks.

Javascript/AJAX Show Text in text file automatically

I am trying to make a simple AJAX program, that always displays the newest text from a file.
It should be retrieving it from the file, wait 2 seconds, and if something changed, write it out.
I tried already but the code doesn't seem to work.
<html>
<head>
<script type="text/javascript">
function sleep()
{
var dt = new Date();
dt.setTime(dt.getTime() + 2000);
while (new Date().getTime() < dt.getTime());
}
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxtest.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script>
while (0=0)
{
loadXMLDoc();
</script>
<div id="myDiv"><h2>Status</h2></div>
<script type="text/javascript">
setTimeout(loadXMLDoc(),1000)
}
</script>
</body>
</html>
How do I get it to check and update the text automatically?
Thanks!
Edit:
Here is the final code for anybody who is interested:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","status.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script type="text/javascript">
loadXMLDoc();
</script>
<div id="myDiv">Current Status</div>
<script type="text/javascript">
setInterval("loadXMLDoc()", 2000);
</script>
</body>
</html>
I am not sure if its a typo or a thing from another language. (Like PHP)
In HTML you cannot have javascript code that goes across multiple script tags.
Also your while loop has only one = sign, would need two to be comparison.
But that being said you do want setTimeout or setInterval, because non multi-threaded javascript will just lockup, mulit-threaded ones would wasting processing time as well but not totally lockedup.
Something like
setInterval("loadXMLDoc()", 2000);
setTimeout executes the first parameter as javascript after the second parameter of milliseconds.
setInterval executes the like setTimeout except every X milliseconds.
Both setTimeout and setInterval return a value which can be used to stop the javascript from being executed again.
That value is used in clearTimeout(value) or clearInterval(value)
The body of your page would look like this:
<body>
<div id="myDiv"><h2>Status</h2></div>
<script type="text/javascript">
setInterval("loadXMLDoc()", 2000);
</script>
</body>

How can I have a double Ajax request?

I have a problem: I'd like to have a double Ajax request, but I can't.
For example I have a page in PHP (rand.php) which returns a random number.
Code:
<?php
$rand = rand(0,10);
echo $rand;
?>
In an other page I want to create an Ajax request which get a random number from rand.php twice and write it in different div.
<head>
<script type="text/javascript">
http = new XMLHttpRequest;
function rando(div){
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
document.getElementById(div).innerHTML = http.responseText;
}
}
http.open("GET","rand.php",true);
http.send();
}
</script>
</head>
<body>
<div id="div1"></div><br />
<div id="div2"></div><br />
<button onclick="rando('div1');rando('div2')">Randomize!</button>
</body>
It doesn't work. Help me, please!
Yeah, as others have pointed out, your http is shared between all callers to rando. You should create a new one inside rando.
As an aside, that wont work on all browsers. You need to create a different type of http request object on early versions of Internet Explorer.
You have to initialize XMLHttpRequest every time you want to call rand.php:
<head>
<script type="text/javascript">
function rando(div)
{
var http = new XMLHttpRequest;
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
document.getElementById(div).innerHTML = http.responseText;
}
}
http.open("GET","rand.php",true);
http.send();
}
</script>
</head>
<body>
<div id="div1"></div><br />
<div id="div2"></div><br />
<button onclick="rando('div1');rando('div2')">Randomize!</button>
</body>

Categories

Resources