1

Basically, I have working solution for this, but I'm wondering if it could (should?) be done better in some other way.

I have table I'm creating in PHP with values from MYSQL. Each item in table has multiple values. In each line there is single link and clicking on this link fires up jQuery function. In each link there is also VALUE attribute with values from multiple MYSQL fields and joined with &&:

PHP code is:

    foreach ($this->_data as $l)
    {
        ?>
        ...
        <td><a href="#" class="clickMe" value="<?php echo $l->data1 . '&&' . $l->data2; ?>">Link</a></td>
        ...
        <?php
    }

And jQuery function to fire up when clickin' on link is:

$(".clickMe").click(function() {
    myData = $(this).attr('value').split('&&');
});

Script splits string in VALUE attribute on && and creates an array myData with values:

myData[0] => value passed from $l->_data1 in PHP

myData[1] => value passed from $l->_data2 in PHP

Is this the right way to do it?

1

2 Answers 2

1

It's fine, as long as you'll never have && in your data. You could use json_encode() in PHP and then decode this into an array in JavaScript. That would be a more standard solution.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought as much, that I should be using JSON, was just wondering if my dirty solution is acceptable :)
0

I would recommend against using && which looks like a boolean AND. Instead I would probably use something like a pipe to separate them val1|val2.

I think you're better off passing the whole joined string in to PHP and splitting it out there. It saves you work on both ends having to put the two resultant values into the proper post or get variables to send to PHP.

Then on the PHP side, it's a little easier to validate the one value's format before splitting it, as you can use a single regex like:

// Validate both values at once: 1 or more digits, a pipe, and one or more digits
if (preg_match('/^(\d+)\|(\d+)$/', $_POST['jqueryinput'])) {
  // explode() and use in PHP...
  list($val1, $val2) = explode("|", $_POST['jqueryinput']);
}

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.