Folks I am working on the Editinplace functionality and while running I get this error on the chrome console Uncaught SyntaxError: Unexpected token < I am doing this with the node.js snippet as follows
case '/':
res.writeHead(302,{'location':'http://localhost/editinplace/index.html'});
res.end();
break;
case '/save':
console.log("called");
console.log("Inside called");
res.write('_testcb(\'{"message": "Hello world!"}\')');
res.writeHead(302,{'location':'http://localhost/editinplace/save.html'});
res.end();
break;
The code for the index.html is as follows
<script type="text/javascript">
$(document).ready(function(){
setClickable();
});
function setClickable() {
$('#editInPlace').click(function() {
var textarea = '<div><textarea rows="10" cols="60">'+$(this).html()+'</textarea>';
var button = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL"class="cancelButton" /></div></div>';
var revert = $(this).html();
$(this).after(textarea+button).remove();
$('.saveButton').click(function(){saveChanges(this, false);});
$('.cancelButton').click(function(){saveChanges(this, revert);});
})
.mouseover(function() {
$(this).addClass("editable");
})
.mouseout(function() {
$(this).removeClass("editable");
});
};//end of function setClickable
function saveChanges(obj, cancel) {
if(!cancel) {
var t = $(obj).parent().siblings(0).val();
var data=t;
$.ajax({
url: 'http://localhost:9090/save',
type:"GET",
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: true,
timeout: 1000,
data:{data:JSON.stringify(data)},
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}
else {
var t = cancel;
}
$(obj).parent().parent().after('<div id="editInPlace">'+t+'</div>').remove() ;
}
</script>
</head>
<body>
<div id="editInPlace">Nilesh</div>
</body>
The save.html is a simple text enclosed in <pre>tags.And the error is shown to be in save.html line 1.Thankx for your efforts.
OK, so here's what happens:
browser loads index.html
user edits the field and clicks save
saveChanges makes an AJAX GET request to /save
Your server code sends an HTTP response with a 302 status code and a jsonp body
I think that the browser is transparently handling the 302 status code and ignoring the body
Thus your jquery code is expecting your javascript from the response body of /save, but it's really getting the HTML from /save.html. That's where the syntax error happens, when jquery tries to evaluate that HTML as javascript because you told it the dataType was jsonp.
See also this question about browsers handling redirects automatically
The solution is you need to send a 200 response code so jquery can do the jsonp thing and then after that you can change window.location to /save.html if you like.
Related
I'm trying to get json data from the Bing Search API.
What I have done is this
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"></script>
<script>
$(document).ready(function() {
var appId = ':mykey';
function getNews() {
//console.log("DF");
var azureKey = btoa(appId);
var myUrl = 'https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27britain%27&$format=json';
$.ajax({
method: 'post',
url: myUrl,
dataType:"jsonp"
//Set headers to authorize search with Bing
headers:{'Authorization':'Basic ' + azureKey }
}
success: function(data) {
console.log("DF");
//console.log(data);
var json = data.d.results[1].Url;
document.getElementById("demo").innerHTML = json;
},
error: function(jqXHR, error, textStatus) { console.error(jqXHR, error, textStatus); }
});
};
getNews();
});
</script>
</body>
</html>
When I try to run this, the following error comes in the console:
Uncaught SyntaxError: Unexpected identifier
for the line
headers:{'Authorization':'Basic ' + azureKey }
I have the following doubts:
Whether I am doing the jsonp thing right?
Whether I am correct in including two scripts:
language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"> and the main script.
And of course, why the error.
The syntax error is a missing comma
dataType:"jsonp",
// ^
You also have an extra } after the headers object, which will be another syntax error, change that to a comma.
headers:{'Authorization':'Basic ' + azureKey }
,
// ^ comma not a }
You won't be able to use the authorization header with JSONP, it is not possible. If the service supports CORS (which it looks like it does) then you can use a normal XHR by setting the dataType to json.
I have an html page that works like a control module and on there is a button that when clicked runs a python script that triggers an alarm. When I click it, it does nothing. Yet I'm not getting any errors in developer tool. The python code works so the script isn't the problem but my ajax request.
Here is the code:
<input type='button' class="btn btn-default" value='Alarm ON' id = 'alarm'>
<script>
$("#alarm").click(function()
{
$.ajax({
type: "GET",
url: "lib/scripts/AlarmON.py",
success: function(response){}
});
})
</script>
I know if the call would work because an alarm in my room would go off.
EDIT:
For those interested, this is my script:
import suds
from suds.client import Client
from suds.transport.http import HttpAuthenticated
from suds.sax.text import Raw
def main():
#Sends a network message to device to trigger an alarm
url = "http://foobar/WSDL/v4.0/iLON100.WSDL"
client = Client(url, username='ilon', password='ilon', location = 'http://foobar/WSDL/iLON100.WSDL')
xml = Raw('<Item><UCPTname>Net/MB485/PLC/Virtual Fb/y2</UCPTname><UCPTvalue>TRUE</UCPTvalue></Item>')
client.service.Write(xml)
if __name__ == "__main__":
main()
UPDATE I put document.write("hi) inside the success() and it writes hi to the page if the call works, so I'm not sure what is going on..
You can't execute a python script directly like that. Have a look here:
http://docs.python.org/2/howto/webservers.html
Include also the function error to see what happens:
<script>
$("#alarm").click(function()
{
$.ajax({
type: "GET",
url: "lib/scripts/AlarmON.py",
success: function(response){
console.log(response);
},
error: function(xhr){
var status = xhr.status;
var text = xhr.statusText;
console.log( status + ': ' + text);
}
});
})
</script>
I am using Code Igniter and I have the following Javascript function in my View. I have tried to echo values such as "error" from my handler function in the controller, but the "success" code is always ran in this function below instead.
Do I use echo or return to respond to the AJAX post? What value do I return for success and failure?
<script>
function removeDatacenter(id)
{
var cfm = confirm("Do you wish to delete this datacenter?");
if (cfm==true)
{
$.ajax({
type: "POST",
url: "<?=base_url()?>datacenters/remove_handler.php",
data: { id: id },
success: function(result)
{
document.location.href = document.URL + "?result=success";
},
error: function(result)
{
document.location.href = document.URL + "?result=failed";
}}
);
}
};
</script>
The success-method runs if the ajax-request was successfully sent to your script. It does not say anything about what the request returned.
If you simply do echo "error"; in your PHP-script, you can check the value in the success-method like this:
success: function(response) {
if (response == "error") {
document.location.href = document.URL + "?result=failed";
}
else {
document.location.href = document.URL + "?result=success";
}
}
Edit: People tend to use json_encode in the PHP-code and decode the json-string to an object in the javascript-code. That way you can send more structured data from your script.
Any text you echo will be seen, by AJAX, as a success. Even if it's the word "error". In order for you to trigger the Javascript error handler, you need to trigger some sort of actual HTTP error. If you're just trying to trigger an error for testing purposes, you could throw an exception in your controller. Or point the AJAX request to a URL that doesn't exist on your server (then you'd get a 404 error).
By the way, the error callback you have in your Javascript is slightly off on the API. It might not matter depending on what you do in the error handler, but here's the full call:
error: function(xmlHttpRequest, textStatus, errorThrown) {
//handle error here
}
I am having trouble with a program that I have written. The idea is that I click a link and the value of the link is picked up in a JavaScript variable. I then do a GET request to send the value to a PHP variable and print it out.
Here is the code:
The HTML
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id='mydiv'>
<a href='/codeigniter/index.php/hashtest/hi'>Link 1</a>
<a href='/codeigniter/index.php/hashtest/hi'>Link 2</a>
</div>
</body>
</html>
The jQuery (in a <script> tag within the above body)
$(function()
{
var mydiv = $('#mydiv');
mydiv.on('click', 'a', function(){
var text = $(this).text();
console.log(text);
//$.get("hashtest.php", {qwerty: text});
$.ajax
({
url: "/codeigniter/index.php/hashtest/hi",
data: {
qwerty : text
},
async: "false",
success: function(data){
console.log("success!");
},
error: function(jqXHR, status, error)
{
alert("Status : " + status + " error: " + error);
}
});
});
});
The PHP
class Hashtest extends CI_Controller {
function __construct() {
parent::__construct();
}
public function hi() {
$x = $this->input->get('qwerty');
print $x;
print "";
}
}
The error:
NS_ERROR_NOT_AVAILABLE: prompt aborted by user
At the moment, the JavaScript correctly gets the right link value as the console.log() line outputs the right thing for both links. But it seems the PHP is not receiving this value because nothing is being printed out. I've tried replacing the variable with a hard-coded string but it makes no difference. I can print static PHP from within the method above so I don't think it's an issue where I can't print any PHP at all.
A few points:
I used $.ajax instead of $.get just to see what error message would
appear (ideally I'd want to use $.get though). It seems it's some
sort of uncaught exception based on what I've read about the above
error message and the fact that the alert box that appears doesn't
show an error message, just a status of "error".
I don't expect any value back, the success method is just there to
see if the request is wokring or not (which it currently isn't)
I am assuming that the id of the link is unknown.
The code is all within the same class and the URL that I'm pointing
to in the AJAX request is correct (I got a HTTP 200 code back in my
browser console).
The PHP was written using the CodeIgniter framework.
You need to prevent the default action of following the link:
$(function()
{
var mydiv = $('#mydiv');
mydiv.on('click', 'a', function(e){
e.preventDefault(); // <-- THIS IS NEEDED
var text = $(this).text();
console.log(text);
//$.get("hashtest.php", {qwerty: text});
$.ajax
({
url: "/codeigniter/index.php/hashtest/hi",
data: {qwerty : text},
async: "false",
success: function(data){
console.log("success!");
},
error: function(jqXHR, status, error)
{
alert("Status : " + status + " error: " + error);
}
});
});
});
Your code is correct, but your not stopping the event when you click on the link.
Add e.preventDefault();
var mydiv = $('#mydiv');
mydiv.on('click', 'a', function(e){
e.preventDefault();
var text = $(this).text();
</code>
I've been trying to create a small page and all it does is update some values from a source document. The page loads fine, but I don't get the results from the requested source. The .fail function runs, but the textStatus and errorThrown values don't appear in the alert() window that pops up.
I'm very new to javascript and jquery. I'm trying to bash this together with pieces found from the web to figure it out but nothing seems to be working. Mainly, it's the response I think I'm falling down on...
Anyway, here's the code:
<html>
<head>
<title></title>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function update() {
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890/linearlist.xml",
dataType: "xml"
}).done(function (res) {
//alert(res);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
}
function GetData() {
update();
setTimeout(function () {
GetData();
}, 50);
}
});
</script>
</head>
<body>
<script type="text/javascript">
GetData();
</script>
<div class="result"> result div</div>
</body>
</html>
UPDATE:
I've update my code re: #Ian's answer. It's still not working, sadly. I'm not getting the textStatus or errorThrown results either. I've tried debugging with Internet Explorer through VS2012 but it's not getting me far. If I put the URL into a webpage, I can view the XML document.
$.get does not accept one parameter as an object literal; it accepts several: http://api.jquery.com/jQuery.get/#jQuery-get1
You might be thinking of the $.ajax syntax: http://api.jquery.com/jQuery.ajax/
Anyways, call it like:
$.get("http://192.168.2.86:15890//onair.status.xml", {}, function (res) {
var xml;
var tmp;
if (typeof res == "string") {
tmp = "<root>" + res + "</root>";
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(res);
} else {
xml = res;
}
alert("Success!");
}, "text");
Or use $.ajax:
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890//onair.status.xml",
dataType: "text"
}).done(function (res) {
// Your `success` code
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
Using the fail method, you can see that an error occurred and some details why.
Depending on what/where http://192.168.2.86:15890 is, you may not be able to make AJAX calls due to the same origin policy - https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript
I know you have some logic in your success callback, but I'm pretty sure if you specify the dataType as "text", the res variable will always be a string. So your if/else shouldn't really do much - the else should never execute. Either way, if you're expecting XML, it's probably easier to just specify the dataType as "xml".