I would like to call a function onclick, but with a json_encode parameter like this:
<a href="#" onclick="javascript:table1Modif(<?php echo substr(json_encode($res['base']),1,-1); ?>);return false;">
And the Jquery function just alert the parameter:
<script>
function table1Modif(key){
$('#table1').html(function() {
alert(key);
});
}
</script>
But I have an “undefined” error!
I am sure that it’s due to json_encode, but I don’t know how to solve it.
Thank you!
It looks like you are passing a string to
json_encodein order to generate a JavaScript string literal (which is not valid JSON).You are using
substrto remove the quotes from this string.JavaScript will therefore see an identifier (which in that context will be treated as a variable).
You need a string literal, so the first thing to do is remove the substr call.
This will create a new problem. You are inserting the string into an HTML document, but not expressing it as HTML. The
"character at the start of the string literal will therefore be treated as end of attribute value, which you don’t want.When inserting non-HTML content into an HTML document you need to express it as HTML. Run the code through the
htmlspecialcharsfunction to do this.Incidently, I’ve removed the entirely useless
javascript:label. You don’t have a loop tobreakorcontinuefrom so it isn’t doing anything. While you’re at it, you should replacehref="#"with something more sensible. Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.