I am working on a project for drag and drop items in a shopping cart. For an item dropped into the cart, I am trying to implement jQuery $.ajax. The result back from the PHP is pre-pended with '`' and I can not figure out why.
This is the javascript:
$('#target').droppable({
drop: function(event,ui) {
var id = $(ui.draggable).data('id');
var aisle = $(ui.draggable).data('aisle');
$.ajax({
url : base_url+'/index.php/groceries/jquery_append_to_list',
cache : false,
type : 'post',
data : {
'id' : id,
'aisle' : aisle
},
success : function(data) {
$('#target').append('<p data-id="'+id+'" data-aisle="'+aisle+'" class="draggable">'+data.item+'</p>');
}
})
}
});
This is the PHP script:
function jquery_append_to_list(){
$id = $this->input->post('id');
$aisle = $this->input->post('aisle');
$arr = array(
'r' => '1',
'id' => $id,
'aisle' => $aisle,
'item' => 'Rye Bread');
$data = json_encode($arr);
echo $data;
}
For the PHP, I am using Codeigniter as the framework. The PHP is very basic right now as I am debugging this problem so I am trying to return static response values.
The item showing up in the shopping cart is 'undefined' instead of 'Rye Bread' for the JSON array is coming into the browser as `{"r":"1","id":"7","aisle":"1","item":"Rye Bread"}.
I have stepped through the PHP with an IDE and $data is {"r":"1","id":"7","aisle":"1","item":"Rye Bread"}. Somewhere in jQuery's handling it is prepending '`' to the array.
I am using
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
as the jQuery sources. These are the same sources I use for other projects and the returns on those .ajax calls don't come back with a '`'.
The encoding in the editors used is UTF-8. The same is declared in the metadata of the browser. Thinking it might be an encoding problem I have opened the files in different editors under Windows and Linux (Linux my main environment) and nothing has shown as unexpected to account where the '`' is coming from.
For the success part I have tried
success : function(data) {
data = data.replace(/\`/,'');
console.log(data);
var item = data.item;
console.log(item);
$('#target').append('<p data-id="'+id+'" data-aisle="'+aisle+'" class="draggable">'+item+'</p>');
}
The array data is cleaned up and variable item still comes up as undefined.
Does anyone have an idea of what to do next?