GET xmlHTTPrequest not working - javascript

i am trying to make an ajax commenting system where if a new comment is posted, the document title changes to (1) website title (like twitter)
my code is here
The xmlHTTPrequest
function loadXMLDoc7(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('newcomments').innerHTML=xmlhttp.responseText;
}
The PHP
echo "<script type='text/javascript'>
function auto2comments()
{
var MyDiv1 = document.getElementById('uiuiui');";
echo "loadXMLDoc7(MyDiv1.innerHTML)";
echo "}";
echo "setInterval(\"auto2comments()\",15000);</script>";
}
The DIV uiuiui contains /newcommentingi.php?show=0&id=username
The problem is when the Newcomments DIV gets filled, it shows
ID =
Show = 0
why?

The XmlHttpRequest object is asynchronous, which means that when it has the data ready, it returns it in a method. It is best to create a function to act as an event handler so that when the server responds, it calls the event handler function.
I think the solution you need is similar to here: How to get the response of XMLHttpRequest?

Related

Load same div everytime a button is clicked

I have been troubled on how to load the same div into the same page for days.
Been looking for answer in stackoverflow but not found one yet.
Simplified, this is my code so far,
<script>
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "add_more.php", false);
xmlhttp.send();
document.getElementById("add_more1").innerHTML = xmlhttp.responseText;
}
</script>
<html>
<body>
<input type="button" onclick="add_fields()" value="ADD"/>
<div id="add_more1"></div>
</body>
</html>
The problem is that when i clicked the button, it will only load add_more.php once. I want it to load everytime the button is clicked. How to do that?
Please help.
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //really no need for this anymore these days.
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) //success
{
document.getElementById("add_more1").innerHTML=this.responseText;
}
}
xmlhttp.open("POST","add_more.php",true); //set the sync to true, modern browsers will block a synchronous request.
xmlhttp.send();
}
This updated versions contains a readystate event that will fill your div every time the Ajax call is completed.
You were using a XMLHttpRequest with the asynchronous option set to false. This could block the user experience and modern browsers (like Firefox) will block this.
if you would like to add more content to the div, use
document.getElementById("add_more1").innerHTML += this.responseText;
+= adds content to the element instead of replacing it. It's a shorthand for:
document.getElementById("add_more1").innerHTML = document.getElementById("add_more1").innerHTML + this.responseText;
SIDENOTE: You are using a POST (in this case a GET would be better, since you're retrieving information only). If you want to send post data to the server you need to put the querystring (without the ?) as an argument in the send method.
To continue with this read up on asynchronous coding:
Easy to understand definition of "asynchronous event"? (very simple explanation).
How does Asynchronous Javascript Execution happen? and when not to use return statement? (more comprehensive).

XMLHttpRequest does nothing....?

I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>

Refresh page title every 10 seconds - Javascript

I am currently trying to refresh my page title every 10 seconds to ensure that the song info changes here:
But after the song changes, I am left with the same page title:
My JavaScript setInterval function isn't working correctly.
Here's my code (what should have worked):
<script type="text/javascript">
function songToTitle() {
document.title = "BDR | <?php echo $radio_info['now_playing']; ?>";
}
songToTitle();
setInterval(songToTitle, 10000);
</script>
<title>BDR | Loading Song Title...</title>
I don't really know what's up here.
It imports the song name correctly, but does not refresh.
Can anyone help me with this?
EDIT:
I tried using this too:
<script type="text/javascript">
function songTitle(){
var xmlhttp;
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.title.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.x86cam.com/wp-content/plugins/songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
It won't even load the title.
You are refreshing a static piece of information. To get new information you must use AJAX.
PHP is loaded before your browser opens it.
In other words...
<?php echo $radio_info['now_playing']; ?>
turns into
'Song Name'
so when Javascript looks at it, it only sees Song Name and is none the wiser.
AJAX Reference - complete API reference with examples down the page for you to fork off of. Your responding page also needs to be programmed to respond correctly. Usually I suggest JSON but this you can probably just use a text transfer since it's so little data.
You can send the data using POST and the PHP file can have something like this at the top:
<?php if ($_POST['songcheck'] === true) { echo $songName; return; }; ?>
PS - refreshing every 10 seconds isn't very efficient. When the song is loaded, use the song length +2 or +3 seconds for the timer instead. Much better :)
You can't use that php code in there, it's not going to execute when the function runs because PHP ran at the server, the code is now running in your browser, so once the song changes, that string is still going to be the exact same string it was when the browser asked your server for that .html file
You'll have to ask your server what the current title is using an xhr call ever X seconds and then refresh the title based on that.
I guess you should do an ajax call or listen to a some event to retrieve updated song title. The document.title = "BDR | <?php echo $radio_info['now_playing']; ?>"; string is generated on initial page load.
Okay. I figured it out.
I put this in my code:
<script type="text/javascript">
function songTitle(){
var xmlhttp;
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.title=xmlhttp.responseText;
}
}
xmlhttp.open("GET","songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
In my songTitle.php, it requests the song name from the Icecast server and displays only that.
Whenever the song changes now, it also changes the title.
I just had to integrate an XMLHTTPRequest like I did with how I displayed the song info on the page.

how to abort a xmlhttprequest before starting a new request?

I got a cgi-script the performs a search according to the query-string it gets submitted.
That works all fine.
But since the search can take some time and the user might start another search. I want the first search to get aborted before a second search is started, but if I insert a xmlhttp.abort() at the beginning of my AJAXRequest function the cgi-script doesn't get started at all.
Can anyone tell me how this could be performed?
Thanks in advance!
and here is the AJAX-code snippet
var xmlhttp;
function AJAXRequest()
{
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)
{
window.document.getElementById("resultlist").innerHTML=xmlhttp.responseText;
}
}
var queryString= "from=03-01-2006&to=04-30-2006&pattern=345";
xmlhttp.open("POST","../cgi-bin/search.exe?"+queryString);
xmlhttp.send();
}
Yea, XMLHttpRequest.abort() is a correct method to use for AJAX request aborting.
In my opinion your problem is more kind of design problem and not technical.
Therefore my suggestion is to review the flow of how the user interacts with your application.
For example, the classical solution is to show the progress bar or spinner and disable the "Search" button while your request is not completed and revert this state on success or error.
I found my problem.
I tried to abort a request object that has just been created. The object has to be global. At least that's the only way I see how to achieve this.

Send or get data from mysql using php ajax jquery - what is the secure method?

I have use Ajax and jquery for get data from database and send data, but when we use ajax or jquery methods, web page source view ,we can see details like below;
Ajax
<script type="text/javascript">
function showUser()
function showUser()
{
var str = document.getElementById('txtusername').value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="<span style='color:#FFF;font-size:10px;'>Enter username</span>";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","chkusername.php?q="+str,true);
xmlhttp.send();
}
</script>
In here you can see the get method and what are the sending values and also more things. I want hide these thing from source view, help me ..
You can't. Anything on the client side (HTML, CSS, JavaScript) is free for the user to see.
That's why anything security-related is on the server side, where it can be trusted (for the most part).
It's not a security risk if the user knows that to log in you go to /chkusername.php?q=username (or whatever). It is one, however, if you don't properly sanitise the input.

Categories