0

Is there a way to have javascript create php code, to be executed when it runs on the php page? I'm trying to set the value of an input to , where div_id is a js variable, and inputs is a 2D associative array.

The problem is that it literally sets the value to "" instead of the value of the floor_type field. Everything else seems to work.

inputs_div.innerHTML += `<div id="`+div_id+`" class="dynamic_div">
                        <ul class="dynamic_ul">
                        <li><input type="text" onblur="$('.save').click();" placeholder="Flooring Type: Wood Floor, Tile, etc." name="inputs[`+div_id+`][floor_type]" maxlength="255" value="<?php echo $_SESSION['inputs']['`+div_id+`']['floor_type']; ?>"></li>
                        </ul>
                        </div>

I'm creating some html inputs dynamically with javascript, but I'm looking for a way to prevent them from getting cleared if the page is refreshed. Maybe there is a simpler way to make the inputs stay there?

My idea was to use ajax to run some php code from the onblur event of each input element, which saves the inputs[][] array into the session, so it doesn't get lost when refreshing the page.

4
  • PHP execute first and js after. in your code php need div_id which is causing problem Commented Feb 17, 2017 at 6:00
  • You can't print session in javascript Check this [stackoverflow.com/questions/3362417/… Commented Feb 17, 2017 at 6:00
  • You cannot use javascript variables into php Commented Feb 17, 2017 at 6:00
  • use session storage to persist data in a window tutorials.jenkov.com/html5/… Commented Feb 17, 2017 at 6:15

1 Answer 1

1

Use a hidden field to store $_SESSION[] value and then on document ready get the value of hidden field and set to the javascript variable.

<input type="hidden" id="hdn" value="<? php echo $_SESSION['inputs'] ?>" />


$(document).ready(function()
{    var session_value = $('#hdn').attr('value');    // now use session_value variable when set the innerhtml of inputs_div });
Sign up to request clarification or add additional context in comments.

3 Comments

hmm, the value of hdn end up being just "array", not an actual array. inputs is a 2D associative array. So I need to find a way to copy it from the session to a js array
Maybe i can save the inputs array into a cookie, or sessionstorage. But then i'm not sure what to put into the onblur event of each input
You can use Ajax on document.ready() to make a call to a php page and get Session array value in its response. In success callback function you can assign response data to a javascript variable.

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.