You are not following along, a page once redirected will not contain the previous state, unless you preserve it using server-side code or the client-side code.
if(!$foo.data('clicked'))
This requires that your element contains a data property, or that you attach a data property on runtime. Otherwise, it will be false (your condition being true), it will always try sending an SMS. Then you do this,
$foo.data('clicked', true);
You try making sure that the button now has the data property of clicked, and it set to true. But that is where your problem arises. After this, your page refreshes and the DOM reloads the HTML content and in this content there is no data property for the hyperlink (your button).
You can solve it in two ways. First one is that you employ a server-side code and render the data property on demand, such as,
ViewBag.BtnClicked = true;
Response.Redirect("~/your-url");
Then in the client-side, render the control like,
<a class="btn btn-default" @if(ViewBag.BtnClicked != null) { <text>data-clicked="true"</text> } id="sms">Sent SMS</a>
This will render the hyperlink with the property you wanted to be assigned. Second way is using the JavaScript's libraries and tools, one of such is
localStorage
[
^] API. Using this you can store the state of the values in the browser, instead of storing them on the server. In this you can do,
$(function () {
$("#sms").click(function () {
var btnClicked = localStorage.get($(this));
if(!btnClicked)
{
alert("SMS sent successfully!");
localStorage.set($(this), true);
}
else {
alert("You've already sent this sms.");
}
});
});
This will be a bit tricky if you have multiple buttons on the page and you want to control which of the buttons have been clicked and which of the buttons are disabled/enabled. Same is true for server-side as well.
Read more about
.data()
[
^] function in jQuery.
Check out the localStorage examples on MDN:
window.localStorage - Web APIs | MDN[
^].
Edit
Also, I forgot to write you can always consider using Ajax and sending a background request, which will not refresh the page. This way your SMS will be sent, your data property will be added, and your code will work too. You can read the following link to learn more about sending Ajax requests using jQuery.
jQuery.ajax() | jQuery API Documentation[
^]