Home » Php » php – Javascript – function doesn't get external input values from JQuery

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

Posted by: admin February 25, 2020 Leave a comment


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>
function saveObject(params) {
    console.log('p: ' + params);

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>
// Save object
var params = [
    'tableName=' + 'Test',
    '&ST_text=' + $('#aText').val(),
    '&NU_likes=' + $('#aNumber').val(),     
].toString().replace(/,/g, '');
<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&Answers:

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];