Reputation: 6988
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())
");
Upvotes: 0
Views: 1965
Reputation: 6862
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>'
);
});
Upvotes: 3