javascript syntax error, missing ";" - javascript

I have a form with potential errors in the form defined in php. I'm used javascript to change the form action depending on whether errors are present or not. I've converted the php error variable, $errors using json_encode so I can use it in javascript. Running the file in Firefox I get the following error in Firebug:
Syntax error: missing ;
before statement var errors = "{"firstnameErr:......etc}, with the pointer at the letter f in firstnameErr. It looks like I have the errors in the json_encode object.
Here is the javascript:
<script type = "text/javascript">
function switchFormAction() {
var errors = [];
var errors = "<?php echo json_encode($errors); ?>";
if(!empty(errors)) {
alert("Please correct these errors");
}
else {
var element = document.getElementById("regForm");
element.setAttribute("action", "serraInsertForm.php");
return true;
}
}
window.onload = function() {
document.getElementById("regForm").onsubmit = function()
switchFormAction();
}
</script>
Probably something simple but I can't work it out. Javascript and json are new to me.
Appreciate any help stackoverflow can offer.

var errors = "<?php echo json_encode($errors); ?>";
^--- ^--
The indicated quotes are not necessary and are in fact causing the problem. json_encode() will produce whatever quotes/brackets are necessary to turn the data in $errors into syntactically valid Javascript. You're producing:
var errors = "{"somekey":"somevalue"}";
^--start string
^--end string
^^^^^^^ undefined variable
All you need is
var errors = <?php echo json_encode($errors); ?>;

Losing the quotes around here ought to do it.
var errors = "<?php echo json_encode($errors); ?>";
Should probably be:
var errors = <?php echo json_encode($errors); ?>;

Related

Uncaught SyntaxError:Invalid or unexpected token

Here is my code:
<script type="text/javascript">
var logged = "<?php echo $_SESSION['LoginValidation'] ?>"; // check loging or not for voting, favoriting and ...
$(document).ready(function(e) {
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 37) {
$("#header").addClass("header_shadow");
}
else
$("#header").removeClass("header_shadow");
});
});
</script>
And it throws this error:
The image seems I'm missing semi-colon in the end of line, But as you see in the code, I've written it.
So what's the problem? How can I fix it?
The error says "Undefined index: LoginValidation", so you'll need to make sure it exists before referencing it. I don't know how you intend your code to work, but you can do something like:
var logged = "<?php echo isset($_SESSION['LoginValidation'])
? $_SESSION['LoginValidation']
: ''; ?>";
This will use the value of $_SESSION['LoginValidation'] if it exists, otherwise it will set an empty string ("").
You have missing semi-colon in php tag echo statement .
var logged= "<?php echo $_SESSION['LoginValidation'] ?>"
Just change
var logged= "<?php echo $_SESSION['LoginValidation']; ?>"
Resolved
Check the session has value or not first like
var logged= "<?php echo (isset($_SESSION['LoginValidation'])?$_SESSION['LoginValidation']:''); ?>"
It will work for you.
If $_SESSION['LoginValidation'] isn't always going to be present, you'll need to at least return null or something to assign to logged.
Fortunately for you, if you'd output this variable properly with json_encode() (which makes it compatible with JSON), this happens automagically!
var logged = <?php echo json_encode($_SESSION['LoginValidation']) ?>;
I'll leave it to you to decide how you want to handle when that variable isn't there. You really should test for it (isset(), !empty(), etc.) so that you don't end up with warnings in your logs. (Also, turn off warnings and error output in your output... dump them into logs instead.)

Passing Array From PHP to JQuery json_encode

I have an HTML form generated by php which has a dropdown of voucherproviders.
I want to select the provider and have this populate the form for editing.
Here is my JQuery code:
$(document).ready(function() {
$(document).on('change','#id_voucherprovider',function(){
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
//The value I have got from the drop down is....
var value = $('#id_voucherprovider option:selected').val();
var vendortext = $('#id_voucherprovider option:selected').text();
//so the voucher provider is
alert(vendortext);
$('.ftext input').val(vendortext);
$("textarea#id_vendornotes").val(voucher_providers[value]);
});
});
voucherproviders is not being passed into the JQuery despite the echo json_encode($voucher_providers); code working when inline with the php code.
It seems to return a null array. Can anyone see what is wrong?
Many Thanks
Dave
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
json_encode returns a string, unless it is parsed it will not be usable. Use JQuery .parseJSON and you should have better results. :)
var jsonString = <?php echo json_encode($voucher_providers); ?>;
var voucher_providers = $.parseJSON(jsonString);
try this (note the quotes):
var voucher_providers = JSON.parse('<?php echo json_encode($voucher_providers); ?>');
parse your json ex: obj = JSON.parse(data);
Hi please check the json format at below site:-
http://jsonlint.com/
and check if this is fine.

Uncaught ReferenceError: testString is not defined

This is really weird..
I need to send a couple of variables through to jquery from PHP.. one is an INT and the other a string.
When $a is an INT it works fine but when i use a string, i get this error.. Uncaught ReferenceError: testString is not defined
Here is my code.
<?php $a = 'testString'; ?>
<script type="text/javascript">
var a = <?php echo $a; ?>;
alert(a);
</script>
I assumed that i needed to stick a (int) or (string) before the variable, but i wasn't entirely sure how to and unsuccessful in my googles/attempts.
Any ideas?
You forgot the quotes to make the value of var a a string:
var a = "<?php echo $a; ?>";
What you're writing into the document is:
var a = testString;
so javascript is looking for a variable called testString. Instead, you want the result to be:
var a = "testString";
so make sure you include the quotes around what php is writing in.
There are quotes missing in javascript code:
<script type="text/javascript">
var a = '<?php echo $a; ?>';
alert(a);
</script>

How to use javascript in PHP? The script tag is not recognized

I don't know why but the script tag is not working, the SELECT query is working but i am not getting the prompt from the javascript.
it is not redirecting anywhere only a blank screen is seen
$qry1="SELECT area, aadhar FROM user where username='$user'";
$result1 = $connector->query($qry1);
if($result1){
$row1=mysql_fetch_array($result1);
$userarea= $row1['area'];
$useraadhar=$row1['aadhar'];
}?>
<body>
<script type="text/javascript">
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
if(inputarea==userarea){
<?php/
//date
$today = date("Y-m-d");
//Create INSERT query
$qry = "INSERT INTO complain (user,category,regno,course,lecturer,room,details,address,datein) VALUES ('$userid','$category','$reg','$coursename','$lectname','$roomno','$details','$address','$today')";
//$result = #mysql_query($qry);
$result = $connector->query($qry);
//Check whether difjslk the query was successful or not
if($result) {
$errmsg_arr[] = 'Complain succesfully added, please wait for your response';
$errflag = true;
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: _new_complains.php");
exit();
}
header("location: _new_complains.php");
exit();
}else {
die("Query failed, couldn't add the new record");
header("location: _new_complains.php");
exit();
}
?>
}
You are sending data (for example body tag) before header(), therefore PHP creates an error. You just don't see it. Header needs to come before anything is sent to the browser (even a space).
You have multiple JS syntax errors:
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
Never EVER dump out raw text from PHP into a Javascript context. You're generating code that looks like
var inputarea=foo;
var userarea=bar;
var useradhar=baz';
The data will be seen as undefined variables, and you've got a stray ' in there. All of these errors will KILL the entire <script> block.
Always use json_encode() to dump from PHP->JS:
var inputarea = <?php echo json_encode($coursename); ?>;
This will GUARANTEE that you're producing correct Javascript code. The above line would produce
var inputarea = 'foo';
and be perfectly valid and executable code.

Sending PHP array to Javascript

I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});

Categories