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())
");
$('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 erroradd-ajax.phpreturn what I want to append as a data (that will be passed to my success handler)..question of separating client from server