I have a js AJAX that fetches some content and inserts it into a html element called content_holder. And I would like to call a function right after the content have been updated with the ajax. I have tried to put a <script> element into the content that gets added but it seems like it don't get executed. So I was hoping someone here would know a solution to this. (I'm not using jQuery)
function ajax(instruction, push, url, callback){
var xmlhttp; // the object for the httprequest
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() { // every time the readystate changes
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // status 200 = sucessfull page! NOT 404! // 1 2 3 4 are states of the request (4 is when it's done)
var content = xmlhttp.responseText + "<script>ajaxDone();</script>";
callback(content); // goes to the callback function (from the argument "callback") and then passes the xmlhttp
}
};
xmlhttp.open(instruction,url,true); // sends a the var q to the next php file
xmlhttp.send(''); // Sends the request
if(push == true){ // Change the link to the url of the ajax with
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on
if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !!
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
window.history.pushState({path:urlPath},'','./'); // an empty url push (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY)
return; // exit's the function
}else{}
var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php
newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file
window.history.pushState({path:urlPath},'',newLink); // the push
}
else{}
}
<p>Top Lists</p>
<div id="content_holder"></div>
Take a look at this topic: How to make an AJAX call without jQuery?
You can do smth like:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
//here you call whichever function you want
}
.....
}
Hope it helps
Related
There is a main-feed showing a list of blog post titles. When a title is clicked, I need to display the details of the blog post in a new html file. Below is my current code:
window.location.href = "/viewpost.html";
postID = this.id;
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("view-post-container").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "viewpost.php?q=" + postID, true);
xmlhttp.send();
The problem is, the element view-post-container, is in the file viewpost.html, and so I don't think the PHP file can access it. I would just display the data on the current page (index.php), but I wanted to have individual pages for each post so I can eventually learn how to have dynamic URL's for SEO and sharing purposes. The end goal is having dynamic urls, so maybe there is a better approach? Any help would is much appreciated. Thanks.
just try this, You have to put your code in on window.onload function
window.onload = function() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("view-post-container").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "viewpost.php?q=" + postID, true);
xmlhttp.send();
}
After function() it is not working, i don't know why. If I put an alert before that statement it's working but after that statement it isn't working.
<script>
function new_order() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
alert("asdasd");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("order_id").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "item_sort.php?sort=" + str, true);
xmlhttp.send();
}
</script>
3 things you can check
If an element corresponding to id order_id exists on the page
if the str is not null or not defined
If you are using older IE versions IE5 or 6 you need to add the
following in your code.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
Also you need to use the following way if you want to do POST ajax call.
xmlhttp.open("POST", "item_sort.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("sort=" + str);
So, I'm pulling a query from a php file using javascript, then publishing it to another javascript that will then put another php query in another text area.
In other words:
[input text area 1] -> [javascript live search] -> [Query results]
[Query results] -> [onClick event] -> [Load results in text area 2]
The idea is that live searches in one textarea will come out with its approximate match in another live.
However, when I try to load the data in the second textarea it comes out as raw data. I'm confused on how to view it properly.
HTML:
The first text area is the input with a function to call a script, which is here:
function showResult(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border = "0px";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
document.getElementById("livesearch").style.border = "1px solid #000";
}
}
xmlhttp.open("GET", "ajax-search.php?keyword=" + str, true);
xmlhttp.send();
}
The php returns the result:
echo '<li onclick="grabID('.$row['dir_id'].')" >'.$row['eng_dir'].'</li><br />';
Which then initiates a clicked event:
function grabID(num){
xmlhttp.open("GET","ajax-result.php?result="+num,true);
xmlhttp.send();
document.getElementById("output").innerHTML="Something here?!?!?!";
}
Once again the results from the other php are returned correctly. The problem is that because it's a loop, it returns a lot of results instead of just 1. I just want the 1 result that matches the ID of the previous search.
I want to add html variables : "<script>var var1 = new CalendarPopup();</script>" according to a number that the user chooses. At the moment I have an ajax setup that is suppose to change my tag to add the variables by changing the inner html like so :
<div id="calVar">
<script>
var cal1 = new CalendarPopup();
var cal2 = new CalendarPopup();
</script>
</div>
function addRespDropDownAjax(currentNumberOfDropDown)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Ajax receiving the response in this function
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('calVar').innerHTML = '<script>var cal3 = new CalendarPopup();</script>';
alert(document.getElementById('calVar').innerHTML);
}
};
//Send the Ajax request.
xmlhttp.open('GET','mainServlet?command=ajax.AddRespDropDown&NUMBER_OF_DROP_DOWN=' + currentNumberOfDropDown, true);
xmlhttp.send();
}
The last alert :document.getElementById('calVar').innerHTML return nothing and my varaibles are not created. any ideas?
Thanks alot!!
HTML doesn't have variables, and any that are defined in a <script> without deeper nested scope can be simple defined off the window object.
Instead of trying to insert HTML, just use:
window.cal3 = new CalendarPopup();
then any other script can access this variable now or later.
I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.