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!
Related
I am using Jquery to fetch remote data but getting error
Uncaught TypeError: $(...).autocomplete is not a function.
I have tried a lot but did not find out the issue behind this I think must be an error in the library.
Using API: link also not fetching data from API
Data is coming in form of Json:
[{"PubId":"1","Title":"Punjab Kesari","Place":"1"}]
Code:
//But it is not fetching data
$(function() {
$("#pub").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://myimpact.in/deletearticle/services/publication.php",
type: "GET",
data: request,
dataType: "JSON",
minLength: 2,
success: function(data) {
response($.map(data, function(el) {
return {
label: el.Title,
value: el.PubId
};
}));
}
});
},
select: function(event, ui) {
this.value = ui.item.label;
event.preventDefault();
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
</head>
<body>
<div class="input-group">
<label class="label"> Publication </label>
<input class="input--style-4" type="text" id="pub" name="publication">
<div id="pub"> </div>
</div>
</body>
</html>
There can be 2 scenarios …
You are calling the autocomplete function before calling the
jQuery library.
Another version of jQuery is included with the other version.
You can use the below code in your query. I hope it will resolve the issue.
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
I am trying to call a local api I am testing. I am getting a Uncaught ReferenceError: $ is not defined on the call. Here is the JS and html. Is there something I am missing with defining the query within the .js file? It was working before I did some refactoring I am not sure if I deleted something I need and didnt even notice it.
taskpane.js
function domainWhois(domain){
var apiurl = 'http://localhost:5000/linkcheck';
console.log("entering domainWHois");
var request = {"link": domain};
$.ajax({
url: apiurl,
method: 'POST',
type: 'json',
data: JSON.stringify(request),
contentType: 'application/json',
crossDomain: true
}).done(
function(data){
console.log("successfully called API");
console.log(JSON.stringify(data));
}).fail(function(error){
console.log("api call failed");
console.log(JSON.stringify(error));
});
}
Here is the HTML set up
!DOCTYPE html>
<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>Contoso Task Pane Add-in</title>
<!-- Office JavaScript API -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
<script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"></script>
<!-- For more information on Office UI Fabric, visit https://developer.microsoft.com/fabric. -->
<link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/9.6.1/css/fabric.min.css"/>
<!-- AJAX-->
<!-- Template styles -->
<link href="taskpane.css" rel="stylesheet" type="text/css" />
<script src="taskpane.js" type="text/javascript"></script>
</head>
<body class="ms-font-m ms-welcome ms-Fabric">
<header class="ms-welcome__header ms-bgColor-neutralLighter">
<img width="90" height="90" src="../../assets/logo-filled.png" alt="Contoso" title="Contoso" />
<h1 class="ms-font-su">Welcome to your Email Security Assistant</h1>
</header>
<section id="sideload-msg" class="ms-welcome__main">
<h2 class="ms-font-xl">Please sideload your add-in to see app body.</h2>
</section>
<main id="app-body" class="ms-welcome__main" style="display: none;">
<div>
<h2>Secuirty Checks</h2>
<h3>Attachments</h3>
<p><label id="attachment-count"></label></p>
<p><label id="attachment-msg"></label></p>
<h3>Embedded Links</h3>
<p id="linkCheck"></p>
<h3>Header Checks</h3>
<p><label id="reply-match"></label></p>
<p><label id="dkimspfchk"></label></p>
<p><label id="domainMatch"></label></p>
</div>
</main>
</body>
</html>
Check Handling code which relies on jQuery before jQuery is loaded . It will solve your problem. Because your jquery is loaded. So t is recommended to put external scripts imports before the closing body tag, it allows asynchronous loading while the loading in the head tag is a blocking synchronous loading.
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!
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().
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.