Uncaught SyntaxError: Unexpected token < ajax call jsonp - javascript

As the title states, getting this error in Chrome remote debugging. I am trying to send an ajax request (jsonp) to my .php file in localhost which will then do something to the database using the URL in the QR Code after a QR code is scanned. However, I am getting this error.
I am aware that jsonp is different from json and uses different syntax, however the code I am using worked for other ajax calls. I am unable to figure out the problem, and would appreciate some help.
Here are the codes:
.html file
<!DOCTYPE html>
<html>
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<title></title>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header">
<h1></h1>
</div>
<div data-role="main" class="ui-content">
<p>
<a target="_blank" href="javascript:scan();" style="text-decoration: none"><button>Scan</button></a>
</p>
</div>
</div>
<div data-role="page" id="display">
<div data-role="header">
<h1>Display</h1>
</div>
<div data-role="main" class="ui-content">
<table data-role="table" data-mode="column" id="allTable" class="ui-responsive table-stroke">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type= "text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script>
function scan()
{
cordova.plugins.barcodeScanner.scan(
function (result) {
if(!result.cancelled)
{
if(result.format == "QR_CODE")
{
var value = result.text;
$.ajax({
type: "GET",
url: value + '?callback=?',
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
if (response == "Success")
{
alert(response);
}
else
{
alert(response);
}
}
});
}
}
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
</script>
</body>
</html>
.php file
<?php
header('Content-Type: application/json');
require 'dbcon.php';
session_start();
$acc_points = $_SESSION["acc_points"];
$acc_id = $_SESSION["acc_id"];
$result = $con->prepare(" UPDATE `points` SET `acc_points` = acc_points+1 WHERE `acc_id` = ? ");
$result->bind_param("i", $acc_id);
$result->execute();
if($acc_points != null)
{
$response = "Success";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "Failed. Please try again.";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>

Error was:
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Duplicate entry '12' for key 'PRIMARY'' in C:\xampp\htdocs\MP\appqrcode.php:14 Stack trace: #0 C:\xampp\htdocs\MP\appqrcode.php(14): mysqli_stmt->execute() #1 {main} thrown in C:\xampp\htdocs\MP\appqrcode.php on line 14
Solved the problem by changing the primary key of the table.

Related

AJAX POST Request Exception

I'm trying to send an AJAX request with a JSON file to my NodeJS server, but it's throwing what looks like a JSON formatting error client side.
Error Message
SyntaxError: Unexpected token S in JSON at position 0
at parse (<anonymous>)
at Nb (jquery-3.1.1.min.js:4)
at A (jquery-3.1.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)
Script:
<script>
function SendToServer() {
var textToSubmit = document.getElementById("SubmitDataEntry").value;
var objectData = {
submittedText: textToSubmit,
column2: "Mitochondria is the powerhouse of the cell",
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "/",
dataType: "json",
data: {
o: objectDataString,
},
success: function (data) {
alert("Success");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
// alert("Error");
},
});
}
</script>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>AJAX Test</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
</head>
<body>
<div class="form-group" style="margin-top: 40px; padding: 50px;">
<label for="SubmitDataEntry">Submit My Data</label>
<input
type="text"
class="form-control"
id="SubmitDataEntry"
placeholder="Example input"
/>
<button onclick="SendToServer()">
Submit
</button>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</body>
</html>
So far, I've checked the JSON I'm trying to send in a linter, and verified that my Node server can receive requests with Insomnia Core. I believe my JQuery import is also working correctly since the error that's firing is from there!

Triggering a Rest API call with a JQuery Mobile button

This is simple but my JS is a bit rusty..
I am trying to trigger a get request by pressing a JQuery Mobile element.
I can see the button but failing to do an actual Get Request
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<p><input type="checkbox" data-role="flipswitch" name="flip-checkbox-1" id="generator_button"></p>
</form>
</body>
<script>
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
</script>
Please, note: in your markup there is a Flip switch of type checkbox, not a button, so I believe you may better check the state of the underlying checkbox instead of stick to a tap event.
Reference: jQuery Mobile Flip switch
Moreover, you it would be nice to provide a JQM page structure to the whole stuff.
Here is an example:
function sendRequest() {
$.ajax({
'url': '192.168.8.110:5000/generator_on',
'type': 'GET',
'success': function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
}
$(document).on("change", "#generator_button", function() {
var state = $("#generator_button").prop("checked");
if (state === true) {
// Flip switch is on
console.log("Request sent.");
//sendRequest(); // uncomment
} else {
// Flip switch is off
//...endpoint _off
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="page-one" data-role="page">
<div data-role="header" data-position="fixed">
<h1>Header</h1>
</div>
<div role="main" class="ui-content">
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<input type="checkbox" data-role="flipswitch" name="generator_button" id="generator_button">
</div>
<div data-role="footer" data-position="fixed">
<h1>Footer</h1>
</div>
</div>
</body>
</html>
You are missing }); on last line of your javascript.
Your javascript code should look like this
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
});
Ok, so I had to change the url to: 'http://192.168.8.110:5000/generator_on and tested it on a browser without an adblock I mentioned to make it work!

Edit JSON file with a use of AJAX

I tried to do that when I'm pressing the turn on button it calls the turnon() function which opens the JSON file named light.json and writes there {"light" : "on"} but it doesn't work for me and I don't know why. Can anybody help me?
<?php
$light = $_GET['light'];
$file = fopen("light.json", "w") or die("can't open file");
if($light == "on") {
fwrite($file, '{"light": "on"}');
}
else if ($light == "off") {
fwrite($file, '{"light": "off"}');
}
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LED for ESP8266</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
</head>
<body>
<div class="row" style="margin-top: 20px;">
<div class="col-md-8 col-md-offset-2">
<form>
<input type="button" id="StartButton" value="Turn On" onClick="turnOn()">
</form>
<!--<button onclick="turnOn()">Turn On</button>
<button onclick="turnOff()">Turn Off</button>-->
<div class="light-status well" style="margin-top: 5px; text-align:center">
<script type="text/javascript">
function turnOn() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://192.168.1.108/test/light.json",
data: {"light": "on"},
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
}
</script>
</div>
</div>
</div>
</body>
</html>
Thanks!
You use POST method to send AJAX request, but try to get it by using GET method from PHP.
Simply change AJAX method from POST to GET can solve the problem.
You are sending an AJAX request directly to light.json instead of PHP page. Moreover you're using type: "POST" on AJAX but reading from $_GET on PHP.
If the PHP script is on the same page, you won't need to specify url in your AJAX request
<?php
if (isset($_GET['light'])) {
$light = $_GET['light'];
$file = fopen("light.json", "w") or die("can't open file");
if($light == "on") {
fwrite($file, '{"light": "on"}');
} else if ($light == "off") {
fwrite($file, '{"light": "off"}');
}
echo fread($file, filesize($file));
}
?>
$.ajax({
type: "GET",
data: {"light": "on"},
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
Be sure that light.json is in the same directory, otherwise specify the correct path on fopen().

why $.ajax does not work with me?

i don't know why $.ajax never called on my code ?
i use xampp as localhost
jquery called ok , so when i click on the button , the text below it changed .. but $.ajax part never execute ?
my page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script type="text/javascript" src="layout/js/jquery-1.12.4.min.js">
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
my js :
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
and my moremore.php :
<div class="alert alert-success"> alerts alerts by ajax </div>
1) Look for console.log errors or errors in network header
2) Make sure you .php script where you are requesting the ajax, has major headers to allow access control.
3) Sometimes, the headers doesn't allow to make you request.
4) When making request, keep your console opened (F12) and enable Log XMLhttpRequest
Try adding these headers to you moremore.php
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
header("Access-Control-Allow-Origin: http://localhost");
Also to give it a try, check the ajax request with the ajax header, add this too in your moremore.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo '<div class="alert alert-success"> alerts alerts by ajax </div>';
} else {
echo 'no ajax';
}
This will give you an idea if ajax request is working fine or not.
New ajax js:
$(document).ready(function() {
$('#btn').click(function() {
var ID = $(this).attr('id');
$(this).html("Loading ... ");
$.ajax({
type: "POST",
url: "http://localhost/my_projects/testing/moremore.php",
data: {
id: ID
},
cache: false,
xhrFields: {
withCredentials: true
},
dataType: html,
success: function(html) {
$('.container').append(html);
$('#btn').html("done");
},
error: function() {
alert("Something went wrong");
$("#btn").html("hmmmm, it was called... ");
}
});
});
});
Do leave comments for more help!
I tested your code, and it pretty much works as is. The only thing that I changed was the ajax url from absolute http://localhost/my_projects/testing/moremore.php to relative moremore.php and I threw in the official jQuery CDN in case yours was borked.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="http://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script>
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
moremore.php:
<div class="alert alert-success"> alerts alerts by ajax </div>
Results in this expected output after a couple clicks:
Try to wrap anonymous function, and change selector document to '#btn'
(function($) {
$('#btn').on('click',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
})(jQuery);

Whenever I try and load my JSON data into my listview or select menu, nothing shows up

So basically, when I load my data from the server script (retrieve.php), it shows up the in the showlist.html using $('#result').html(data). But whenever I try to load my listview or selectbox with that data..nothing happens. PLEASE ADVICE what I might be doing wrong
//SERVER-SIDE SCRIPT - retrieve.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=sports_rush;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query = "SELECT eid,event_title FROM event_table";
$result = $pdo->prepare($query);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo json_encode($row);
}
$db_connection = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
//I found this recursive function online to enable me force convert to UTF-8 all the strings contained in an array
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else {
return utf8_encode($d);
}
return $d;
}
?>
//FILE THAT SHOWS MY DATA FROM SERVER-SIDE SCRIPT - Showlist.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<title>SHOW LIST</title>
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css"/>
<link rel="stylesheet" href="jquery-mobile/jquery.mobile-1.4.2.min.css" />
<script src="jquery-mobile/jquery-1.9.1.min.js"></script>
<script src="jquery-mobile/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<div data-role="page" id="home_page">
<div data-role="header" data-theme="a">
<h1>Header</h1>
</div>
<div data-role="content">
<select name="zip" id="zip" onChange="initializeRetrieve()"></select>
<div id="result"></div>
<ul data-role="listview" data-inset="true" id="postallist"></ul>
</div>
</div>
<script>
$(function(){
$.ajax({
url : 'retrieve.php',
type : "POST",
success : function(data){
var output = '';
$('#result').html(data); //This is just a test to see my data
$.each(data, function (index, value) {
output += '<li>' + value.eid + '</li>';
});
$('#postallist').html(output).listview("refresh");
}
});
});
function initializeRetrieve(){
var $select5 = $('#zip');
//request the JSON data and parse into the select element
$.getJSON("retrieve.php", function(data){
//iterate over the data and append a select option where eid is in the json file
$.each(data, function(key, value){
$select5.append('<option>' + value.eid + '</option>');
});
});
}
</script>
</body>
</html>
Have you tried using the GET method
Try putting your request to $(document).ready
$(document).ready(function(){
$.getJSON('retrieve.php', function(data) {
$('#result').html(data);
})
});
//FINALLY GOT IT WORKING. The problem was in my showlist.html. Needed to change up my initialization when my page opens
<html>
<meta charset="utf-8" />
<title>SHOW LIST</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Sports Rush Events</h1>
</div>
<div data-role = "content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$.ajax({
url : 'retrievelist.php',
type : "POST",
dataType: 'json',
success : function(data){
$.each(data,function(i,dat){
$("#list").append("<li><b>ID: </b>"+i+"</br><b> Name: </b>"+dat.event_title+"</li>");
});
$("#list").listview('refresh');
}
});
});
</script>
<div data-role="footer" data-position="fixed">
</div>
</div>

Categories