-1

I have 3 files [CallTasks.JS, opentask.php, calltask.php], I am doing an AJAX call in CallTasks.JS to calltask.php, in order to pass a string value to calltask.php and show it on opentask.php. I am using JQUERY selector to write text data in div #id="callsuccess", but it's not working.

CallTasks.JS:

$(document).ready(function () {
    $("#display_tasks").click(function() {
        var name = $(this).text();
        var namecut = name.substr(0,name.indexOf(' |'));
        $.ajax({
            type: 'POST',
            url: 'calltask.php',
            data: {mydata : namecut},
            success:function(data) {
                alert(data)
                $('#callsuccess').text(data)
            }
        });
    });
});

opentask.php: require_once $_SERVER['DOCUMENT_ROOT'] . 'calltask.php';

calltask.php:

<?php
    require_once $_SERVER['DOCUMENT_ROOT'] . 'sessionnotfound.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . 'dbinfo.php';
    $dbc   = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
    $taskname = isset($_POST['mydata']) ? $_POST['mydata']: '' ;
    echo $taskname;
    $datatablequery = "SELECT DISTINCT datatable,docid FROM tasks WHERE tskname="."'".$taskname."'";
    $selectdatatable = $dbc->query($datatablequery);
    while ($row = $selectdatatable->fetch_assoc()) {
        $datatablerowresult = $row['datatable'];
        $docidrowresult = $row['docid'];
    ?>
        <div>
            <?php
                echo '<div id="callsuccess">'.$datatablerowresult.'<br>'.$docidrowresult.'</div>';
            ?>
        </div>
<?php
    }
?>

I am also including the CallTasks.JS script file into HTML Head tag inside opentask.php. the alert successfully shows the records I am retrieving from the table, but when I try to echo the results ON page, through the JQUERY final line inside success to PHP div echo into calltask.php, nothing is being shown on opentask.php which includes the calltask.php. What am I doing wrong here?

Samy
  • 63
  • 7
  • Are you getting the alert? – Barmar Nov 16 '22 at 17:32
  • @Barmar yes, value are returning correctly through the AJAX call & MYSQL query. can't echo on php page with JQUERY. – Samy Nov 16 '22 at 17:33
  • Is `#display_tasks` a submit button in a form? That will cause the form to be submitted, which reloads the page. – Barmar Nov 16 '22 at 17:34
  • @Barmar it's defined into another php file as href tag, JQUERY selects it by id on click, to open it – Samy Nov 16 '22 at 17:35
  • 1
  • exactly, the href definition in other php file was like this and displaying data dynamically fine: echo ''.$displaytaskrowresult.''; target is to open the file opentask.php – Samy Nov 16 '22 at 17:38
  • When you link to a new page, the JS on the current page stops running. – Barmar Nov 16 '22 at 17:39
  • @Barmar I don't understand what does reload do? – Samy Nov 16 '22 at 17:39
  • 1
    It replaces the current page with the page you're linking to. – Barmar Nov 16 '22 at 17:39
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Nov 16 '22 at 17:40
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Nov 16 '22 at 17:40
  • Add `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` before your `mysqli_connect()` (or `new mysqli()`) command, and this will ensure that errors with your SQL queries are reported correctly to PHP automatically. See also [mysqli or die, does it have to die?](https://stackoverflow.com/questions/15318368/mysqli-or-die-does-it-have-to-die) – ADyson Nov 16 '22 at 17:40
  • @Barmar where should I place the event.preventDefault()? or how I could be able to open the other page through a link and also keeping the call data. forgive my lack of info but so many details I am trying to grasp and it's difficult somehow – Samy Nov 16 '22 at 17:41
  • @ADyson thank you for the hint, I will consider it in my code after I finish working on the foundation first. – Samy Nov 16 '22 at 17:47
  • 1
    `how I could be able to open the other page`...the whole point of AJAX is to avoid opening new pages, or reloading the current page. The idea is to bring the output from the PHP script and show it in the page where the AJAX code is already running. If you want to open a new page in a new tab, make a hyperlink like `link`. But I'm not 100% sure if that's what you're actually asking for or not. – ADyson Nov 16 '22 at 17:49
  • Why don't you return the data and prepare the HTML in the opentask.php – Mohammed Jhosawa Nov 16 '22 at 17:53
  • @ADyson wow! you just reminded me of the whole concept. omg I totally missed the point!! I am trying to retrieve a record from the DB based on the selected link, I thought of a workaround to get the value itself which is unique, and it worked through the query, except the mechanism itself is very wrong. you are right! what other way would you recommend to achieve what I want? simply, when a user clicks on current notification, i want it to get its id and search for another record through a query. – Samy Nov 16 '22 at 17:53
  • Well there's nothing wrong with the ajax approach for doing that. It depends what kind of user experience exactly you want – ADyson Nov 16 '22 at 18:37

1 Answers1

0

You're refreshing the page by redirecting to a URL when you click on the link. If you want to use AJAX to update the current page, call Event.preventDefault() in the click handler.

$(document).ready(function () {
    $("#display_tasks").click(function(e) {
        e.preventDefault();
        var name = $(this).text();
        var namecut = name.substr(0,name.indexOf(' |'));
        $.ajax({
            type: 'POST',
            url: 'calltask.php',
            data: {mydata : namecut},
            success:function(data) {
                alert(data)
                $('#callsuccess').text(data)
            }
        });
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I added the line but still I get blank page and no alert this time, what it could be possibly? thanks for your time man I really appreciate you trying to help. – Samy Nov 16 '22 at 17:45
  • Are there any errors in the console? Have you tried to debug them? – Barmar Nov 16 '22 at 17:48
  • I was mistaken, I forgot the (e) parameter in the click function. but again, this didn't solve the issue, because I am trying to pass it to (another) page, and I understood that this is not what AJAX does, given your comment (update the current page). I just want to pass the value on click to another php file that runs in a different page. – Samy Nov 16 '22 at 18:35
  • 1
    @Samy `window.location.href - "opentask.php" will cause the browser to load the `opentask.php` page. This destroys your current page and moves to that one instead. Therefore the line `$('#callsuccess').text(data)` will never execute, because it's part of the current page, and you just told the browser to leave this page and go to another one. You still seem a little confused about whether you want to update the current page, or visit a different one. If you want the browser to go to another page, I'd suggest just posting your data directly to that page (via a form) rather than using AJAX. – ADyson Nov 16 '22 at 19:01
  • @ADyson thanks for the guide, I will actually try that – Samy Nov 16 '22 at 19:02
  • 1
    @ADyson I don't know where to begin, but that's the second solution from you in 2 days omg, it totally worked that way.. Thank you so so so much man for enlightening me and bearing with me to learn, I am very grateful:) converting from AJAX's POST logic to Form's POST logic totally satisfied my requirements for now. – Samy Nov 16 '22 at 22:11