0

I have checked a few posts about "How to insert PHP into jQuery?" but don't seem to find what I am want. I am not sure if this will work but I do have a todo list in php and I am trying to implement ajax into it. in ajax upon success I want to appened

<a href="done.php?as=done&item=<?php echo $item['id']; ?>" class="done-button">Done</a>

but somehow I am stuck at the php part. This is what I have inside my script

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function() {
    $(".submit").click(function(e){
        var todoText = $("input[name='todoText']").val();
        e.preventDefault();

        $.ajax({
            method: "POST",
            url: "add-ajax.php",
            data: {todoText : todoText},
            success: function(){
                $('p.empty').empty();
                $('input.input').val('');
                $('ul.items').append('<li>'+todoText+'<a href="#" class="done-button">Done</a></li>');
            }
        })
    });
});

the append here works but when I am trying to add the php in it, it wouldn't work.

EDIT (the errors I get):

let's say if I put the whole line

$('ul.items').append('<li>'+todoText+'<a href="done.php?as=done&item=<?php echo $item["id"]; ?>" class="done-button">Done</a></li>');

the error I get from firefox is

SyntaxError: unterminated string literal
$('ul.items').append('<li>'+todoText+'<a href="done.php?as=done&item=<br />

In chrome I get

Uncaught SyntaxError: Unexpected token ILLEGAL

My Html:

        <ul class="items">
            <?php foreach($items as $item): ?>
                <li>
                    <span class="item<?php echo $item['done'] ? ' done' : '' ?>">
                        <?php echo $item['todoText']; ?>
                    </span>
                    <?php if($item['done']): ?>
                        <a href="delete.php?as=delete&item=<?php echo $item['id']; ?>" class="delete-button">Delete Task</a>
                    <?php endif; ?> 
                    <?php if(!$item['done']): ?>
                      <a href="done.php?as=done&item=<?php echo $item['id']; ?>" class="done-button">Done</a>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>

I want the ajax to return pretty much the same thing as my html where I can click the done button.

my add-ajax.php

require_once 'app/init.php';

if (isset($_POST['todoText']))
{
$todoText = htmlentities(trim($_POST['todoText']), ENT_QUOTES);

if (!empty($todoText))
{


    $addedQuery = $db->prepare("
            INSERT INTO todoitems (todoText, user, done, created)
            VALUES (:todoText, :user, 0, NOW())
        ");
6
  • 2
    Explain the 'id doesn`t work' part, open the console of your browser and check if there are javascript errors or php (within the response) Commented Jun 13, 2015 at 23:34
  • what doesn't work? What do you see after you append the PHP? Just raw text rather than the echoed value? Commented Jun 13, 2015 at 23:35
  • View the source of your page ... You'll notice you have $('ul.items').append('<li>'+todoText+'<a href="done.php?as=done&item=<br /> ... The <br /> is telling me that you have a PHP error ... The page source will have the full error Commented Jun 13, 2015 at 23:52
  • ah, I see it can't find the item variable by any chance I can use php to loop through? actually let me edit my post again. I should have shown what's in the html. Commented Jun 14, 2015 at 0:01
  • In your situation, I would make add-ajax.php return what I want to append as a data (that will be passed to my success handler)..question of separating client from server Commented Jun 14, 2015 at 0:01

1 Answer 1

3

You can return the "id" as a JSON to your AJAX call.

In your "add-ajax.php":

$returnValue = array("id"=>$id);
exit(json_encode($returnValue));

In your AJAX call:

$.ajax({
    method: "POST",
    url: "add-ajax.php",
    dataType: "json", // type of data that you're expecting back from the server
    data: {todoText : todoText}
})
.done(function(data) {
    $('p.empty').empty();
    $('input.input').val('');
    $('ul.items').append(
        '<li>' + todoText + 
        '<a href="done.php?as=done&item=' + data.id + 
        '" class="done-button">Done</a></li>'
    );
});
Sign up to request clarification or add additional context in comments.

3 Comments

ah ok, but in my add-ajax.php it's a php script inserting those data into the database. Do I have run a loop query to find the right id? or there is a faster way to do it? I edited and added my add-ajax.php
If you're using PDO, you can use PDO::lastInsertId(), like this: $id = $db->lastInsertId();.
thanks thanks a lot! first time doing ajax myself. It's fun~ let me see if I can do a delete button myself with ajax too :D thx thx again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.