Home » Jquery » php – Javascript – function doesn't get external input values from JQuery-Exceptionshub

php – Javascript – function doesn't get external input values from JQuery-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have the following function stored in my sdk.php file:

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
function saveObject(params) {
    console.log('p: ' + params);
}
</script>

In another php file – index.php – I call that function passing input values as parameters:

Text: <input type="text" name="aText" id="aText"><br>
Number: <input type="number" name="aNumber" id="aNumber"><br>
<script>
// Save object
var params = [
    'tableName=' + 'Test',
    '&ST_text=' + $('#aText').val(),
    '&NU_likes=' + $('#aNumber').val(),     
].toString().replace(/,/g, '');
</script>
<a class="btn btn-info" href="#" onclick="saveObject(params)">Save Object</a>

Now, if I type something in the 2 input files and hit the Save Object button, this is what I get in the Chrome console:

p: tableName=Test&ST_text=&NU_likes=

Why am I not getting the aText and aNumber values in the string I compose?

I’m asking this because if I move the params array into the saveObject() function, I get the values.

What am I doing wrong?

How to&Answer:

Your params are not being defined because the script is only executed on page load. You need to define the values after an event, like clicking the Save Object button.
Try something like this:

<a class="btn btn-info" id="saveButton" href="#">Save Object</a>

In jQuery:

$("#saveButton").click(function () {
var params = [//define params here];
saveObject(params);
});