Reputation: 1123
I have an ajax block that is processing a json response from an external API. I have a field for the object called status and depending on the status, I would like to display the corresponding tooltip. Currently, I am trying to do this with an if statement but but I am getting an error.
The error is:
Uncaught SyntaxError: Unexpected token if
Ajax block
<script type="text/javascript">
$.ajax({
url: "pull_overview",
dataType: "json",
cache: false,
success: function(data){
if ( data == null ) {
$('#ajax-loader').hide()
$('#overviewlist tbody').append("<tr><td colspan='100'><h3><center>You have no recent transactions.</center></h3></td></tr>");
}
else {
$('#ajax-loader').hide()
$.each(data, function(index, element) {
$('#overviewlist tbody').append("<tr><td>" + element.name + "</td><td>"
+ element.time + "</td><td>"
+ element.type + "</td><td>"
+ element.change_in_balance + "</td><td>"
+ element.method + "</td><td>"
+
if (element.status == 'New Transaction') {
"<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>"
}
});
}
}
});
</script>
Upvotes: 1
Views: 2138
Reputation: 113385
Like the error says, you have a SyntaxError. The fixed code is:
$.ajax({
url: "pull_overview",
dataType: "json",
cache: false,
success: function (data) {
if (data == null) {
$('#ajax-loader').hide()
$('#overviewlist tbody').append("<tr><td colspan='100'><h3><center>You have no recent transactions.</center></h3></td></tr>");
} else {
$('#ajax-loader').hide()
$.each(data, function (index, element) {
$('#overviewlist tbody').append("<tr><td>" + element.name + "</td><td>" + element.time + "</td><td>" + element.type + "</td><td>" + element.change_in_balance + "</td><td>" + element.method + "</td><td>" + element.status == 'New Transaction' ?
"<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>" : "");
});
}
}
});
What is changed?
if
statement inside of a string (e.g. "foo" + if(something) "bar"
). Use ternary operator instead: "foo" + something ? "bar" : ""
Useful resources:
Upvotes: 2
Reputation: 2691
You cannot put an if statement in the middle of a string concatination in your last append
call. do this instead
content = "<tr><td>" + element.name + "</td><td>"
+ element.time + "</td><td>"
+ element.type + "</td><td>"
+ element.change_in_balance + "</td><td>"
+ element.method + "</td><td>";
if (element.status == 'New Transaction')
content += "<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>";
$('#overviewlist tbody').append(content);
Upvotes: 2