James
James

Reputation: 567

Ajax/Javascript Delete Confirm Text Without Dialog

I have searched everywhere but cannot seem to find any examples anywhere of what I am trying to achieve.

I have a Delete button, and when you press the button I would like the text to appear on the screen without the page refreshing asking the user with Yes/No hyperlinks (not buttons) if they want to delete their message. I strictly do not want to use a modal or dialog, I just want text on screen.

I have tried the following script on the ajax page but doesnt do exactly what I want:

function loadDoc() {
  var xhttp;
  if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
<p id="demo">Let AJAX change this text.</p>

<button type='submit' name='btn-delete' id='btn-delete' onclick='loadDoc()'>Delete</button>

As my button is set to submit, I know its posting to the next page before asking the user for delete confirmation.

Any help would be appreciated.

Thanks in advance.

Upvotes: 0

Views: 360

Answers (1)

Andrew Hill
Andrew Hill

Reputation: 2253

WORKING JSFIDDLE

You essentially need to first wrap your markup in a container <div> to append your confirmation <a> tags when they are created.

<div id="container">
  <p id="demo">Let AJAX change this text.</p>
</div>

Then create the confirmation <a> tags and append them to the container <div>.

var node = document.createElement("a");
var textnode = document.createTextNode("Yes");
node.appendChild(textnode);
node.id = 'confirm-delete';
node.href = 'javascript:void(0)';
document.getElementById("container").appendChild(node);

Then fire the request when the user clicks the newly created <a> tag.

document.getElementById('confirm-delete').onclick = function confirmation() {
  // ...
}

Upvotes: 1

Related Questions