Ajax .open returns empty error - php

I am updating my website to HTML 5. I had an Ajax script that called a PHP file, but it now doesn't work. The Firefox web developer add-on just throws an empty error containing only the line number. The line number points to the following line:
arequest.open('GET','userrating.php?h=' + h,true);
Here is the full script:
function ajaxRequest(){
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
if(window.ActiveXObject){
for(var i = 0; i < activexmodes.length; i++){
try {
return new ActiveXObject(activexmodes[i]);
} catch(e){
//suppress error
}
}
} else if(window.XMLHttpRequest){
return new XMLHttpRequest();
} else {
return false;
}
}
function resetRating(h){
var arequest = new ajaxRequest();
arequest.onreadystatechange = function(){
if(arequest.readyState == 4){
if(arequest.status == 200 && window.location.href.indexOf("http")==-1){
var response = arequest.responseText;
// do something
}
}
}
h = encodeURIComponent(h);
arequest.open('GET','userrating.php?h=' + h,true);
arequest.send(null);
}
I know I am passing the correct value for 'h' and that the userrating.php page works absolutely fine with that value. I have tried a few different Ajax scripts now and they all give the same blank error on the .open line of the script.
Can anyone please give me any pointers?
Thanks in advance, Ian

Related

script within a php page not executed when called using ajax

Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}

PHP & MySql and Ajax auto-suggest issue

I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>

Why is '\n' being pre-pended to my HTTP (AJAX) responseText?

This particular AJAX call is returning "\n" in front of the value returned by responseText.
It was previously not doing that and now when I test for a valid returned code with if (request.responseText == 100) it fails because it now equals "\n100".
I know I could strip off the "\n", but that would be a workaround and I would prefer to find the cause and fix it.
Here's my client-side code:
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function logDetails() {
var request,
Result = document.getElementById('Result'),
message = document.getElementById('message'),
url = 'ajax/login.user.php?',
us = document.getElementById('username').value,
pa = document.getElementById('password').value;
Result.innerHTML = 'Logging in...';
if (document.getElementById) {
request = AJAX();
}
if (request) {
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var r = request.responseText;
//var r = 100;
if (r == '100') {
Result.innerHTML = 'You are now logged in.';
window.location.href = "prebooks.php";
}
else if (r == '101' || r == '102') {
Result.innerHTML = 'Your login attempt failed.';
resetDetails();
}
else if (r == '103') {
Result.innerHTML = 'Sorry, you have no books subscription.';
}
else if (r == '999') {
Result.innerHTML = 'You have no more attempts!';
message.innerHTML = 'Please call us on (02) XXXXXXX so that we can assist you.';
} else {
alert(r);
}
}
};
}
// add my vars to url
url += "arg1="+us+"&arg2="+pa;
request.open("GET", url, true);
request.send(null);
}
Here's my server-side code:
<?= 100 ?>
Ok, I simplified it, but I've tried just echoing '100' directly and the issue remains.
UPDATE
I was mistaken that echoing '100' directly didn't solve the problem. It does. Sorry about that and thanks for pointing me in the right direction.
However, this does leave me with trying to find how the output is being polluted on the server-side.
On the server-side I have a class which handles the authentication and returns a value (100) to be echoed. This is the line:
echo $L->doLogin($pkg);
The lines relating to the return in the doLogin() method are:
$pkg[status]=100;
return $pkg[status];
And to be sure that a newline isn't leaking in some place, if I replace echo $L->doLogin($pkg); with echo 100; it works.
UPDATE 2 - SOLVED
It turns out that the problem was in an included class file which is included within the doLogin() method, which had recently been updated to include a single line-break at the top of the file, before the opening <?.
Many thanks to everyone for your input (I'd still be fumbling around in client-side code without it)!
I had the same problem and discovered (by adding dataFilter option to Ajax with an alert show the stringified JSON returned) that it was really the PHP script which was having syntax problem. PHP server was then pre-pending an HTML mini-document to signal the error. But then, when back to AJAX, as dataType was 'json', the whole returned PHP response was json parsed first, thus stripping off all the HTML prepended and leaving only newlines. These newlines in front of valid JSON returned data was causing the JSON data to be considered syntax error, and that was it ! With dataFilter option sending the raw data in an alert, I was able to see the PHP script initial error and once corrected, no more newlines pre-pended!
i had the same problem and i understood I hit Inter several times in end of page that i incloude to my page and when i delete it my responseText show without \n. :)
example:
_enter
_enter
_enter

ajax with JavaScript exception: unexpected end of input

I have an input field for a concept and when the user fills it out, he has to then check if the concept exists. So I made a check button, which checks a database using ajax and JavaScript to see if the concept exists. My problem is when using ajax and JavaScript I get this exception:
unexpected end of input
JS :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
}
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.send();
What is the exception and how can I solve it ?
PHP : function to check database and I always return true in it
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
return json_encode($d);
}
}
Demo: http://jsfiddle.net/Wiliam_Kinaan/s7Srx/2/
After looking at the code for a while, one thing that might be a suspect is your PHP.
Your function in php ends with a return command. What the AJAX call is actually waiting for is some data to be sent back. The return command simply passes that value back to the entity that originally called the function.
Try alter your function to echo the result as opposed to returning it. Save your return value for when you need the result to go into another PHP function, not when you are returning data to the client.
I only put this return command here for readability.
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
echo json_encode($d);
}
return;
}
Try this:
public function isExistedConcept($concpetName,$Ajax) {
if( $Ajax) return "1";
}
// This is a simplified version of what you're doing, but it returns "1" instead of "[true]"
// Now for the JS:
if( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var isexisted = xmlhttp.responseText == "1";
if( isexisted) {...}
If that doesn't work, try adding alert(xmlhttp.responseText) and see if you're getting anything other than what should be there.
try this :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
else{
console.log('error');
}
}
}
}
xmlhttp.send(null);

Strange JavaScript syntax error from an AJAX call to PHP

Long time reader, first time poster. Any help is greatly appreciated.
I have crafted an AJAX query using JavaScript. The script works correctly, and the interface does what I want, but Firefox is giving me an error message related to the PHP file being hit. It's strange, because it seems to suggest there's a syntax error in the PHP, but that doesn't make any sense. This is the error:
Error: syntax error
Source File: http://www.mysite.com/includes/ajax.php?action=checkpsudo&value=fd
Line: 1, Column: 1
Source Code:
yes
And the Javascript is below. Can anybody help me out? Thanks.
var ajaxobject = createajaxobjectObject();
function createajaxobjectObject() {
if (window.XMLHttpRequest) { // Mozilla, Safari,...
ajaxobject = new XMLHttpRequest();
if (ajaxobject.overrideMimeType) {
// set type accordingly to anticipated content type
ajaxobject.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
ajaxobject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxobject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ajaxobject) {
alrt('Cannot create XMLHTTP instance');
return false;
}
return ajaxobject;
}
function checkpsudo(value) {
if (value == "") {
document.getElementById('feedback').innerHTML = "Please select a psudonym";
document.getElementById('feedback').className = "fail";
document.getElementById('done').disabled=true;
} else {
ajaxobject.onreadystatechange = function() { check(); };
ajaxobject.open('GET', '/includes/ajax.php?action=checkpsudo&value='+value, true);
ajaxobject.send(null);
}
}
function check() {
if (ajaxobject.readyState == 4) {
//IF WE GOT OUR CHAT XML BACK CORRECTLY
if (ajaxobject.status == 200) {
var response = ajaxobject.responseText;
var value = document.getElementById('psudoentry').value;
if(response=='no') {
document.getElementById('feedback').innerHTML = "'" + value + "' is already being used";
document.getElementById('feedback').className = "fail";
document.getElementById('done').disabled=true;
} else {
document.getElementById('feedback').innerHTML = "'" + value + "' is available";
document.getElementById('feedback').className = "success";
document.getElementById('done').disabled=false;
}
} else {
alert('There was a problem with the request.');
}
}
}
My first instinct is that this is not a problem with your JS but with the XML being output by the PHP script.
It sorta looks like your PHP may be generating a notice or a warning - then the first thing in the generated XML isn't an XML element, but the string "Notice: etc. etc.", which causes the browser to complain that what it's getting doesn't match the format it expects. In my experience, sometimes this breaks everything and sometimes there isn't any obvious effect. I'd turn off notices and warnings on your server - and if that clears up the problem, then you know where to start tracking it down.
Why shouldn't that make sense? If the php file has a syntax issue than the ajax call will get back the error page your server spits out and that will show up in the FF error-console while FF tries to parse the response

Categories