Ajax return error Unexpected token < in JSON at position 4
i'm working on a small "facebook like" application for a school project and i'm having some issue with an Ajax request
i'm trying to do a like dislike systeme with Jquery Ajax but i got this error in the console when i debug my "data"
Uncaught SyntaxError: Unexpected token < in JSON at position 4
This is my ajax call :
$(document).ready(function(){
$('.like-btn').on('click', function(){
var post_id = $(this).data('id');
$clicked_btn = $(this);
if ($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up')) {
var action = 'like';
} else if($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up liked')){
var action = 'unlike';
}
$.ajax({
type: "POST",
url: 'index.php?action=likes',
data:{
'action': action,
'post_id': post_id
},
success: function(data){
alert("succes");
console.log(data);
res = JSON.parse(data);
if (action == "like") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up liked');
} else if(action == "unlike") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up liked');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up');
}
// Affiche le nombre de like dislike
$clicked_btn.siblings('span.likes').text(res.likes);
$clicked_btn.siblings('span.dislikes').text(res.dislikes);
// Change le style du boutton suivant si user click dessus
$clicked_btn.siblings('glyphicon glyphicon-thumbs-
down').removeClass('glyphicon glyphicon-thumbs-
down').addClass('glyphicon glyphicon-thumbs-down disliked');
}, error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: '
+ message);
console.log(status + message);
}
});
});
And this is my likes.php :
<?php
function getRating($id)
{
global $pdo;
$rating = array();
$likes_query = "SELECT COUNT(*) FROM rating_info WHERE post_id = ? AND
rating_action='like'";
$dislikes_query = "SELECT COUNT(*) FROM rating_info
WHERE post_id = ? AND rating_action='dislike'";
$likes_rs = $pdo->prepare($likes_query);
$dislikes_rs = $pdo->prepare($dislikes_query);
$likes_rs->execute(array($id));
$dislikes_rs->execute(array($id));
$likes=$likes_rs->fetch();
$dislikes=$dislikes_rs->fetch();
$rating = [
'likes' => $likes[0],
'dislikes' => $dislikes[0]
];
return json_encode($rating);
}
if (isset($_POST['action'])) {
$user_id=$_SESSION['id'];
$return = $_POST;
$post_id = $_POST['post_id'];
$action = $_POST['action'];
switch ($action) {
case 'like':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'like')
ON DUPLICATE KEY UPDATE rating_action='like'";
break;
case 'dislike':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'dislike')
ON DUPLICATE KEY UPDATE rating_action='dislike'";
break;
case 'unlike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
case 'undislike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
default:
break;
}
$q = $pdo->prepare($sql);
$q->execute();
echo getRating($post_id);
exit(0);
}
I've tried using datatype:'json' but it also return me an error ,
Actually it work to insert value in my DB, but it doesnt handle the change of the css and i've got this error.
I'm not use to Ajax this might be simple, sorry if i'm saying a stupid question.
Thanks you in advance for you time and messages, see ya.
javascript php jquery json ajax
|
show 1 more comment
i'm working on a small "facebook like" application for a school project and i'm having some issue with an Ajax request
i'm trying to do a like dislike systeme with Jquery Ajax but i got this error in the console when i debug my "data"
Uncaught SyntaxError: Unexpected token < in JSON at position 4
This is my ajax call :
$(document).ready(function(){
$('.like-btn').on('click', function(){
var post_id = $(this).data('id');
$clicked_btn = $(this);
if ($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up')) {
var action = 'like';
} else if($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up liked')){
var action = 'unlike';
}
$.ajax({
type: "POST",
url: 'index.php?action=likes',
data:{
'action': action,
'post_id': post_id
},
success: function(data){
alert("succes");
console.log(data);
res = JSON.parse(data);
if (action == "like") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up liked');
} else if(action == "unlike") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up liked');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up');
}
// Affiche le nombre de like dislike
$clicked_btn.siblings('span.likes').text(res.likes);
$clicked_btn.siblings('span.dislikes').text(res.dislikes);
// Change le style du boutton suivant si user click dessus
$clicked_btn.siblings('glyphicon glyphicon-thumbs-
down').removeClass('glyphicon glyphicon-thumbs-
down').addClass('glyphicon glyphicon-thumbs-down disliked');
}, error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: '
+ message);
console.log(status + message);
}
});
});
And this is my likes.php :
<?php
function getRating($id)
{
global $pdo;
$rating = array();
$likes_query = "SELECT COUNT(*) FROM rating_info WHERE post_id = ? AND
rating_action='like'";
$dislikes_query = "SELECT COUNT(*) FROM rating_info
WHERE post_id = ? AND rating_action='dislike'";
$likes_rs = $pdo->prepare($likes_query);
$dislikes_rs = $pdo->prepare($dislikes_query);
$likes_rs->execute(array($id));
$dislikes_rs->execute(array($id));
$likes=$likes_rs->fetch();
$dislikes=$dislikes_rs->fetch();
$rating = [
'likes' => $likes[0],
'dislikes' => $dislikes[0]
];
return json_encode($rating);
}
if (isset($_POST['action'])) {
$user_id=$_SESSION['id'];
$return = $_POST;
$post_id = $_POST['post_id'];
$action = $_POST['action'];
switch ($action) {
case 'like':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'like')
ON DUPLICATE KEY UPDATE rating_action='like'";
break;
case 'dislike':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'dislike')
ON DUPLICATE KEY UPDATE rating_action='dislike'";
break;
case 'unlike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
case 'undislike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
default:
break;
}
$q = $pdo->prepare($sql);
$q->execute();
echo getRating($post_id);
exit(0);
}
I've tried using datatype:'json' but it also return me an error ,
Actually it work to insert value in my DB, but it doesnt handle the change of the css and i've got this error.
I'm not use to Ajax this might be simple, sorry if i'm saying a stupid question.
Thanks you in advance for you time and messages, see ya.
javascript php jquery json ajax
1
What do you see in the console as the output for the console.log(data) line? I've gotten similar errors when I'm getting a response I wasn't expecting.
– Peter Breen
Nov 12 '18 at 19:14
2
Usually this error means the server is returning HTML instead of JSON. Check what your PHP is outputting. I see you're sending your AJAX request to index.php. This is usually the main page of your site. it's much better to separate the generating of JSON data and HTML data into separate scripts. I would remove all the PHP code shown above into a separate script which does nothing else, and then call that script specifically in your AJAX request. Probably you've also inadvertently output some HTML along with the JSON.
– ADyson
Nov 12 '18 at 19:15
P.S. Your insert queries are vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
– ADyson
Nov 12 '18 at 19:16
@PeterBreen Yes the error is the result of the console.log
– ruko kei
Nov 12 '18 at 20:12
Possible duplicate of "SyntaxError: Unexpected token < in JSON at position 0" in React App
– miken32
Nov 12 '18 at 20:29
|
show 1 more comment
i'm working on a small "facebook like" application for a school project and i'm having some issue with an Ajax request
i'm trying to do a like dislike systeme with Jquery Ajax but i got this error in the console when i debug my "data"
Uncaught SyntaxError: Unexpected token < in JSON at position 4
This is my ajax call :
$(document).ready(function(){
$('.like-btn').on('click', function(){
var post_id = $(this).data('id');
$clicked_btn = $(this);
if ($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up')) {
var action = 'like';
} else if($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up liked')){
var action = 'unlike';
}
$.ajax({
type: "POST",
url: 'index.php?action=likes',
data:{
'action': action,
'post_id': post_id
},
success: function(data){
alert("succes");
console.log(data);
res = JSON.parse(data);
if (action == "like") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up liked');
} else if(action == "unlike") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up liked');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up');
}
// Affiche le nombre de like dislike
$clicked_btn.siblings('span.likes').text(res.likes);
$clicked_btn.siblings('span.dislikes').text(res.dislikes);
// Change le style du boutton suivant si user click dessus
$clicked_btn.siblings('glyphicon glyphicon-thumbs-
down').removeClass('glyphicon glyphicon-thumbs-
down').addClass('glyphicon glyphicon-thumbs-down disliked');
}, error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: '
+ message);
console.log(status + message);
}
});
});
And this is my likes.php :
<?php
function getRating($id)
{
global $pdo;
$rating = array();
$likes_query = "SELECT COUNT(*) FROM rating_info WHERE post_id = ? AND
rating_action='like'";
$dislikes_query = "SELECT COUNT(*) FROM rating_info
WHERE post_id = ? AND rating_action='dislike'";
$likes_rs = $pdo->prepare($likes_query);
$dislikes_rs = $pdo->prepare($dislikes_query);
$likes_rs->execute(array($id));
$dislikes_rs->execute(array($id));
$likes=$likes_rs->fetch();
$dislikes=$dislikes_rs->fetch();
$rating = [
'likes' => $likes[0],
'dislikes' => $dislikes[0]
];
return json_encode($rating);
}
if (isset($_POST['action'])) {
$user_id=$_SESSION['id'];
$return = $_POST;
$post_id = $_POST['post_id'];
$action = $_POST['action'];
switch ($action) {
case 'like':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'like')
ON DUPLICATE KEY UPDATE rating_action='like'";
break;
case 'dislike':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'dislike')
ON DUPLICATE KEY UPDATE rating_action='dislike'";
break;
case 'unlike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
case 'undislike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
default:
break;
}
$q = $pdo->prepare($sql);
$q->execute();
echo getRating($post_id);
exit(0);
}
I've tried using datatype:'json' but it also return me an error ,
Actually it work to insert value in my DB, but it doesnt handle the change of the css and i've got this error.
I'm not use to Ajax this might be simple, sorry if i'm saying a stupid question.
Thanks you in advance for you time and messages, see ya.
javascript php jquery json ajax
i'm working on a small "facebook like" application for a school project and i'm having some issue with an Ajax request
i'm trying to do a like dislike systeme with Jquery Ajax but i got this error in the console when i debug my "data"
Uncaught SyntaxError: Unexpected token < in JSON at position 4
This is my ajax call :
$(document).ready(function(){
$('.like-btn').on('click', function(){
var post_id = $(this).data('id');
$clicked_btn = $(this);
if ($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up')) {
var action = 'like';
} else if($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up liked')){
var action = 'unlike';
}
$.ajax({
type: "POST",
url: 'index.php?action=likes',
data:{
'action': action,
'post_id': post_id
},
success: function(data){
alert("succes");
console.log(data);
res = JSON.parse(data);
if (action == "like") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up liked');
} else if(action == "unlike") {
$clicked_btn.removeClass('glyphicon glyphicon-thumbs-up liked');
$clicked_btn.addClass('glyphicon glyphicon-thumbs-up');
}
// Affiche le nombre de like dislike
$clicked_btn.siblings('span.likes').text(res.likes);
$clicked_btn.siblings('span.dislikes').text(res.dislikes);
// Change le style du boutton suivant si user click dessus
$clicked_btn.siblings('glyphicon glyphicon-thumbs-
down').removeClass('glyphicon glyphicon-thumbs-
down').addClass('glyphicon glyphicon-thumbs-down disliked');
}, error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: '
+ message);
console.log(status + message);
}
});
});
And this is my likes.php :
<?php
function getRating($id)
{
global $pdo;
$rating = array();
$likes_query = "SELECT COUNT(*) FROM rating_info WHERE post_id = ? AND
rating_action='like'";
$dislikes_query = "SELECT COUNT(*) FROM rating_info
WHERE post_id = ? AND rating_action='dislike'";
$likes_rs = $pdo->prepare($likes_query);
$dislikes_rs = $pdo->prepare($dislikes_query);
$likes_rs->execute(array($id));
$dislikes_rs->execute(array($id));
$likes=$likes_rs->fetch();
$dislikes=$dislikes_rs->fetch();
$rating = [
'likes' => $likes[0],
'dislikes' => $dislikes[0]
];
return json_encode($rating);
}
if (isset($_POST['action'])) {
$user_id=$_SESSION['id'];
$return = $_POST;
$post_id = $_POST['post_id'];
$action = $_POST['action'];
switch ($action) {
case 'like':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'like')
ON DUPLICATE KEY UPDATE rating_action='like'";
break;
case 'dislike':
$sql="INSERT INTO rating_info (user_id, post_id, rating_action)
VALUES ($user_id, $post_id, 'dislike')
ON DUPLICATE KEY UPDATE rating_action='dislike'";
break;
case 'unlike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
case 'undislike':
$sql="DELETE FROM rating_info WHERE user_id=$user_id AND
post_id=$post_id";
break;
default:
break;
}
$q = $pdo->prepare($sql);
$q->execute();
echo getRating($post_id);
exit(0);
}
I've tried using datatype:'json' but it also return me an error ,
Actually it work to insert value in my DB, but it doesnt handle the change of the css and i've got this error.
I'm not use to Ajax this might be simple, sorry if i'm saying a stupid question.
Thanks you in advance for you time and messages, see ya.
javascript php jquery json ajax
javascript php jquery json ajax
asked Nov 12 '18 at 19:09
ruko keiruko kei
82
82
1
What do you see in the console as the output for the console.log(data) line? I've gotten similar errors when I'm getting a response I wasn't expecting.
– Peter Breen
Nov 12 '18 at 19:14
2
Usually this error means the server is returning HTML instead of JSON. Check what your PHP is outputting. I see you're sending your AJAX request to index.php. This is usually the main page of your site. it's much better to separate the generating of JSON data and HTML data into separate scripts. I would remove all the PHP code shown above into a separate script which does nothing else, and then call that script specifically in your AJAX request. Probably you've also inadvertently output some HTML along with the JSON.
– ADyson
Nov 12 '18 at 19:15
P.S. Your insert queries are vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
– ADyson
Nov 12 '18 at 19:16
@PeterBreen Yes the error is the result of the console.log
– ruko kei
Nov 12 '18 at 20:12
Possible duplicate of "SyntaxError: Unexpected token < in JSON at position 0" in React App
– miken32
Nov 12 '18 at 20:29
|
show 1 more comment
1
What do you see in the console as the output for the console.log(data) line? I've gotten similar errors when I'm getting a response I wasn't expecting.
– Peter Breen
Nov 12 '18 at 19:14
2
Usually this error means the server is returning HTML instead of JSON. Check what your PHP is outputting. I see you're sending your AJAX request to index.php. This is usually the main page of your site. it's much better to separate the generating of JSON data and HTML data into separate scripts. I would remove all the PHP code shown above into a separate script which does nothing else, and then call that script specifically in your AJAX request. Probably you've also inadvertently output some HTML along with the JSON.
– ADyson
Nov 12 '18 at 19:15
P.S. Your insert queries are vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
– ADyson
Nov 12 '18 at 19:16
@PeterBreen Yes the error is the result of the console.log
– ruko kei
Nov 12 '18 at 20:12
Possible duplicate of "SyntaxError: Unexpected token < in JSON at position 0" in React App
– miken32
Nov 12 '18 at 20:29
1
1
What do you see in the console as the output for the console.log(data) line? I've gotten similar errors when I'm getting a response I wasn't expecting.
– Peter Breen
Nov 12 '18 at 19:14
What do you see in the console as the output for the console.log(data) line? I've gotten similar errors when I'm getting a response I wasn't expecting.
– Peter Breen
Nov 12 '18 at 19:14
2
2
Usually this error means the server is returning HTML instead of JSON. Check what your PHP is outputting. I see you're sending your AJAX request to index.php. This is usually the main page of your site. it's much better to separate the generating of JSON data and HTML data into separate scripts. I would remove all the PHP code shown above into a separate script which does nothing else, and then call that script specifically in your AJAX request. Probably you've also inadvertently output some HTML along with the JSON.
– ADyson
Nov 12 '18 at 19:15
Usually this error means the server is returning HTML instead of JSON. Check what your PHP is outputting. I see you're sending your AJAX request to index.php. This is usually the main page of your site. it's much better to separate the generating of JSON data and HTML data into separate scripts. I would remove all the PHP code shown above into a separate script which does nothing else, and then call that script specifically in your AJAX request. Probably you've also inadvertently output some HTML along with the JSON.
– ADyson
Nov 12 '18 at 19:15
P.S. Your insert queries are vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
– ADyson
Nov 12 '18 at 19:16
P.S. Your insert queries are vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
– ADyson
Nov 12 '18 at 19:16
@PeterBreen Yes the error is the result of the console.log
– ruko kei
Nov 12 '18 at 20:12
@PeterBreen Yes the error is the result of the console.log
– ruko kei
Nov 12 '18 at 20:12
Possible duplicate of "SyntaxError: Unexpected token < in JSON at position 0" in React App
– miken32
Nov 12 '18 at 20:29
Possible duplicate of "SyntaxError: Unexpected token < in JSON at position 0" in React App
– miken32
Nov 12 '18 at 20:29
|
show 1 more comment
1 Answer
1
active
oldest
votes
I found the solution thanks you @ADyson, first of all i've changed my php in it's own file
and i've also parameterised my queries in the php file, so yes i think the problem was in my index.php thanks you all
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53268594%2fajax-return-error-unexpected-token-in-json-at-position-4%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I found the solution thanks you @ADyson, first of all i've changed my php in it's own file
and i've also parameterised my queries in the php file, so yes i think the problem was in my index.php thanks you all
add a comment |
I found the solution thanks you @ADyson, first of all i've changed my php in it's own file
and i've also parameterised my queries in the php file, so yes i think the problem was in my index.php thanks you all
add a comment |
I found the solution thanks you @ADyson, first of all i've changed my php in it's own file
and i've also parameterised my queries in the php file, so yes i think the problem was in my index.php thanks you all
I found the solution thanks you @ADyson, first of all i've changed my php in it's own file
and i've also parameterised my queries in the php file, so yes i think the problem was in my index.php thanks you all
answered Nov 12 '18 at 20:53
ruko keiruko kei
82
82
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53268594%2fajax-return-error-unexpected-token-in-json-at-position-4%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
What do you see in the console as the output for the console.log(data) line? I've gotten similar errors when I'm getting a response I wasn't expecting.
– Peter Breen
Nov 12 '18 at 19:14
2
Usually this error means the server is returning HTML instead of JSON. Check what your PHP is outputting. I see you're sending your AJAX request to index.php. This is usually the main page of your site. it's much better to separate the generating of JSON data and HTML data into separate scripts. I would remove all the PHP code shown above into a separate script which does nothing else, and then call that script specifically in your AJAX request. Probably you've also inadvertently output some HTML along with the JSON.
– ADyson
Nov 12 '18 at 19:15
P.S. Your insert queries are vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
– ADyson
Nov 12 '18 at 19:16
@PeterBreen Yes the error is the result of the console.log
– ruko kei
Nov 12 '18 at 20:12
Possible duplicate of "SyntaxError: Unexpected token < in JSON at position 0" in React App
– miken32
Nov 12 '18 at 20:29