Why am I having ajax communication issue? - php

I've trying to send some infromation to a php file and display the result returned. First of all I'm not receiving any results from php file i.e. no value in xmlhttp.responseText. Instead of responseText, I tried putting 'something else' which made no difference. But when i comment out //if (xmlhttp.readyState==4 && xmlhttp.status==200), the result briefly appears.
What have I done wrong?
Ajax code looks like this:
var div = 'display';
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
writeBack (div, xmlhttp.responseText+'something else', 'red');
}
}
xmlhttp.open("POST","update_profile2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("rr="+id);
Php code:
..
if(isset($_POST['rr']))
{
die('connection made');
}
..

Every problem I've ever had with AJAX is usually caused by trying to submit an AJAX request using a 'submit' button in a form. If you are doing that, make sure you stop the .submit() .... Also, if you use jQuery, your AJAX code will look sooooo much better :)

As others users say with jquery the code looks much better.
However I am quite sure your problem is with this line:
xmlhttp.open("POST","update_profile2.php",true);
The request above access directly the update_profile2.php and gets back the entire content of the php page, not the output elaborated by the page.
This is way you access the page without asking the web server (with the php engine) to serve it for you. And of course the http call fails so the condition && xmlhttp.status==200 blocks the execution of the next instruction that fills in the div.
use instead:
xmlhttp.open("POST","http://localhost/update_profile2.php",true);
This will send a ajax http request to apache, il will run the php page and returns the answer of the page!

Related

javascript commands not executing after ajax loads PHP file

I have a PHP script being executed by AJAX, the PHP script loads everything fine except for js scripts in the actual PHP file which I am using to close divs(if the PHP file isnt run via AJAX all the scripts work FYI)..
this is the script not being run in the PHP file by ajax
echo "<script> closeOne('" . $postid . "'); </script>";
The JS scripts to close divs are included in the header of the page
This is the AJAX script I am using
<script type="text/javascript">
function mainload(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(str);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("loadmain").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mainload.php?page="+str,true);
xmlhttp.send();
}
</script>
Any help would be appreciated.
JS in the ajax response is not executed by default. You have to parse and identify JS statements, then run them using eval function of js. See this code as an example to start your own code:
var sc=xmlhttp.responseText;
sc=sc.replace(/[\n\r\t\v\u00A0\u2028\u2029]{1,}/gm, ''); //Remove all types of White Space
sc=sc.match(/<.*?script.*?>.*?<\/.*?script.*>/gm); //divide into array, all the script tags
Then you will loop each of the 'sc' and run the following in the loop:
abc=loop_var.replace(/<.*?script.*?>(.*?)<\/script>/gm, "$1"); //remove script/open close tags and get JS only
eval(abc);
If you add script element to innerHTML of a DOM element, JS wont run immediately.
because that script element is just added.
and that tag is not going to get parsed at all.
Ideally you should send a response in form of a JSON wrapped function.
You can send output like this from the PHP page.
echo "(function(){ closeOne('" . $postid . "'); })";
In response, you could evaluate this String containing the function using eval.
codeToExecute = eval(xmlhttp.responseText);
then call the function,
codeToExecute();
Note: sending functions from server and directly executing it using eval could be a security concern.
be careful and better use some JS libraray function to evaluate the string into a JSON object.
There will be String-To-JSON convertersin jQuery,prototype and sencha's libraraies.
Better use them or if the browser supports, JSON.parse is also a good option.
But I hope the concept is clear to you.
Alternatively,
You could just send the post id from server in a JSON and call closeOne on the response like this:
in PHP,
echo "{post_id:".$postid."}";
and when the response comes,
responseObject = eval("("+xmlhttp.responseText+")");
closeOne(responseObject.post_id);

What is ajax returning to me? (ajax call to php file)

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

xmlhttp.responseText; returning whole page html results instead of just list options?

I have a joomla component for managing workshops.
In the edit view, I have, among other fields, 3 select lists:
topic list
level list
prize currency
I'm trying to populate level list options depending on what has been selected in topic list options.
So in topic list onchange I've added a call to a .js file containing an AJAX request:
var xmlhttp;
function listUpdate(str)
{
if (str=="")
{
document.getElementById("jform_work_topic_level_idfk").innerHTML="";
return;
}
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert("Browser does not support HTTP Request");
return;
}
var url = document.URL+"&tid="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("jform_work_topic_level_idfk").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
It's working properly, and level list options are populated with desired values depending on what has been selected in topic list. The problem is that level list is not just populated with that options BUT ALSO with the options of topic list and prize currency.
I think that it's because xmlhttp.open("GET",url,true); is requesting the url that generates the entire form html and xmlhttp.responseText; is returning back the entire html page code. How can I do to just retrieve the options for level list?
Thank you very much!
You have two options when it comes to retrieving specific AJAX data.
You can either send a request to the server to only get certain values and let a server-side script split it up. For example, you could load a page with a GET argument of ?stuff=a and tell PHP or a CGI script to filter out extraneous content if ($_GET["stuff"] == "a"). This is probably the quickest and safest way to do it.
Your second option is to filter it out on the client right when you get the request, though this is slower and more risky.
Apologizes if I misread your question.
My english is not so good.so please try it to understand. I faced the same problem in asp.net.
if you have server page (aspx.cs) then remove whole html content from source(.aspx) only server side code should be written in code behind.
i try to show you my code through screen shot.
My javascript and html code is written in html page that is static page and server side
code written in ".aspx.cs" page and no html content written in ".aspx" only top 1 line will be there that is source code.
this is .aspx file means source code and this is server page and the last this is static page that is html page

simultaneously calling 2 functions via ajax with "onclick"

I have a problem using AJAX. I'm new to this so the answer could be simple!
So, i have this piece of code.
echo '<input type="button" onclick="opinion(1,\''.$v.'\'); op_status(1,\''.$v.'\');"/>';
which is written in php.
The 2 functions that are called via the onclick event, toggle AJAX in 2 different html divs. What i get is the outcome of the second function on both divs.
Any ideas why this could be happening?
Thanks!!
sorry for the inconvenience but this is my first post. so this is one of the 2 (identical, just with different variables) js scripts.
function op_status(op,pid)
{
if (op=="")
{
document.getElementById("opstatus"+pid).innerHTML="";
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("opstatus"+pid).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","post_op_stat_disp.php?ajxpid="+pid,true);
xmlhttp.send();
}
the file that is called makes some checks and outputs a text depending on that checks at a certain html div. the other js script does exactly the same, making some other tests and outputting some other text on another html div. :) however the outputs are the same text echoed in both the divs
First I'd add "var xmlhttp = null;" at the top of your function - that will locally scope the variable instead of making it global in nature - as #David Dorward points out. That would end up assigning the response handler of the ajax request in the second declared function (which ever that happens to be second) as the response handler for both ajax requests and you'd get the behavior you describe.
If you're still getting the same text in both div's then I'd suspect that both javascript functions are calling post_op_stat_disp.php instead of the opinion function calling what I would guess to be post_opinion_disp.php and as a result it is returning the same data to each div. Or (even more unlikely) that both post_opinion_disp and post_op_stat_disp are returning the same result.
Since this problem isn't really germain to AJAX but instead is likely a coding problem - I would suggest navigating manually to http://[server]/post_op_stat_disp.php?ajaxid=test and your other url and see what should be populated in both divs.
Then I would highly suggest that you abstract your ajax code to some common function so that you are not duplicating the http status code and xmlhttp instantiation logic. And though it may not help you solve this particular problem, it would reduce your code size to something along these lines if you followed #Jared Farrish's advice and used jquery:
function op_status(op, pid) {
if (!op) return $('#opstatus' + pid).html("");
$.get('post_op_status_disp.php?ajaxid=' + pid, function(r) {
$('#opstatus' + pid).html(r);
});
}
My money is on the var key word which will ensure you get two different xmlhttp objects instead of one global one.
But as most have already commented - you might want to post the generated results to help us out in helping you track this bugger down.
Thanks, let us know how it turns out!

Fetching file with AJAX, can't read PHP

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

Categories