$.parseJSON Unexpected Character - javascript

I'm trying to send data from an html data attribute on a span element and receive it with Ajax and then process it with php and mysql and return the new value to my data attribute in html, but I'm getting a error that says "$.parseJSON unexpected character", can someone please look over my code to see if I'm processing the data correctly as I'm new to working with JSON.
HTML / PHP
<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}'
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->
jQuery / Ajax
$("span[class*='star']").on('click', function () {
var data = $.parseJSON($(this).data('object'));
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', JSON.stringify( data ));
});
});
PHP / mySQL
if($_POST['art_featured']==1) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
echo json_encode($result);
}
else if($_POST['art_featured']==0){
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
echo json_encode($result);
}
if(query($sql_articles)) {
}
else {
}

You don't need to use $.parseJSON, jQuery does that for you.
$("span[class*='star']").on('click', function () {
var data = $(this).data('object');
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', data);
});
});
You also don't need to stringify it later.

Related

Don't alert AJAX

I'm trying to get result and alert it if the solicitude was successful or not on the PHP file, it worked (because changed the results) but the AJAX didn't show alerts (No error and no "true")
js:
function addentrys() {
var nwentry = {};
el = document.getElementById('addname').value;
eldmn = document.getElementById('adddomain').value;
nwentry.name = el;
nwentry.domain = eldmn;
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: nwentry
}).done(function(data) {
alert(data);
});
}
php:
$app->post('/domain', function () {
$jsonContents = file_get_contents('data/data.json');
$name = $_POST['name'];
$domain = $_POST['domain'];
$data = json_decode($jsonContents, true);
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'name' => $name,
'domain' => $domain,
'id' => $last_item_id+1
);
$json = json_encode($data);
file_put_contents('data/data.json', $json);
return true;
});
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.

Fetching PHP Data with Javascript and assign it to an array

I've got a php script with collects data from a server and displays it in an array and after that as a json with the function.
echo json_encode($result);
Now I want to access that array with my javascript and display it. It should be saved in a var as an array so it should look like:
data = [ "xxxx" , "ssss",];
But I guess I can simply put in my function which gets the array data instead so it'd be:
data = myfunction ;
What I've tried so far:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
};
oReq.open("get", "http://myserver.com/myscript.php", true);
oReq.send();
and
function getdata(url) {
jQuery.ajax(
{
type: "GET",
url: "http://myserver.com/myscript.php/",
dataType: "text",
success: function (response) {
var JSONArray = jQuery.parseJSON(response);
connsole.log(JSONArray);
}
});
}
But none seems to work and I get displayed 'undefined' instead of my arrays.
Would be really great if somebody has some ideas on that and can help me out.
Edit:
Since we are getting nowhere here's my php code:
<?php
error_reporting(0);
$html = file_get_contents("url here");
$dom = new DOMDocument();
$dom->loadHTML($html);
$tbodyRows = $dom->getElementsByTagName( 'tbody' )
->item( 0 ) // grab first tbody
->getElementsByTagName( 'tr' );
$result = array();
foreach( $tbodyRows as $tbodyRow )
{
$result[] = $tbodyRow->getElementsByTagName( 'td' )
->item( 2 ) // grab 3rd column
->nodeValue;
}
echo json_encode($result);
?>
Try this code:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "text",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
Open the browser's console, and let me know about its contents. If you don't see Error or Success, your code isn't actually executing
I have done a similar thing earlier. I will describe it and I wish it will help you.
In the following code (get_categories.php), I am retrieving data from the database and add them to an array. Then return it by encoding as a JSON.
$sql = "SELECT category_name FROM category;";
$dataArray = [];
$result = $connection->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
echo json_encode($dataArray);
}
Then in my Javascript code, I can get the data as follows.
$.ajax({
url: "/get_categories.php",
type: "GET",
dataType: "json",
success: function (categories) {
for (var i = 0; i < categories.length; i++) {
console.log(categories[i]);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Error handling code
}
});

Ajax call - PHP return value

I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call
So far, I made this..
ajax call
function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
type: "POST",
url: url,
cache: false,
data: { "kategorija": id},
dataType: "json",
success: function (data) {
document.getElementById("kat_id").innerHTML += 'aaa';
},
error: function () {
alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
}
});
return null;
}
php class
<?php
require_once 'baza_model.php';
$akcija = new Akcija();
if (isset($_GET['kategorija'])) {
echo $_GET['kategorija'];
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}
class Akcija{
private $baza;
static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){
$baza = new Baza();
$akcije = array();
$upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id
join kategorija on lijek.kategorija = kategorija.id
where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1
ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';
$rez = $baza->selectDB($upit);
while($red = $rez->fetch_assoc()){
echo "id: " . $red["id"];
$akcije[] = $red;
}
return $akcije;
}
}
I also tried this...
You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).

Format Json returned by AJax call and assign it to javascript variable

I have script that return this from the server using ajax call
//ajax call
var comment_frm = $('#comment_form');
comment_frm.submit(function (ev) {
$.ajax({
type: comment_frm.attr('method'),
url: comment_frm.attr('action'),
data: comment_frm.serialize(),
success: function (data) {
if (data == 1){
$("#success_message").show();
$('#comment_form').trigger("reset");
}
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
//prevent the page from loading
ev.preventDefault();
});
[{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
I want to format it to look like this and assign the json result to a javascript variable
var comment_array = {"Comments": [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"coment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]}
//php code
$operation = $_POST['operation'];
if($operation == 'add_comment'){
$name = $_POST['name'];
$comment = $_POST['comment'];
$blog_id = $_POST['blog_id'];
$comment_status = 1;
if ($me->add_comment($name, $comment, $blog_id)){
//get the comment
$comment_array = $me-> fetch_moderated_comment($blog_id);
echo json_encode($comment_array);
}else{echo 10;}
}
I will also love to know how to read get that from the call... Can someone please help me
Working Example
You could assign a variable to hold your new 'Comments' array and then push to it:
var a = [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
var b = {"Comments": []};
for (var prop in a) {
b.Comments.push(a[prop]);
}
echo json_encode(['Comments' => $comment_array]);
If I understand correctly, just wrap the result in an object literal:
vat result = {"Comments": comment_frm};

ajax function not returning right data

I'm trying to get the proper information out of this ajax function (thumbnail image, the owner of the image). I dont think it knows what data.images[i].imgurl and data.images[i].username is.
ajax.php
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('123456');
// Receive AJAX request and create call object
$tag = $_GET['tag'];
$maxID = $_GET['max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = array(
"imgurl"=>$data->images->thumbnail->url,
"username"=>$data->user->username;
);
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images,
));
search.php
<script>
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('#photos').append('<div id=box><div class=mainimg><img src="'+ data.images[i].imgurl +'"></div><div class=\"pfooter\">'+ data.images[i].username +'</div></div>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
..
In your search.php file you have to close the variable statement with a semicolon.
Change this line:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
to this:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'); // <-- added semicolon

Categories