ajax with JavaScript exception: unexpected end of input - php

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

Related

innerHTML modification visible after an `alert` but not otherwise

All,
I have a fairly simple javascript script that changes some text in my html page. The weird thing is that the data is only changed if I have an alert. If I hide the alert as a comment, the data doesn't appear on the webpage. To be specific, here are the relevant pieces of the JS code:
var index=0;
var xmlObject=null;
function calcIndex(){
return index++;
}
function showNextName(){
retrieveNextName();
var someText = xmlObject.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById('nextName').innerHTML=someText;
}
function retrieveNextName(){
var index=calcIndex();
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "Ajax_retrieveName.php?index=" + index;
request.open("GET", url, true);
request.onreadystatechange = createXml;
request.send(null);
alert("abc");
//If the alert above is missing, the html is not modified...
}
function createXml() {
if (request.readyState == 4) {
if (request.status == 200) {
xmlObject = request.responseXML;
}else{
return;
}
}else{
return;
}
}
Does anyone know what might be causing that?
The problem is that XML object is not immediately available, because the request isn't finished yet, so the callback hasn't been called yet. (Alerting allows the request to finish in the time before you clock the alert box away.)
A better solution would be to have an updateElementHtml(newHtml) function and call that from within the callback.

PHP AJAX Confirm on Form Submit

I have a small form which contains a first name, last name and a date. On clicking to submit the form I want it to check the database for a duplicate entry (with Ajax), and if there is already 1+ entries, present a confirm window confirming another submission. The confirm shouldn't show if there aren't any entries.
For some reason it seems to be presenting the confirm without the result from the Ajax PHP page. If I introduce an alert after the xmlHttp.send(null) line, it gets the text from the PHP (as wanted), making me think I misunderstand the order the code is executed. Here is the code:
Javascript:
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+first;
url=url+"&last="+last;
url=url+"&date="+date;
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
result = xmlHttp.responseText;
alert("RESULT="+result);
if(result != "clean") {
var validate = confirm(result);
return validate;
}
}
}
xmlHttp.open("GET",url,true);
var test = xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
PHP:
// DATABASE CONNECTION INFORMATION REMOVED
$first = $_GET['first'];
$last = $_GET['last'];
$date = date('Y-m-d',strtotime($_GET['date']));
$sql = "SELECT COUNT(*) AS count FROM Table WHERE First='$first' AND ".
"Last='$last' AND Date='$date'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if($row['count'] > 0) {
if($row['count'] == 1) {
echo "There is already an entry for ".$first." ".$last." on ".
date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
else { // plural version of the same message
echo "There are already ".$row['count']." entries for ".$first." ".
$last." on ".date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
} else {
echo "clean";
}
Here is an answer using synchronous AJAX. This way, you don't have to overload the default form handling to get it to work. However, all javascript will be blocked while the confirmation request is running, which means your web page may appear to come to a screeching halt for however long the confirmation request lasts.
This function will return true if the record should be added, and false otherwise.
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return false;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
var validated = true;
var result = xmlHttp.responseText;
if (result != 'clean')
validated = confirm("RESULT="+result);
return validated;
}
This line of code return undefined.
var test = xmlHttp.send(null);
What you have to understand is that the send() call returns immediately and Javascript keeps running. Meanwhile, your AJAX request is running in the background. Also, your onreadystatechange handler is called once the request is done, whether it takes 10ms or 100s, and its return value is not received by the rest of your code.
I think what you wanted to submit the form AFTER the confirmation was finished. You only know when the request is finished from inside your onreadystatechange handler. The problem here is that, in order to wait for the AJAX request to finish you have to override the default behavior of the form.
You'll need to call preventDefault() on the form-submit event, and then submit the data manually after confirmation.
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
var confirmed = false;
var result = xmlHttp.responseText;
if (result == "clean")
confirmed = true;
else
confirmed = confirm("RESULT="+result);
if (confirmed) {
var url = "addData.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
window.location = url;
}
}
}
Also, when you're building your URL you should use encodeURIComponent.
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);

AJAX and auto-refreshing

im trying to get a bit of html to refresh every 1 second with AJAX, I made this code my self with bits from different websites that I found. Im trying to understand how it all works.
I want to be able to refresh the page without reloading it in the browser and I want the JS function AJAXdisplay(); to run every one second with the variables I send to AJAXreturn(); when I call it.
When I call AJAXreturn(); I want it to run AJAXdisplay(); once to print out the html from my php file, on my body if the index file I want somthing like this
<body onClick=:AJAXdisplay(same variables as used when the page was made);">
</body>
here is my code:
function getHTTPObject(){
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function AJAXsend(url) {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("POST",url);
httpObject.send(null);
}
}
function AJAXreturn(url,pageName){
httpObject = getHTTPObject();
if (httpObject != null) {
if (navigator.appName != "Microsoft Internet Explorer") {
history.replaceState("", "", "index.php?page=" + pageName)
}
httpObject.open("POST",url);
httpObject.send(null);
AJAXdisplay(httpObject,url,pageName);
}
}
function AJAXdisplay(httpObjectIn,urlIn, pageNameIn){
httpObjectIn.onreadystatechange = function(){
if(httpObjectIn.readyState == 4){
document.getElementById('outputHTML').innerHTML = httpObjectIn.responseText;
AJAXdisplay('function(httpObjectIn,urlIn,pageNameIn)',1000);
}
}
}
To make javascript refresh, you should use the setInterval(); function. Here's what your looking for:
var timer = setInterval ("AJAXdisplay(variable);", 1000);
And if you ever need to stop the refresh you use:
clearInterval (timer);

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

How to pass a javascript object array to php using POST

Lets say I have an array of javascript objects, and I am trying to pass those objects to a php page to save them into a database. I have no problems passing a variable to the php and using $_POST["entries"] on that variable but I can't figure out how to pass an entire array of objects, so I can access my objects.entryId and .mediaType values on the php page.
Oh and before anyone asks, yes the reason I need to do it this way is because I have a flash uploader, that you guessed it.. uploads into a CDN server (remote) and the remote server only replies back with such js objects.
Thanks for any help anyone can provide.
Here is my JS functions:
function test() {
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
var parameterString;
for(var i = 0; i < entries.length; i++) {
parameterString += (i > 0 ? "&" : "")
+ "test" + "="
+ encodeURI(entries[i].entryId);
}
xmlhttp.open("POST","ajax_entries.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameterString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = handleServerResponseTest;
xmlhttp.send(parameterString);
}
function handleServerResponseTest() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
maybe you need to take a look at json and jQuery ajax methods:
.- http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
.- http://us.php.net/json_decode
The turorial is maybe a little outdated because jQuery last version is 1.3.x but you will get an idea on that and about the PHP json functions... if your server does not have the json extension enabled you can use some php classes:
.- http://google.com.co/search?rlz=1C1GPEA_enVE314VE314&sourceid=chrome&ie=UTF-8&q=php+json+class
good luck!
I too had the same trouble. But googling dint help.
I tried myself to tweak and test. And I got it. I am using POST method though. Please try the idea with GET method. Here is the idea:
Append the array index value within square brackets to the Post/Get variable name for array. Do this for each array element.
The part var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2; of the following script would give you a hint.
This is the test JS, I used (Again this uses POST method not GET):
var xmlAJAXObject;
function test() {
xmlAJAXObject=GetxmlAJAXObject();
if (xmlAJAXObject==null) {
alert ("Oops!! Browser does not support HTTP Request.");
return false;
}
var namevalue1=encodeURIComponent("Element 1");
var namevalue2=encodeURIComponent("Element 1");
var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2;
xmlAJAXObject.open("POST", "test.php", true);
xmlAJAXObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlAJAXObject.setRequestHeader("Content-length", parameters.length);
xmlAJAXObject.onreadystatechange=stateChanged;
xmlAJAXObject.send(parameters);
}
function stateChanged() {
if (xmlAJAXObject.readyState ==4) {
if (xmlAJAXObject.status == 200) {
alert('Good Request is back');
document.getElementById("show").innerHTML=xmlAJAXObject.responseText;
}
}
}
function GetxmlAJAXObject() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) {
// code for IE6, IE5
return new ActiveXObject("Microsoft.Microsoft.XMLHTTP");
}
return null;
}
This worked for me. Sorry for the formatting and incomplete code. I meant to give a direction. Google reault websites couldn't give a solution. Hope you find this useful.

Categories