Javascript Unexpected token ILLEGAL - javascript

I have a PHP script (fetchData.php) that fetches some data and outputs it to a page.
<?php
require 'config.php';
require 'jsonapiSDK.php';
$api = new JSONAPI($ip_address, $jsonapi_port, $username, $password, $salt);
$response = $api->call('BWMFunction');
echo(addslashes($response["success"].";"));
?>
You can see the output here: http://justicecraft.net/worldmap/fetchData.php
I have another page that uses an XMLHttpRquest to get the response from fetchData.php
Here's the JavaScript for it. It's supposed to take the response, and eval() it (to create an array called BWMFunction) then pass that array to another function I have. The Illegal token error occurs when I try to eval() the response.
function fetchData() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
res = xmlhttp.responseText;
alert(res);
eval(res);
generate(BWMFunction);
}
}
xmlhttp.open("GET", "fetchData.php", true);
xmlhttp.send();
}
This is my first time on StackOverflow, so any help would be appreciated. I have googled around for quite a while now, but none of the answers helped me.

You have invalid javascript returned from fetchData.php which is why the eval method crashes. Instead of \" in the output you should have simple ". I know strictly nothing about PHP but I am ready to bet some bucks that its the addslashes function which is causing the damage. So maybe you could try something along the lines of:
echo($response["success"].";");

Related

Php not receiving post from JavaScript

I have implemented the same setup elsewhere in my site and can't figure out why it's not working this time.
When a user clicks the accept button, it calls a JavaScript function acceptOrder(orderID) which passes the orderID onto a php page to update a record in the db.
orderID is assigned ok in the JavaScript but it doesn't reach the php. Var_dump on POST shows nothing, nor does $_POST('orderID'). I've even tried just sending an integer to the php in case there was a problem with the var but it made no difference.
Js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft. }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}
Php
<?php
require_once("config1412/class.shop.php");
session_start();
$shop = new SHOP();
echo var_dump($_POST);
//$orderID = $_POST['orderID'];
//echo "orderId var = ".$orderID."<br/>post ".$_POST['orderID'];
//$shop->acceptOrder($orderID);
?>
Needless to say I've searched about and don't see any solutions elsewhere.
Many thanks
As i can see, you didn't set variable name for orderID, change line of code:
xmlhttp.send(orderID);
to:
xmlhttp.send("orderID="+orderID);
If it's only SQL error of missing orderID, and all other passess okay, it's solution for you. As you said in comments "I just get a sql error because the variable orderID is empty".
You're missing only naming post send data, that's why it's empty.
Please replace this line
xmlhttp=new ActiveXObject("Microsoft. }
with following this line
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
You should write this in your js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}
I would recommend you to use jQuery for ajax calls. It's much easier to setup and straightforward. Especially, and specialy because it is very easy setup for a beginner. And for people who want to install ajax the easy way. I use it every single time I want to do ajax in my code. Here is a link:
http://api.jquery.com/jquery.ajax/
Just put the tag to include jQuery and then one javascript command to call the ajax.

Text file comes back empty when loading with Ajax javascript

I've searched and searched and could not find a solution for this:
I'm trying to load .txt file contents with Ajax but the file comes back empty.
I checked the ready state and status. ready state is 4 which means that connection was set, data received , status is 0 which means error for loading http but I read on a forum that it is ok for a local file.
I really don't know what to do.
all help will be appreciated!
this is my code:
<script>
function load() {
var selectedValue = document.getElementById("mySelect").value;
var xhttp;
alert("in func")
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
try{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
}
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && (xhttp.status == 200 || xhttp.status == 0)) {
document.getElementById("textDiv").innerHTML = xhttp.responseText;
alert(xhttp.responseText);
}
};
if(selectedValue == "Year 1"){
xhttp.open("GET", "file://year1.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 2"){
xhttp.open("GET", "year2.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 3"){
xhttp.open("GET", "year3.txt", true);
xhttp.send(null);
}
}
</script>
The issue is most likely the file protocol: file://year1.txt
try using a relative path instead, ie ./year1.txt
Edit..
I missed this the first time around.. you will get several hits to your callback function on a successful call. You'll get one where the status is zero first, then if successful you'll get another one with a 200. Why are you checking for both?
change this...
if (xhttp.readyState == 4 && (xhttp.status==200 || xhttp.status==0))
to this...
if (xhttp.readyState == 4 && xhttp.status==200)
OK! after EXTENSIVE research the problem was the infamous cross origin request problem (which does not allow access to local files as part of a security measure to insure you don't upload infected files &ct)
the solution is :
when initializing the variable for the XMLHttpRequest write:
xhttp = new XMLHttpRequest({mozSystem: true});
(notice the {mozSystem: true} inside the request)
AND IT SOLVES THE PROBLEM!!!
Thank you for your time, I hope this helps someone :)
My previous answer worked but not for long - after I restarted my computer the ajax stopped working at started throwing the cross origin error again. so- the best option I found that also works for all the browsers I checked (chrome, IE), is to set up a local server and run it from there.
here is a link for instructions:
https://www.maketecheasier.com/setup-local-web-server-all-platforms/
Good luck!

AJAX xmlhttp.responseText

I've been racking my brain for a few hours and can't figure out why a string comparison won't work. In the following code, I do a xmlhttp call and get a response text. The PHP file that I get a call IS returning the proper response string "NOAD", and NOAD is being displayed when appropriate in my testing. However, when the call is returned NOAD I want to identify it, however for some reason within the call below xmlhttp.responseText == comparisonText its NOT properly comparing the two. Why does xmlhttp.responseText printout NOAD but I can't use it within the comparator?
function loadXMLAdImage1Doc(currentScenarioTime)
{
var returnText = "Not Here";
var comparisonText = "NOAD";
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText == comparisonText)
{
document.getElementById("AJAXTEST").innerHTML =returnText;
} else {
document.getElementById("AJAXTEST").innerHTML =xmlhttp.responseText;
}
}
}
Okay, thanks Luth for pointing me in the right direction. I solved my problem, but I'm not sure what the problem is within xmlhttp.responseText or user error that caused it.
The return text from my PHP file was placing an unseen character BEFORE the returned string (in testing, I would have figured it was an invisible character after prior to the results but go figure). Theoretically, this shouldn't be happening...my PHP is returning a straightforward string:
..do some MYSQL queries..
$AdLink = mysql_result($result, 0);
if ($AdLink == "") {
echo "NOAD";
} else
{
echo $AdLink;
}
So the PHP file SHOULD be sending a 4 character return screen to the xmlhttp.responseText call named "NOAD". But what was found in measuring the string length was that it was sending a 5 character string back with some invisible character BEFORE "NOAD" that wasn't showing up on the screen - therefore screwing up the comparator. I used the following code to remove the character and it worked perfectly...
returnText = xmlhttp.responseText;
var returnlength = returnText.length;
returnText = returnText.substring(1, returnlength);
I have no idea WHAT the character is, whether its a problem with my PHP code or the xmlhttp.responseText call, but something to be aware of if you're dealing with the call.

Assigning a php variable from a javascript variable

I am trying to set a php variable for use in a later page with out using $_GET or $_POST. I am also assigning the same variable to a text box. I already have the function to assign the textbox variable but not the php variable.
function setText(data){
document.getElementById("filtext").value = data.value
// <?php $_SESSION["provid"] = ?>
// I am trying to set the php variable above
}
Any help would be greatly appreciated!
I think in this case, setting a cookie would be the easiest solution. By setting the cookie using Javascript, the cookie key and value will automatically be sent to PHP with the next page request.
See also:
http://www.w3schools.com/js/js_cookies.asp, especially "A Function to Set a Cookie"
http://www.w3schools.com/php/php_cookies.asp, especially "How to Retrieve a Cookie Value?"
To send a value for a server-side language you can use AJAX.
function setPHPVariable()
{
var myAjax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
myAjax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
myAjax=new ActiveXObject("Microsoft.XMLHTTP");
}
myAjax.onreadystatechange=function()
{
if (myAjax.readyState==4 && myAjax.status==200)
{
alert('PHP returned: ' + myAjax.responseText);
}
}
myAjax.open("GET","my_file.php?my_var=12345", true);
myAjax.send();
}
In your PHP code, you can use:
$myVar = $_GET['my_var'];
$_SESSION['my_var'] = $myVar; // or even $_SESSION['my_var'] = $_GET['my_var'];
http://www.w3schools.com/ajax/ajax_examples.asp

Show Save-As window from JSP

I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.

Categories

Resources