Hitting token error exception unexpectedly? - javascript

I am getting unexpected token error from below code and not sure which part have gone wrong
<script>
function delete(n){
alert("This is Called");
if (confirm("Are you sure?")) {
$.ajax({
url: 'functions/delete.php',
type: 'POST',
data: {id: n},
success: function(response) {
console.log(response);
alert('This Works');
}
});
} else {
}
}
</script>

Re-name your function and get rid of the <script> tag if the code is in an external script. Check out below for example:
function deleteFn() {
alert("This is Called");
if (confirm("Are you sure?")) {
alert('This Works');
//Make AJAX call here
}
}
deleteFn();

delete is reserved word in JavaScript, you need to rename "delete" function.
And I would split the code on small peaces and test them separately.
Here is a working example (https://next.plnkr.co/edit/BwG70k3cNQf9sy3A) and the same code below. It does the same as you wanted but without alerts and confirm popups, and I put different URL, it returns response:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button onclick="remove('7')">Run POST Request</button>
<div id="result"></div>
<pre id="data"></pre>
<script>
function remove(n){
$.ajax({
url: 'https://httpbin.org/post',
type: 'POST',
data: {id: n},
success: function(response) {
//console.log(response);
$('#result').html('POST request was successfull:');
$('#data').html(JSON.stringify(response, null, '\t'));
}
});
};
</script>
</body>
</html>

Related

AJAX callback does not see jQuery plugin's method

I'm receiving a data from AJAX response and I'm trying to update a jQuery plugin with that value in the success callback:
$.ajax({
url: '/some/url',
type: 'GET',
dataType: 'json',
success: (data) => {
$(".my-rating").starRating('setRating', data.rating);
}
});
I'm using the star-rating-svg plugin to show ratigns (http://nashio.github.io/star-rating-svg/demo/). The problem is that I'm having an error:
Uncaught TypeError: $(...).starRating is not a function
However, this function works perfectly when is called outside AJAX callback. Do you know how to deal with this?
EDIT:
Larger piece of my code:
show.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/star-svg/src/jquery.star-rating-svg.js"></script>
<link rel="stylesheet" type="text/css" href="/star-svg/src/css/star-rating-svg.css">
</head>
<body>
<div class="my-rating mb-1"></div>
<script>
function getUserRating() {
$.ajax({
url: '/some/url/rating',
type: 'GET',
dataType: 'json',
success: () => {
$(".my-rating").starRating('setRating', data.rating);
}
});
}
function webpageReady() {
if($(".my-rating").is(':visible')) {
$(".my-rating").starRating({
starSize: 20,
disableAfterRate: false,
callback: function(currentRating, $el){
$.ajax({
url: '/some/url/setRating',
type: 'POST',
data: {'rating' : currentRating}
});
}
});
getUserRating();
}
}
</script>
<script type="text/javascript">webpageReady();</script>
</body>
</html>
rating.js
router.get("/some/url/rating", function (req, res) {
Rating.findOne({'author.id': req.user._id}).populate("ratings").exec(function(err, rating){
if(err){
console.log(err);
}
else{
res.send({userRating : rating});
}
});
});
I had the same question, and I figured it out like this - I use jQuery StarRatingSvg v1.2.0:
callback: function(rating, $el){
$.post(
URL,
{ rating: rating, _token : "csrf_token" }
).done(function (resp) {
$el.starRating('setRating', parseFloat(resp.rating), false);
});
}
The callback function has two parameters: rating - the value set by a user when they click the stars, and $el - the rating element.
I hope it helps someone.
Here is simple demo for this plugin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/star-rating-svg#3.5.0/src/jquery.star-rating-svg.js"></script>
</head>
<body>
<div class="my-rating"></div>
<script>
$(document).ready(function(){
$(".my-rating").starRating({
starSize: 25,
callback: function(currentRating, $el){
// make a server call here
}
});
});
</script>
</body>
</html>
Problem solved: In a footer there was another link to a jquery.

Computer Vision API for javascript not working[Beginner's error]

I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.
DO I have to add something in the code
Also, I have nowt provided any image in this code what's he doing without an image?
The script code is here
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"details": "{string}",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
code and preview of error
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}. Here's code with suitable values:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myKey = "6e07223‌​403d94848be20af6f126‌​fsssd";
var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
alert("success");
debugger;
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>

poloniex api error: invalid command

Having issues returning chart data from poloniex api, the reloadData() just returns successfully with an error, error: "Invalid command." .
https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400
This link shows the data i'm trying to get but it fails in javaScript with the same arguments?
API info https://poloniex.com/support/api/
Any help or insight would be greatly appreciated.
window.onload = function() {
reloadData();
}
function reloadData() {
$.ajax({ // fetch some chart data
url: 'https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400',
success: function (data) {
console.log(data);
}
});
}
</script>
This code work fine for me:
<html>
<head>
<script src="jquery-3.1.1.js"></script>
</head>
<body>
<script>
function reloadData() {
$.ajax({ // fetch some chart data
url: 'https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400',
success: function (data) {
console.log(data);
}
});
}
window.onload = function() {
reloadData();
}
</script>
</body>
</html>

How to get total length of JSON object using ajax

I have JSON in URL and I am showing the total length of JSON array, but not showing the length of an object. Please view the code and correct the code.
$(document).ready(function () {
$.ajax({
url: "/hehe/GetAllBus",
data: "",
type: "GET",
dataType: "json",
success: function (dataBus1) {
loaddataBus(dataBus1);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
function myFunction() {
var fruits = dataBus1;
document.getElementById("demo12").innerHTML = fruits.length;
}
Print the length of array
<code>
<body onload="myFunction()">
<p id="demo12"</p>
</body>
</code>
change:
success: function (dataBus1) {
loaddataBus(dataBus1);
},
...
function myFunction() {
var fruits = dataBus1;
document.getElementById("demo12").innerHTML = fruits.length;
}
to:
success: function (dataBus1) {
myFunction(dataBus1);
},
...
function myFunction(dataBus1) {
var fruits = dataBus1;
document.getElementById("demo12").innerHTML = fruits.length;
}
You forget to close the p tag (missing symbol '>' after "demo12")
<code>
<body onload="myFunction()">
<p id="demo12"></p>
</body>
</code>
$(document).ready(function () {
$.ajax({
url: "/hehe/GetAllBus",
data: "",
type: "GET",
dataType: "json",
success: function (dataBus1) {
loaddataBus(dataBus1);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
function loaddataBus(fruits) {
document.getElementById("demo12").innerHTML = fruits.length;
}
You don't even need the onload on body:
<body>
<p id="demo12"></p>
</body>
Try this. In your code you have written ajax inside ready event which will fire after onload so data is not available.
function myFunction() {
$.ajax({
url: "http://mysafeinfo.com/api/data?list=englishmonarchs&format=json",
data: "",
type: "GET",
dataType: "json",
success: function(dataBus1) {
var fruits = dataBus1;
document.getElementById("demo12").innerHTML = dataBus1.length;
},
error: function() {
alert("Failed! Please try again.");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code>
<body onload="myFunction()">
<p id="demo12"</p>
</body>
</code>
If your using jQuery, which it looks like, there is a easier and faster way:
Using $.getJSON.
JS (can be in <head> or in <body> :
<script>
$(document).ready(function(){
$.getJSON("/hehe/GetAllBus", function(data){
$('#demo12').html(data.length);
});
});
</script>
HTML:
<body>
<p id="demo12"></p>
</body>
For more feedback:
$(document).ready(function(){
$.getJSON("/hehe/GetAllBus", function(){
console.log("fetched json");
})
.done(function(data){
$('#demo12').html(data.length);
});
.fail(function(){
console.log("error");
});
});

Ajax not sending info to php

I'm trying to get some information from my php code when clicking on a button, but it doesn't connect to php.
front page is displayed in index.php
index.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="functions.js"></script>
<title>Account Panel</title>
</head>
<div "getInfos">
<h2>In this section you can get your inforrmation</h2>
<button id="getNameBtn">Get Your Name!</button>
<span id="getNameSpan"> something must come here</span>
</div>
</body>
</html>
javascript codes and ajax are in
functions.js:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
and php in serverside is some simple thing like this:
handler.php:
<?php
echo('Ajax successful!');
?>
You have not close the document ready function:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
data:JSON.stringify({taskid = 1}),
shoulde be
data:JSON.stringify({taskid: 1}),
First of all, you should better use a newer jquery version.
There is at least one error in your Code:
data:JSON.stringify({taskid = 1})
The json should read
{taskid : 1}
Use a colon, not an equal sign. Not sure that it is true for your jQuery version, but usually data can be attached as json object already, so the whole line should work so:
data: {taskid : 1},
And the data is then visible as POST data in the PHP page. Note that the live() function is deprecated since 1.7. You can use
$("#getNameBtn").click(function(){...});
instead. Moreover, I don't think you need the headers in your request.
First important change you need to do, use $.on instead of $.live, since the latter is deprecated. Another thing you should check, if the handler.php file is at the same level as your JS/HTML file. It could be that the file is not reachable from your code. Here is what you can try:
$(document).ready(function(){
$("#getNameBtn").on('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data: { call: 'myAjax', taskid : 1 },
headers: {
'content-type': 'application/json'
},
success: function(response) {
$('#getNameSpan').html(response);
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
And in the PHP file, you can check for the call key:
<?php
if(isset($_POST) && $_POST['call'] == 'myAjax') {
echo $_POST['taskid'];
exit;
}
?>
That exit is really important.
In your PHP file that returns JSON you should also set the header to JSON.
header("Content-Type: application/json"); //Above all HTML and returns
And the true answer to your problem has already been answered.

Categories