syntaxerror: expected expression, got '}' in php and javascript - javascript

I have a select option and when I select an option it must show my colors
Look at my codes
<?php foreach ($colors as $color) { ?>
<option onclick=addColor("<?php echo $color->title ?>", this) value="<?= $color->id ?>"><?= $color->title ?></option>
<?php } ?>
script
function addColor(color_name, tag) {
var optionTag = $(tag);
var selectColor = '<span class="select-color mr-1"><img src="public/images/dialog_close.png">+color_name+</span>';
var divRow = optionTag.parents('.row');
divRow.append(selectColor);
}
but i get this error.
SyntaxError: expected expression, got '}'

Try
PHP
You are not defining the end and beginning of your onclick attribute, enclose it with " " as you also need a string parameter to your method enclose it with ' ' as to not terminate the attribute string prematurely.
<option onclick="addColor('<?php echo $color->title ?>', this)" value="<?= $color->id ?>"><?= $color->title ?></option>
Javascript
Terminate your string around the variable to indicate that the variable is to be appended to the string. If you just write + var + inside a string that will be a normal part of the string.
var selectColor = '<span class="select-color mr-1"><img src="public/images/dialog_close.png">'+color_name+'</span>';
You are also mixing output methods in your PHP, I would recommend sticking to one kind of make it easier to read your code.

Related

Quotes breakes JS variable

I need create var in js script, something like this:
var map = "<div class="map"><?php echo do_shortcode('[wpgmza id="3"]'); ?></div>";
but apostrophes and quotes breaks code. How to change it to make it works?
Use other quotes or escape them.
var map = `<div class="map"><?php echo do_shortcode('[wpgmza id="3"]'); ?></div>`;
var map2 = "<div class=\"map\"><?php echo do_shortcode('[wpgmza id=\"3\"]'); ?></div>";
console.log(map);
console.log(map2);
Escape the quotes.
var map = "<div class=\"map\"><?php echo do_shortcode('[wpgmza id=\"3\"]'); ?></div>";
If you open the value with " then JavaScript will look for the second " to know where the value ends. As you're now using this within the value as well it stops to early. By escaping the " that you want to use within your value, you will make sure JavaScript knows it is part of the value.
So in your code, Javascript will stop after the second ":
var map = "<div class="
As you can see you did now open it with " and after the = there is another " so the value will be closed. How ever, you still have some more code after it: map"><?php echo do_shortcode('[wpgmza id=\"3\"]'); ?></div>";
As JavaScript doesn't know what to do with this part, it'll throw an error.
Maybe this will explain it better if you don't understand the above part:
You can see it as an if statement where if { } you need two brackets. One to open { and one to close }. In your value you need also two characters, one to open and one to close. In your case you use a " to open the value and " to close. So as soon as it hits the second " it'll close the value.
The assignment you did is comparable with this if-statement: if { } }. JavaScript doesn't know what to do with the latest }, as there is no other if-statement to close and because of that reason it'll throw an error.
You can fix the value of your variable using a few methods:
Escaping the quotes
You can add a backslash to the double quotes to make the JS parser ignore them. I would also concatenate the PHP value for clarity:
var map = "<div class=\"map\">" + <?php echo do_shortcode('[wpgmza id="3"]'); ?> + "</div>";
Using single quotes and double quotes alternatively
If you need to use double quotes in the value, you can just wrap it with single quotes.
var map = '<div class="map">' + <?php echo do_shortcode('[wpgmza id="3"]'); ?> + '</div>';
It also works the other way around, if you prefer single quotes in HTML attribute values
var map = "<div class='map'>" + <?php echo do_shortcode('[wpgmza id="3"]'); ?> + "</div>";
Template literals
In ES6, you can use template literals using the back-tick character. Notice you can both use single and double quotes inside a template literal:
var map = `<div class="map"><?php echo do_shortcode('[wpgmza id="3"]'); ?></div>`;
var map = /"<div class=/"map/"><?php echo do_shortcode('[wpgmza id=/"3/"]'); ?></div>/";
or
var map = "<div class='map'><?php echo do_shortcode('[wpgmza id='3']'); ?></div>";

Can't show the query result in select option

UPDATE
I'm working with codeigniter, and i have simple select option like this:
<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv" >
<?php
$jj = "<script>var e = document.getElementById('id_barang').value;document.write(e);</script>";
$noInv = $this->modelku->select_inv($jj);
?>
<option value="" selected="selected" disabled>Pilih no inventaris</option>
<?php
foreach($noInv->result() as $inv){ ?>
<option value="<?php echo $inv->no_inv ?>">
<?php echo $inv->no_inv ?>
</option><?php }
?>
</select><br>
And this is my html element with id = id_barang:
<select name="id_barang" id="id_barang" class="form-control">
<?php $idBarang = $this->modelku->select_idBrang() ?>
<?php foreach($idBarang->result() as $idBr){ ?>
<option value="<?php echo $idBr->id_barang ?>"><?php echo $idBr->id_barang ?></option>
<?php } ?>
</select required>
select_inv function from modelku:
public function select_inv($idbrang)
{
$this->db->select("no_inv");
$this->db->from('detail_barang');
$this->db->where('kondisi', 'Ada');
$this->db->where('id_barang ', $idbrang);
$query = $this->db->get();
return $query;
}
But when i click the select option, the value from no_inv doesn't appear in my select option?
Can someone help me pls?
You can't assign a value to a PHP variable by using javascript, since they have different times for execution, and when you use the script tag, unless the browser loads it, it will be only a PHP string. I think you'll need to change this to use a PHP value for the assignment.
the problem lies in using a variable $idbrang in the manual written where clause. To use a variable change the line
$this->db->where("kondisi = 'Ada' AND id_barang = '$idbrang' ");
to
$this->db->where('kondisi', 'Ada');
$this->db->where('id_barang ', $idbrang);
more info here
note: I gave this answer before the OP was completely remodeled
You can't do this:
<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv" >
<?php
$jj = "<script>var e = document.getElementById('id_barang').value;document.write(e);</script>";
$noInv = $this->modelku->select_inv($jj);
?>
<!-- // ... -->
</select>
Because the content of your PHP $jj variable is plain text, it will not select your #id_barang value. $jj will returns exactly what you put into quotes.
One way to do what you expect is using Ajax to pass javascript values to a PHP file using POST/GET methods. Here are more details.
This : id="field_' + count + '" name="fields[]' + '" will not work too because you're using a javascript variable into HTML. You can set your select id using plain javascript into a <script> tag.

Quotes error when passing php string value to javascript onClick

I want to passing variable from php to Javascript. But it can only passing integer type. When I pass value that is not integer, the variable value is undefined.
<?php
$sqlCall="SELECT * FROM table";
$resCall=mysqli_query($con, $sqlCall);
while($row=mysqli_fetch_array($resCall)){
echo "<tr>";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[name]."</td>";
echo "<a onclick='edit(".$row['id'].",'".$row['name']."')'>Edit</a>"
?>
and here is my JavaScript:
<script>
function edit(id, name){
document.getElementById('edit_id').value = id;
document.getElementById('edit_name').value = name;
}
</script>
The problem comes from the single quotes ' use " instead like :
"<a onclick='edit(".$row['id'].","".$row['name']."")'>Edit</a>"

Referencing a defined html variable in JS

My index.php page includes a config.php file, which returns an array that I have defined some variables in by using "define('var1' , 10)".
I am trying to validate my forms input, but I can't figure out how I can reference var1 from within the JS function. What is the easiest way to do this?
Just echo it to a javascript variable:
<script type="text/javascript">
var var1JS = "<?php echo $var1; ?>";
</script>
Not quite sure I am full understanding without seeing the code but, you could echo the variable from the PHP array in the JS function (as above answer).
Or Echo the entire JS query:
$y = count($PHPdata_array);
echo "function exampleFunction() {";
echo "var ArrayName = [";
for ($i = 1; $i <= $y; $i+=2) {
echo "{" . $PHPdata_array[$i] . "," . $PHPdata_array[$i-1] . "},";
}
echo "];";

php create javascript in foreach loop

i have the following code, but it will not work. i am trying to create a script output:
echo "<script type=\"text/javascript\"><!--\n";
echo "SLIDES = new slideshow(\"SLIDES\")\n";
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $fname ) {
echo 's = new slide()\n';
echo 's.src = \"http://cashbackflorida.com/wpradmin/modules/wprrets/photos/'.$result ->MLS.'/'{$fname}\n\"';
echo 's.width = \"560\"\n';
echo 's.height = \"420\"\n';
echo 's.alt = \"{$fname}\"\n';
echo 's.text = unescape(\"\")\n';
echo 's.link = \"\"\n';
echo 's.target = \"\"\n';
echo 's.attr = \"\"\n';
echo 's.filter = \"\"\n';
echo 'SLIDES.add_slide(s)\n';
}
echo '--></script>\n';
Don't do it this way. Just output the array to JavaScript and deal with it there.
var files = <?php echo json_encode($files); ?>;
You'll find the problem in your string escaping
echo 's.height = \"420\"\n';
You can't escape in single quote strings like that. So try this
echo "s.height = \"420\"\n";
You do NOT need to escape single quotes within double quotes or visa versa, but you can only get a newline character like that in a double quote string.
I would recommend HEREDOC for this kind of string writing though.
$fnamej = json_encode($fname);
echo << EOT
s.height = "420";
s.alt = $fnamej;
EOT;
I am also inclined to say that you'd be better off handling this in javascript. This may end up behaving very badly all of a sudden, and it will take up more bandwidth.

Categories

Resources