Home > Mobile >  AJAX POST Success div upload disappears after a few seconds
AJAX POST Success div upload disappears after a few seconds

Time:11-05

I am having issue after a successful AJAX post, where the updated div disappears after a few moments

Below are the jquery/PHP/POST data in succession.

Button On Click Function:

function Delete_ID(clickBtnValue,clickBtnID,clickBtnName) {
  var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
  $.ajax({
    type: 'POST',
    url: '../Programs/Programs.php',
    data: my_data,
    success: function (data) {
      $('#ProgramsTable').load("../Programs/ProgramChange.php");
      $('#update-div').html(data);
    }
  });
}

PHP DIV display:

$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
  $html = '<br><div id="ProgramsTable"><div >';
  for ($ii=0; $ii < count($list_programs); $ii  ) {
    $html .= <<<HTML
    <div class="CELL">
      <form method="post" action>{$list_programs[$ii]["Program_Name"]}
        <button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
        <button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" >Edit</button>
      </form>
    </div>
    HTML;
  }
}
echo $html;
echo "</div></div><div id='update-div'></div>";

POST in Programs.php:

if (!empty($_POST)) {
    if ($_POST['passvalue'] == "Delete"){
      DB_Delete_Program_list($_POST['passid']);
      echo $_POST['passname'] . " has been deleted";
    }
    if ($_POST['passvalue'] == "Edit"){
      echo '  <div ><form  method="post">';
      echo '     <div style="margin-top:5px"><input type="text" style="height:20px;" id="'.$_POST['passid'].'" value="'.$_POST['passname'].'" size="40" maxlength="253"></div>';
      echo '    <div style="margin-top:10px"></div>';
      echo '    <div ><input  type="Submit" name="Edit_button"></div>';
      echo '  </form></div>';
    }
    return true;
}

When I press delete, it will display for example "Program 1 has been deleted" and then disappear When I press edit, the new form table and display and then disappear

Here is a screen record of my issue

What do I need to change, to make it so my div data "table" refreshes with the latest SQL data while also keeping the success text message?

DSICLAIMER Yes I am aware that the EDIT POST option is not how it's supposed to be, as I am just testing the success message return. Yes there is SQL mitigation in place

CodePudding user response:

I believe what's happening is when you click your button, you're submitting the form while also triggering your Delete_ID function. So, what happens is the JS function executes and displays your div, but the page also reloads, so you only see it for a moment. What you need to do is to call preventDefault() on the event that is generated by the onclick event.

As a tangent, to make passing the data to your Delete_ID function easier, I'd recommend using data attributes rather than passing the data as properties to the function itself.

This is how I'd redo your code.

For your form buttons, remove the onclick attribute, and use the data- attributes for relevant properties. I also added delete-button and edit-button classes to each button to distinguish them.

$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
  $html = '<br><div id="ProgramsTable"><div >';
  for ($ii=0; $ii < count($list_programs); $ii  ) {
    $html .= <<<HTML
    <div >
      <form method="post" action>{$list_programs[$ii]["Program_Name"]}
        <button data-name-hash="{$list_programs[$ii]["Name_Hash"]}"  data-program-name="{$list_programs[$ii]["Program_Name"]}" >Delete</button>
        <button data-name-hash="{$list_programs[$ii]["Name_Hash"]}"  data-program-name="{$list_programs[$ii]["Program_Name"]}" >Edit</button>
      </form>
    </div>
    HTML;
  }
}
echo $html;
echo "</div></div><div id='update-div'></div>";

Then in your javascript, assign the on-click function to buttons with the matching class. This allows you to access the click event in that function.

$('.delete-button').click(Delete_ID);

Now, update the function definition to use the click event and pull the data from data attributes:

function Delete_ID(event) {
  event.preventDefault(); // Stop the form from submitting so the page doesn't reload

  const clickedBtn = event.target; // This is a reference to the <button> itself. 

  const clickBtnValue = 'Delete'; // You could pass this via data attributes too; I assume you'll probably have a separate Edit_ID function though. 

  // Pull the values from the `data-` attributes on the clicked button
  // Note that JS converts the kebab-case attribute names (eg: data-name-hash) to camelCase with "data" removed (eg: nameHash). 
  const clickBtnID = clickedBtn.dataset.nameHash;
  const clickBtnName = clickedBtn.dataset.programName;

  var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
  $.ajax({
    type: 'POST',
    url: '../Programs/Programs.php',
    data: my_data,
    success: function (data) {
      $('#ProgramsTable').load("../Programs/ProgramChange.php");
      $('#update-div').html(data);
    }
  });
}

Here's a very basic JSFiddle example of using preventDefault with data attributes.

CodePudding user response:

you need to prevent your form to be submitted when you press Delete/Edit button, you can do it by remove form tag

$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
    $html = '<br><div id="ProgramsTable"><div >';
    for ($ii=0; $ii < count($list_programs); $ii  ) {
        $html .= <<<HTML
            <div class="CELL">
                {$list_programs[$ii]["Program_Name"]}
                <button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
                <button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" >Edit</button>
            </div>
        HTML;
    }
}

echo $html;
echo "</div></div><div id='update-div'></div>";

or return false on button click event

$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
    $html = '<br><div id="ProgramsTable"><div >';
    for ($ii=0; $ii < count($list_programs); $ii  ) {
        $html .= <<<HTML
            <div class="CELL">
                <form method="post" action>{$list_programs[$ii]["Program_Name"]}
                    <button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" class="button">Delete</button>
                    <button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" >Edit</button>
                </form>
            </div>
        HTML;
    }
}

echo $html;
echo "</div></div><div id='update-div'></div>";
  • Related