0

I want the result of this Ajax request to fill the JavaScript hintArray. That is, I want hintArray to contain the same values as $row. Can this be done in a simple way? How should the php file output be made? Is hintArray = JSON.parse(this); correct?

Many thanks

JavaScript

var hintArray = new Array();
postAjaxRequestFunktion(minFunktion, 'getHint.php', 'id =1')
function minFunktion()
{
  hintArray = JSON.parse(this); 

}

function postAjaxRequestFunktion(minFunk,minUrl, mittArg)
{
   var contenttype = 'application/x-www-form-urlencoded'
   var minRequest        = new skapaAjaxObjekt(minFunk)
   if (!minRequest) return false
   minRequest.open('POST', minUrl, true)
   minRequest.setRequestHeader('Content-type',   contenttype)
   minRequest.setRequestHeader('Content-length', mittArg.length)
   minRequest.setRequestHeader('Connection',     'close')
   minRequest.send(mittArg)
   return true
}

function skapaAjaxObjekt(minFunk)
{
   try       { var   minRequest = new XMLHttpRequest()                   }
   catch(e1) { try { minRequest = new ActiveXObject("Msxml2.XMLHTTP")    }
   catch(e2) { try { minRequest = new ActiveXObject("Microsoft.XMLHTTP") }
   catch(e3) { minRequest = false }}}
   if (minRequest) minRequest.onreadystatechange = function()
   {
      if (this.readyState == 4 && this.status == 200 &&
          this.responseText != null)
            minFunk.call(this.responseText)
   }

   return minRequest
}       

getHint.php

$result = mysql_query("SELECT hint01,hint02 FROM main WHERE id = '00000001'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

1 Answer 1

1

you should encode your php array with

json_encode($your_array);

and decode it in javascript with eval

your_js_array = eval('(' + yourJSONtext + ')');
3
  • I added this to the .php file: echo json_encode($row); And this to JS: function minFunktion() { hintArray = eval('(' + this + ')'); } But it doesn't work. The JS array is empty. What am I doing wrong? If I instead add this to JS: function minFunktion() { document.getElementById('hint').innerHTML = this } This is written in the hint element: ["hintText1"," hintText2"] Commented Mar 15, 2012 at 6:07
  • has "this" a value? use console.info(this); or console.info(this.responseText); .Are you receiving something?? Commented Mar 15, 2012 at 14:34
  • I did a mistake but rectified it and now your solution works perfectly. Many thanks for showing me this simple way to solve it! Commented Mar 15, 2012 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.