0

If anyone could point me in the right direction with this code I would greatly appriciate it, tell me how to debugg or point me in the right direction.

When I click the save button, the database gets updated, what I want to do is to send the new data back to ajax and display it in the same columns as the inputs where.

Question: How do I return the data in a response from PHP to Ajax and update the columns with the new text?

I have implemented code from this thread into my project: Allow editing of Text dynamic php table

This is my front end code:

<div class="planerarad momentrad" data-row="<?php echo $pmomentID; ?>" ondblclick="toggleaction<?php echo $pmomentID; ?>()">

<div data-column='name' class="ansvar <?php echo $rowp['status'];?>">
  <?php echo $rowp['ansvarig'];?>
</div>  

<div data-column='moment' class="moment <?php echo $rowp['status'];?>">
  <?php echo $rowp['moment'];?>
</div>

<div data-column='deadline' class="deadline <?php echo $rowp['status'];?>">
  <?php
   echo $rowp['deadline'];?>
</div>

<div class="icon">
</div>

<div class="moment-meny">

  <div class="m-current">                
    <?php  if ($pstatus == 0) { ?>
    <button type="button"><i class="far fa-question-circle"></i></button>
    <?php 
    } elseif ($pstatus == 1) { ?>
    <button><i class="fas fa-user-check"></i></button>
    <?php 
    } elseif ($pstatus == 2) { ?>
    <button><i class="fas fa-exclamation"></i></button>
    <?php 
    } elseif ($pstatus == 3) { ?>
    <button><i class="fas fa-check"></i></button>
    <?php  } ?>
  </div>
  <div class="ärendeadmin">
    <div class="m-remove">
      <form action="scripts/s_editPlan.php" method="post" id="deletePlan<?php echo $pmomentID; ?>">
      <input type="hidden" name="momentid" value="<?php echo $pmomentID ;?>">
      </form>
      <button name="deleteMoment" type="submit" form="deletePlan<?php echo $pmomentID; ?>"><i class="fas fa-trash-alt"></i></button>
    </div>

    <div class="m-edit">
      <button class="closeWindow btn-info"><i class='fas fa-edit'></i></button>
    </div>
  </div>

And here is the jquery to replace text with inputs and send to php file:

<script>
$( function(){

$(document).on("click", ".btn-info", function(){

    var parent = $(this).closest(".momentrad");
    var id = $(parent).attr("data-row");
    var name = $(parent).children("[data-column='name']");
    var moment = $(parent).children("[data-column='moment']");
    var deadline = $(parent).children("[data-column='deadline']");
    var nameTxt = $(name).html();
    var momentTxt = $(moment).html();
    var deadlineTxt = $(deadline).html();

    $(name).html("<input class='input' list='users' name='name' data-dc='ansv' value='"+$.trim(nameTxt)+"'>");
    $(moment).html("<input name='moment' data-dc='moment' value='"+$.trim(momentTxt)+"'>");
    $(deadline).html("<input type='date' max='9999-12-31' data-dc='deadline' value='"+$.trim(deadlineTxt)+"' name='deadline'>");

    $(this).replaceWith("<button class='btn-info-save'>Save</button>");
});

})
</script>
<script>
$(function(){

$(document).on("click", ".btn-info-save", function(){

    var parent = $(this).closest(".momentrad");
    var id = $(parent).attr("data-row");
    var data = {id: id};
    var name = $(parent).children("[data-column='name']");
    var moment = $(parent).children("[data-column='moment']");
    var deadline = $(parent).children("[data-column='deadline']");

    $("[data-dc]").each( function(){
        var col = $(this).attr("data-dc");
        var val = $(this).val();

        data[col] = val;
        console.log(data);
    });

    $.ajax({
        url: "scripts/s_editPlan.php", // Change this to your PHP update script!
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function(ret){
          $(name).html(data(ansv));
          $(moment).html(data(moment));
          $(deadline).html(data(deadline));
          alert("Ändringen lyckades! '"+$.trim(deadlineTxt)+"' '"+$.trim(momentTxt)+"' '"+$.trim(nameTxt)+"' ");
            console.log(ret.response);
           },
        error: function(ret){
            console.log(ret.response);
            alert("Ändringen lyckades inte, inget!");
           }

    });

});

})

</script>

This is the PHP file:

<?php
include "dbh-script.php";
header('Content-type: application/json');


if (isset($_POST['ansv'], $_POST['moment'], $_POST['deadline'], $_POST['id'])) {
$dataid = $_POST['id'];
$ansv = $_POST['ansv'];
$moment = $_POST['moment'];
$deadline = $_POST['deadline'];

$sql = "UPDATE todoaction SET ansvarig='$ansv', moment='$moment', deadline='$deadline' WHERE id='$dataid'";
if ($conn->query($sql) === TRUE) {
    echo json_encode(print_r($_POST););
} else {
    echo json_encode( ["response"=>"Någonting gick fel. Error: " . $sql . "<br>" . $conn->error] );
}
}

if (isset($_POST['momentid'])) {
$id = $_POST['momentid'];
}

if (isset($_POST['deleteMoment'])) {
    $sql = "UPDATE todoaction SET status='4' WHERE id='$id'";
    if ($conn->query($sql) === TRUE) {
        header('Location: ../index.php?page=ärenden');
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
} 

elseif (isset($_POST['acceptMoment'])) {
    $sql = "UPDATE todoaction SET status='1' WHERE id='$id'";
    if ($conn->query($sql) === TRUE) {
        header('Location: ../index.php?page=ärenden');
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
} 

elseif (isset($_POST['helpMoment'])) {
    $sql = "UPDATE todoaction SET status='2' WHERE id='$id'";
    if ($conn->query($sql) === TRUE) {
        header('Location: ../index.php?page=ärenden');
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
} 

elseif (isset($_POST['checkMoment'])) {
    $sql = "UPDATE todoaction SET status='3' WHERE id='$id'";
    if ($conn->query($sql) === TRUE) {
        header('Location: ../index.php?page=ärenden');
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
} 

I'm aware that it might be alot of errors and strange coding since I'm trying to learn by doing.

Husky
  • 11
  • 3
  • [Why is "point me in the right direction" is not an actual question.](https://meta.stackexchange.com/questions/226103/are-point-me-in-the-right-direction-questions-acceptable) – Jay Blanchard May 08 '20 at 12:07
  • What, *exactly*, is your question? – Jay Blanchard May 08 '20 at 12:07
  • Show us exactly what the result was, and tell us why you feel it didn't work. Give us a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard May 08 '20 at 12:07
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 08 '20 at 12:08
  • Please, [quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/), use `console.log()` instead. – Jay Blanchard May 08 '20 at 12:09
  • Because all of your PHP actions have redirects (which will not work with AJAX) if the query is successful nothing is returned to the AJAX as a response. Only errors that are echoed in PHP will return a response to your AJAX request. – Jay Blanchard May 08 '20 at 12:11
  • Edited a the post with a defined question. – Husky May 08 '20 at 12:17
  • Echo the json-encoded new data at the end of your PHP script, decode it in your `success()` function and insert it back into the document. You'll have to find some other way of dealing with errors - set the response code so that it can be dealt with in other functions. I don't think there's much point doing header-redirect inside PHP called by Ajax, as the whole point is to not re-draw the screen. From an Ajax call, I don't think it will even execute that redirect. – droopsnoot May 08 '20 at 12:19
  • These scripts is only targeting the top query, the ones below is for changing the status, I will try to use ajax for them later if I figure this out. – Husky May 08 '20 at 12:21
  • Your ajax success function have parameter `ret` and you are using `data(..)` to get value ? – Swati May 08 '20 at 12:28
  • I have this: ```if ($conn->query($sql) === TRUE) { echo json_encode(print_r($_POST););``` How do I pick this up in the Ajax script? – Husky May 08 '20 at 12:29
  • `alert(ret);` inside your success function and see what does it gives . – Swati May 08 '20 at 12:31
  • alert(ret); gives: [object Object] – Husky May 08 '20 at 12:34
  • check [this](https://stackoverflow.com/q/5753931/10606400) post and do again see if you are getting required value . – Swati May 08 '20 at 12:50
  • With stringify I get:{"readyState":4,"responseText":"Array\n(\n [id] => 61\n [ansv] => Johe\n [moment] => Ändrar lite igen sssss\n [deadline] => 2020-05-16\n)\ntrue","status":200,"statusText":"OK"} – Husky May 08 '20 at 13:32
  • Solved it with: Adding this if query was successful: ``` echo json_encode(array( 'ansv' => "$ansv", 'moment' => "$moment", 'deadline' => "$deadline" )); ``` – Husky May 08 '20 at 14:27

0 Answers0