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);
bfavaretto
72k18 gold badges118 silver badges162 bronze badges
asked Mar 14, 2012 at 21:09

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 + ')');
answered Mar 14, 2012 at 22:06
Sign up to request clarification or add additional context in comments.

3 Comments

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"]
has "this" a value? use console.info(this); or console.info(this.responseText); .Are you receiving something??
I did a mistake but rectified it and now your solution works perfectly. Many thanks for showing me this simple way to solve it!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.