0

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?

1
  • Use JSON as an intermediary. It will save you much headache. Commented Sep 28, 2014 at 17:39

3 Answers 3

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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).

3 Comments

Your attribute now looks like href="javascript:add(". That isn't going to work.
close but not correct this is right code <td><a href='javascript:add(<?php echo $q->id?>,"<?php echo $q->info?>")'>Edit</a></td>
After editing, that will only work if the string contains no ' characters, no " characters and no new lines.
0

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

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

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.