JSidiot JSidiot - 5 months ago 15
jQuery Question

Uncaught SyntaxError: Unexpected token } when trying pass data to jquery variable

I'm trying pass data to jquery via

onclick


There is jquery function:

function handleit(cId, anotherId) {
var campaingID = cId;
var another = anotherId;
var post = "action=remove&campaign_id=" + campaingID + "&anotherid=" + another;
$.ajax({
type: "post",
url: "ajax/phphandler.php",
data: post,
cache: false,
success: function(html) {
$('#ready').html(html);

}
});
return false;
}


and there is
onclick
code

<td><input class="btn btn-default" type="submit" data='.$row2['campaign_id'].' value="submit" onclick="return handleit("'.$row2['campaign_id'].'","test")"></td>


rendered html

<td><input class="btn btn-default" type="submit" data=43 value="submit" onclick="return handleit(" 43","test")"></td>

Answer

The issue is that your HTML winds up looking like:

<input class="btn btn-default" type="submit" data=foo value="submit"
    onclick="return handleit("campaign_id","test")">
                             ^           ^ ^    ^

When defining an attribute, you can't nest " inside ". The HTML would need to look like:

<input class="btn btn-default" type="submit" data=foo value="submit"
    onclick="return handleit('campaign_id','test')">
                             ^           ^ ^    ^

How you accomplish that depends on whatever server-side language you're using, but probably involves escaping quotation marks:

<td>
  <input class="btn btn-default" type="submit"
    data="'.$row2['campaign_id'].'" value="submit"
    onclick="return handleit(\''.$row2['campaign_id'].'\',\'test\')"
</td>
Comments