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);
bfavaretto
72k18 gold badges118 silver badges162 bronze badges
1 Answer 1
you should encode your php array with
json_encode($your_array);
and decode it in javascript with eval
your_js_array = eval('(' + yourJSONtext + ')');
answered Mar 14, 2012 at 22:06
Packet Tracer
3,9245 gold badges28 silver badges37 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Fred
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"]
Packet Tracer
has "this" a value? use console.info(this); or console.info(this.responseText); .Are you receiving something??
Fred
I did a mistake but rectified it and now your solution works perfectly. Many thanks for showing me this simple way to solve it!
lang-js