I have another question. XMLhttpRequests haunt me. Everything is now in the database but I need this data to update my page on firt page load or reload. The XHR is triggered in JavaScript file which triggers PHP-Script. PHP-Script access MySQL database. But how do I get the fetched records back into my JavaScript for page update. I can not figure it out.
First my synchronous XMLhttpRequest:
function retrieveRowsDB()
{
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","retrieveRowData.php", false);
xmlhttp.send(null);
return xmlhttp.responseText;
}
Then my PHP-Script:
<?php
$con = mysql_connect("localhost","root","*************");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sadb", $con);
$data="SELECT * FROM users ORDER BY rowdata ASC";
if (!mysql_query($data,$con))
{
die('Error: ' . mysql_error());
}
else
{
$dbrecords = mysql_query($data,$con);
}
$rowdata = mysql_fetch_array($dbrecords);
return $rowdata;
mysql_close($con);
?>
What am I missing here? Anyone got a clue?
PHP scripts don't return to JavaScript. You have to echo the data (encoded in some way, for example json_encode).
Really, if you're doing any kind of ajax, you'll make your life a lot easier by using an ajax library.
There's not much technically wrong with your code so far - you just need to actually do something with it.
In your PHP file, instead of return $rowdata;, you need to output it in some way. Currently, it's just sending a blank document back to the javascript, so you'll need to echo out the code. Normally, when using a number of objects to be returned to javascript, JSON is a good format. Check out json_encode.
On the other side, in the js, you'll need to take the response and update the page in some manner. Currently, you're just returning it again.
I suggest you go through a few ajax tutorials, and consider using a framework such as jQuery to do the heavy lifting for you. You might also want to do a bit of reading on this topic, as you have some fundamental misconceptions.
The problem is xmlhttp.responseText, it doesn't exist at the time, try adding this just before your return statement:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
doSomething(xmlhttp.responseText);
}
}
}
Basically you have to wait until the data is available, it takes time to make an HTTP request and get a response.
Related
I am searching for this from yesterday, Do not know, I am unable to implement, or going in wrong direction.
My currently ajax function which is working with local server
function tooltipajax(r_ID)
{
var str ;
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('span'+ r_ID).innerHTML = xmlhttp.responseText ;
}
}
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
xmlhttp.send();
}
PHP code:
print("<tr bgcolor=\"#EEEEEF\">");
print("<td class='normal' id=\"serialno\" onMouseOver='tooltipajax(this.id)'>
<a class=\"tooltip\" >Serial Number <span id=\"spanserialno\"
class=\"custom info\"></span> </a></td>");
print("<td bgcolor = \"#FFFFFF\" ><b>$serial</b></td>\n");
print("</tr>\n");
How can I get data from another server?
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
I want to get from
http://iphere/filename.php
If you use use jQuery like so, this works.
function tooltip_ajax(r_ID) {
$.ajax({
url: "http://iphere/filename.php?id=" + r_ID,
context: document.body,
success: function(data) {
if(data) {
$('span' + r_ID).html(data);
}
}
});
}
That's tested with a different server and it works.
In order to retrieve data from another server using AJAX, you will need to utilize JSONP. This is due to Cross-Domain restrictions on AJAX requests. To expand on this further, if you wanted to make an AJAX request from a page located at http://test1.com, to a page / script located at http://test2.com, you would not be allowed.
Check out this article for more information: http://www.jquery4u.com/json/jsonp-examples/
Basically, JSONP involves adding a temporary SCRIPT tag to the page, which CAN load external content. The URL for this SCRIPT tag contains data, and a callback function name. The JSONP should then respond with the data, enclosed in a call to that function. Of course, the one downside is that the target server must support JSONP requests.
One alternative is using a bridge PHP script locally, that utilizes CURL to make the request, and return the information to your page, via AJAX.
For a bit more information regarding utilizing CURL in PHP, take a look at this article: http://codular.com/curl-with-php
I am quite a noob to AJAX Requesting and PHP and I got a question:
I am trying to do a GET request to a php file on my wamp server but it's responseText stays blank and when I check the status code when the readyState is 4, it's 0.
When I execute the php file in the browser it returns my expectation: An array with JSON Objects.
Does anyone know the answer?
Javascript code:
this.getCars = function(id) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var that = this;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.status);
//that.lastTableCars = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://localhost/getCars.php?q="+id,true);
xmlhttp.send(null);
}
PHP:
<?php
$q=$_GET["q"];
$con = mysql_connect('127.0.0.1', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("autobay", $con);
$sql= "SELECT * FROM autoos WHERE id = '".$q."'";
$result = mysql_query($sql);
$info = [];
while( $row = mysql_fetch_assoc( $result)){
$info[] = $row;
}
echo json_encode($info);
mysql_free_result($result);
mysql_close();
For one, use jQuery to help troubleshoot. It's going to make your life so much easier. Even if you end up wanting to use raw xmlhttprequest, I'd suggest bringing jQuery in to rule out xmlhttprequest problems in your code, and more quickly hone in on the real issue.
Translation: I'm not comfortable with raw xmlhttprequest, so in order to help you let's switch to jQuery. You can go back when the issue is resolved! =)
this.getCars = function(id) {
$.get("/getCars.php?q="+id, function(data) {
alert("response from server: " + data);
});
}
http://api.jquery.com/jQuery.get/
Also make sure you are using Chrome Dev Tools or Firebug to inspect the response from your server, it's possible that it's failing there.
Update:
Make sure your HTML page (that is making the ajax call) and the PHP script are running on the same domain (localhost). I noticed you were specifying the full http://localhost URL in your ajax call. Ajax does not work cross-domain (though there are workarounds, look at JSONP if you really need to do this cross-domain). Best bet is to get your HTML page loading from the same domain as the PHP script.
Update 2:
Actual issue was that the OP was loading the HTML from a folder on his computer (not via http://localhost) and trying to make an ajax call to http://localhost. The ajax call was failing since this is technically cross domain.
I am pretty much brand new to ajax. This is an ajax call which I am using to retrieve information from a sql database using a php document called "bridge.php". I just cannot seem to understand what I am getting back from this, if anything at all. Is it an array? an object? Am I not getting anything back because I'm using a get when I should be using a post? The amount of info that I'm trying to get back would not fit in a get, but the amount I'm sending through the call is small enough to fit.
<script type="text/javascript">
function refreshPro(namex){
alert(namex);
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("port_work").innerHTML=xmlhttp.responseText; //what is xmlhttp.responseText?
}
}
xmlhttp.open("GET","../bridge.php?pro="+namex,true);
xmlhttp.send();
}
</script>
and now for the php(bridge.php) which takes the get var from the url and queries the database, which I know this part works okay by itself...
<?php
$pro = $_GET["pro"];
$sql = "SELECT * FROM portfolio WHERE title LIKE \"%$pro%\"";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<div id="portfolio_item">
<h2><?php echo $row['title']; ?></h2>
<img src="<?php echo $row['image_paths']; ?>" alt="<?php echo $row['title']; ?>" />
<p id="portfolio_desc"><?php echo $row['description']; ?></p>
</div>
<?php
}
?>
And yes, I've done my homework. I've studied these two other posts but one starts talking about JSON which I know nothing about, and the other didn't quite seem to match my problem, but I still found the answer kinda useful. Returning AJAX responseText from a seperate file and Ajax call not returning data from php file
You are getting back plain HTML from the server. The responseText variable is a string containing the plaintext response to the GET request.
A GET request is like any other browser request you normally perform when visiting a given URL. Thus you can test what the bridge.php script sends for a given input by visiting http://url/to/bridge.php?pro=<someValue> using your browser of choice.
It doesn't matter the amount of data you get back, what matterns WRT using a POST or a GET is how much data you want to put in (GET request can only take 255 chars of data, POST is technically unlimited).
If you get nothing visiting the bridge.php script directly, this indicates that this script may be failing resulting in a 500 Internal Server Error code. This doesn't get caught by your javascript code since you're explicitly checking that the code is 200 (success) before doing anything with the response.
I would add:
... snip ...
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("port_work").innerHTML=xmlhttp.responseText;
}
else
{
alert('There was a ' + xmlhttp.status + ' error :(');
}
}
... snip ...
Using jQuery for this makes it rather simple:
<script type="text/javascript" src="path/to/jquery.js">
<script type="text/javascript">
function refreshPro(namex)
{
$.ajax({
type: "GET",
url: "../bridge.php",
data: {
pro: namex
}
}).done(function( msg )
{
$("#port_work").html(msg);
});
}
</script>
First of all just echo 0 or 1 or any damn keyword 'Hello world' from bridge.php.
the code
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
says that if everything is goes fine. I.E if the path to the bridge.php then it would go inside this if condition. and will alert response.
If this works perfectly then your code shold work too.
also see the answer mentioned by #ccKep. It is easy to use.
In addition use the tool like Mozilla firebug. So that you can understand that what is going on. Hope this helps.
The Ajax runs on the client not on the server, so you need to provide the url of your server. This is not going to work:
xmlhttp.open("GET","../bridge.php?pro="+namex,true);
What might work is:
xmlhttp.open("GET","http://yourhost.com/bridge.php?pro="+namex,true);
I am going to bed soon, so I will not be on until the morning, but I have been struggling with trying to find a javascript/jquery method that solves my problem. I am trying to make a chat box feature where once a post is submitting it is then echoed back out and users on both ends can see it. I know that I need to use javascript and or jquery. Right now I am using a very inefficiency system:
<script language='javascript' type='text/javascript'>
setInterval( function() {
$('#responsechat').load('echogetconversation.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>');
}, 100);
</script>
The only reason that I am using it is because it is the only way I know how to project new posts to both users. I was wondering if someone knew a way to do this. Once a post is submitted, it fades into a div and both users can see it, not only the user who submitted it, so it is like a facebook chat in a way. I have no idea about any possible solutions, and have done research, but I could not find any that i could get to work. Any help and/or insight to what I should do next would be appreciated.
What you are looking for is ajax long pulling, also called Comet (it's a silly pun). The basic idea is simple--instead of polling the server, you send your ajax request and the server blocks on it until it gets a new message.
"Blocking" here simply means it does not send a response. You get your request then first up a thread (is that what you would do in PHP? I've only ever used node.js for this) and wait until something changes before sending the response back to the client.
Once the client has a response, it sends another request immediately.
There is one other trick: requests can time out. This means that the server should send a response back after a certain time even if nothing has updated.
This methodology is good if you have to support older browsers; if you can ignore those and stick to newer ones, you can use "websockets".
There are libraries that help you use websockets or fall back on Comet. I think the most popular one is socket.io.
Coincidentally, if you're not tied to PHP, I really suggest using a different server. node.js is a great option--it is a natural fit for this sort of problem and you can write the server-side code in JavaScript, which you already know. Even Facebook--the bastion of PHP--used a different language (Erlang) for their chat backend.
So, in summary: use socket.io. If you can, try using a different backend, although PHP is fine too.
If you don't want to use another language you can simply do it by AJAX..
Just set an interval and update the PHP-generated div's html.. and when you send a message then the reply would be the updated div -html so that both you and the user can assure that their message is posted successfully.. There's a snippet of my own chat system code : look:
function updMsg() {
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()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","Msg.php?pg=1",true);
xmlhttp.send();
}
function sendMsg()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
msg=document.getElementById('msgfrm').value;
sender='<?php echo $name;?>';
xmlhttp.open("GET","Msg.php?msg="+msg+"&sender="+sender+"<?php if(isset($_GET['a']) && $_GET['a'] = 1) { echo "&a=1"; } ?>" ,true);
xmlhttp.send();
document.getElementById('msgfrm').value="";
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
}
function interval() {
updMsg();
t=setTimeout(interval(),500);}
interval();
This code is actually only PHP and Javascript. It's not sufficient to include the whole jQuery Library just for using the AJAX capability. right?
I have checked the suggestions that came up before posting, hope I didn't miss anything now.
I have a piece of code that I use to get txt-files for my website but now I need to redo the code so it gets both txt and php-files, but it just won't read the php-script. I'm a bit afraid to mess up the code at this moment so I'm walking on the safe side of the road and ask here if anyone knows a good add to the code. It's quite embarrasing that I still have codes for IE 5&6 in it, so if you wish to remove that at the same time, go ahead. I won't hate you for it, I promise.
UPDATE:
I have four files:
html - Calling the .js-file with the ajax-script.
js - With all my javascript(and simular)-codes.
php - That contains... Well, you get the point.
I have to call the php-code somehow, like I call my txt-files, but of course so the php works as it should. I am very new to AJAX, so I don't dare to mess around with this code at the moment, but I figured that I might be able to add some kind of if-statement that calles the php-file as it is intended to be.
But I have no clue what that code might be and where to put it for things to work accordingly. Any help would be appritiated and credited in the code, of course.
Heres the AJAX-code that is contained within the .js-file:
/*Load the link.*/
function loadXMLDoc(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.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("leftCol").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
/*Highly unnecessary, but I wanted to see if it worked and it looks better on the .html-page.*/
function get_link(url)
{
loadXMLDoc(url);
}
As the above commenter said, it is best to use a 3rd party tool for such things - if for no other reason than to greatly increase cross-browser compatibility.
if you were to use jQuery, the code would be reduced to.
function get_link(url)
{
$.ajax({url: url, success: success:function(result){
//the code / resulting string will be in the result variable.
}});
}
jQuery CDN Hosted: http://code.jquery.com/jquery-1.5.min.js
Let me ask this... if you change your code to
function get_link(url)
{
window.location=url;
}
Does your web browser successfully navigate to the page you are trying to retrieve via AJAX? If not, there is likely a problem with your PHP syntax.
it just won't read the php-script
It's a rather vague statement, but here are few pointers that could be the solution :
PHP file are interpreted on the server so when you do an Ajax call to that page what you receive on the client side is the result of that php script, not his content.
You are assigning the result of the query directly in the HTML, if the result contains data that does not render anything, you won't see anything. For example the content <script>Text here bla bla bla</script> will just show nothing.
If you want to make sure you get some data back from a file, you can just alert the content when you receive it.
Make sure your path to your PHP page is correct. To detect if the file is not giving a 404 error code or any other error code, you can use this :
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementById("leftCol").innerHTML = xmlhttp.responseText;
} else {
alert("Error " + xmlhttp.status);
}
}
}