Vladimir Štus
Vladimir Štus

Reputation: 49

JavaScript passing string and integer from PHP into function

I am trying to pass both a string and an integer into the same function, howe I have issue with quotes. I figured out that the error is in the echo $q->info part, I must use double quotations on this code.

Can someone help me to write this $q->info, but to get real value not $q->info?

My code so far is

<td><a href="javascript:add(<?php echo $q->info?>,<?php echo $q->id?>)">Edit</a></td>

and the js function

function add(var,var2)

Can someone help me with this?

Upvotes: 0

Views: 147

Answers (3)

Kayani
Kayani

Reputation: 409

Here is the answer of your question: Preg replace part of string?

echo substr($string, 0, strpos($string, "-DELETED"));

Upvotes: 0

Quentin
Quentin

Reputation: 943157

You have a PHP variable. To convert it to a string representation of a JavaScript literal, use json_encode. To make it safe to insert into an HTML attribute value, use htmlspecialchars.

<td><a href="javascript:add(<?php echo htmlspecialchars(json_encode($q->info)); ?>,<?php echo htmlspecialchars(json_encode($q->id)); ?>)">Edit</a></td>

That said, it would be better to write your code to follow the principles of Progressive Enhancement and Unobtrusive JavaScript.

<td>
    <form action="edit" method="post">
        <input type="hidden" name="info" value="<?php echo htmlspecialchars($q->info); ?>">
        <input type="hidden" name="id" value="<?php echo htmlspecialchars($q->id); ?>">
        <input type="submit" value="edit">
    </form>
</td>

And then something like:

document.querySelector('form').addEventListener("submit", function (evt) {
    evt.preventDefault();
    add(this.elements.info.value, this.elements.id.value);
});

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

You need to quote the string.

<td><a href="javascript:add('<?php echo $q->info?>',<?php echo $q->id?>)">Edit</a></td>

Also, var is an invalid variable/argument name (identifier).

Upvotes: 0

Related Questions