1

Below is my javascript code! I'm trying to increment the index of array $arr everytime the user clicks a button. The array is defined in a separate php tag! Where am I going wrong?

function option1() {
var i = 0;

document.getElementById("btn0").value = "newButtonValue";
document.getElementById("question").innerHTML = 
"<?php echo $arr["results"][i++]["question"] ?>"; 
}
4
  • 1
    Where am I going wrong? var i=0 is inside option1 and it is initialized to 0 every time option1 is invoked. Commented Jan 1, 2018 at 13:03
  • here <?php echo $arr["results"][i++]["question"] ?> you are mixing an Array in the backend with an index in the frontend. The two are executed (and therefore available) at different times and on different computers. Commented Jan 1, 2018 at 13:06
  • @Thomas if I add an integer instead of i++ the code runs fine!! It just wont take a variable in the square brackets i.e in [i++] or even [i] Commented Jan 1, 2018 at 13:11
  • @ZaidWaseem because with the static integer, this is all php code now and runs solely in the backend. Commented Jan 1, 2018 at 13:18

2 Answers 2

1

Where your compiler return output to browser your php code was compiled and you can't run it such as javascript.

you can use this js:

var arr  = <?php echo json_encode($arr["results"]);?>;

function option1() {
    var i = 0;

    document.getElementById("btn0").value = "newButtonValue";
    document.getElementById("question").innerHTML = arr[i++]["question"];
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'd extract the var i=0; out of the function, or the i++ is pointless
That's right. check arr[i++] index for undefined bug too.
0

.html file

<button onclick="addIndex(this)" queNo="0">newButtonValue</button>

in .js file

function addIndex(btn) {
    var i = btn.getAttribute("queNo")
    console.log(i);
    btn.setAttribute("queNo", i++);

    document.getElementById("question").innerHTML = "<?php echo $arr['results']["+i+"]['question'] ?>"; 
}

Hope it's help you

Comments

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.