PHP jQuery "unterminated string literal" error in onclick handler - javascript

I'm using PHP to pass variables into the onclick of an element, however when I do this I get an "Unterminated string literal" error of the string is too long. My PHP is as follows:
$query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ID FROM gallery ORDER BY ID desc");
$query->execute();
$query->bind_result($name, $img, $desc, $link, $price, $id);
while($query->fetch())
{
if(strlen($desc) > 100)
{
$sdesc = substr($desc, 0, 100) . '...';
}
$onclick = 'popup(\'' . $name . '\', \'' . $desc . '\', \'' . $price . '\', \'' . $img . '\', \'' . $link . '\', ' . $id . ')';
echo '<div class="gallery" onclick="' . $onclick . '">
<img src="' . $img . '" alt="' . $name . '" />
<div><p>' . $sdesc . '</p>
' . $price . '
</div></div>';
}
My jQuery is as follows
function popup(title, desc, price, img, link, id)
{
$(".popupbodyg").children().remove();
var HTML = '<input type="image" src="close.gif" id="close" /><div><div id="comments">' +
'<iframe src="comments.php?id=' + id + '"></iframe><br /><input type="image" id="share" src="Very-Basic-share-icon.png" /></div>' +
'<div id="desc"><p>' + desc + '</p><br />' +
'<a class="gallery" href="' + link + '" target="_blank">' + price + '</a></div>' +
'<div id="img"><img src="' + img + '" alt="' + title + '"/></div></div>';
$(".popupbodyg").append(HTML);
$("#popup").toggle();
$(".popupbodyg #img").css("width", $(".popupbodyg").width() - 230 + "px");
$(".popupbodyg #img").css("height", $(".popupbodyg").height() - ($("#desc").height - 5) + "px");
$("#close").click(function(){
$("#popup").hide();
});
$("#share").click(function(){
$("#sharepopup").show();
$("#sharepopup").find("#link").attr("value", "http://www.encantojewellerydesign.com/gallery/?g=" + id);
$("#sharepopup").find(".fb-share-button").attr("data-href", "http://www.encantojewellerydesign.com/gallery/?g=" + id);
$("#sclose").click(function(){
$("#sharepopup").hide();
});
});
}
The only way I can think of right now is by limiting the amount of characters in the description, which I would like to avoid.

Did you try any of the string replace methods that are found elsewhere on SO?
$desc=str_replace("\n","\\n",$desc); //I'm guessing that the newline would probably be in the description if anywhere in the data you're passing.
ALSO:
Another slightly different approach would be to just embed the data into your element and retrieve the data with a single click handler that passes it to your popup function.
In other word, you could change the div.gallery look like this:
<div class="gallery" data-name=".$name." data-img=".$img." data-desc=".$desc." data-link=".$link." data-price=".$price." data-id=".$id.">
Then add an click handler like this:
$('gallery').on('click', function() {
var name = $(this).data('name');
var img = $(this).data('img');
var desc = $(this).data('desc');
var link = $(this).data('link');
var price = $(this).data('price');
var id = $(this).data('id');
popup(title, desc, price, img, link, id);
});

I am assuming that it has to do with the extra html characters that $description and other variables are passing to yout js. Try may be something like this(for a better answer, post a dump of the variables you are passing):
<?php
$query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ID FROM gallery ORDER BY ID desc");
$query->execute();
$query->bind_result($name, $img, $desc, $link, $price, $id);
while($query->fetch())
{
if(strlen($desc) > 100)
{
$sdesc = substr($desc, 0, 100) . '...';
}
$onclick = 'popup(\'' .strip_everything( $name ). '\', \'' . strip_everything($desc ). '\', \'' .strip_everything $price) . '\', \'' . $img . '\', \'' . $link . '\', ' . $id . ')';
echo '<div class="gallery" onclick="' . $onclick . '">
<img src="' . $img . '" alt="' . $name . '" />
<div><p>' . $sdesc . '</p>
' . $price . '
</div></div>';
}
function strip_everything($str){
$str = strip_tags($str);
return str_replace("\n" , ' ' , $str);
}

Related

Select2 Not active

<script>
$(document).ready(function(){
$("#btn-tambah-form").click(function(){
var jumlah = parseInt($("#jumlah-form").val());
var nextform = jumlah + 1;
$("#insert-form").append(
"<div class='row mb-10 p-10'>" +
" <div class='input-group col-md-2'>" +
" <?php $result = mysqli_query($conn, 'SELECT * FROM produk');?>" +
" <?php $jsArray = 'var idproduk = new Array();\n';?>" +
" <select class='form-control select2' id=\'idproduk"+nextform+"\' name=\'idproduk[]\' onchange=\'changeProduk"+nextform+"(this.value),sum();\' required>" +
" <option></option>" +
" <?php while ($row = mysqli_fetch_array($result)) {?>" +
" <?php echo '<option value=\'' . $row['idproduk'] . '\'>' . $row['produk_nama'] . '</option>';?>" +
" <?php$jsArray .= 'idproduk[\'' . $row['idproduk'] . '\'] = {harga_beli:\'' . addslashes($row['harga_beli']) . '\',produk_satuan:\'' . addslashes($row['produk_satuan']) . '\'};\n';?>" +
" <?php }?>" +
" </select>" +
" </div>" +
"</div>");
$("#jumlah-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#jumlah-form").val("1");
});
});
</script>
can someone help me. why my select2 not active when i put them on javascript.
when i put them outside java they can run correct.
please help me how to solve this code.
There is problem with backslashed quotes, remove them. It should be all.
<select class='form-control select2' id='idproduk"+nextform+"' name='idproduk[]' onchange='changeProduk"+nextform+"(this.value),sum();' required>" +

remove quotation mark in ajax response

the response comes back as "4" instead of just 4
I tried changing it to .done(function(data)) but still has the same result
$.ajax({
url: "../api/ajax/addToCart.php",
type: "post",
data: data
})
.done(function(response) {
// alert(response);
$('#cart_counter').html(response);
// console.log(JSON.parse(response));
getCart();
// console.log(response);
});
the ajax is taking the response from this page
addToCart.php
$sql1 = 'DELETE FROM temp_cart WHERE item_id = "' . $item_id . '" AND temp_id = "' . $temp_id . '"';
$result = $conn->query($sql1);
{
$sql2 = 'INSERT INTO temp_cart(temp_id, temp_name, temp_number, item_name, item_price, item_quantity, item_total, item_pic, item_id, date_expiry) VALUES ("' . $temp_id . '", "' . $temp_name . '", "' . $temp_number . '", "' . $item_name . '", "' . $item_price . '", "' . $item_quantity . '", "' . $total_row . '", "' . $item_pic . '", "' . $item_id . '", "' . $date_expiry . '" )';
$result = $conn->query($sql2);
{
$sql = "SELECT count(item_quantity) as count_quantity FROM temp_cart WHERE temp_id='$temp_id'";
$resultb = $conn->query($sql);
while($rowb = $resultb->fetch_assoc())
{
$cart_counter=$rowb['count_quantity'];
echo json_encode($cart_counter);
}
}
}
The data not really JSON format, but a number that is being stringified when you pass it back as JSON so it ends up a string. Just parse the string into a number as needed:
$('#cart_counter').html(parseInt(response));
let counter = 4;
let json = JSON.stringify(counter);
console.log(json, `is a ${typeof json}`);
console.log(`...now a ${typeof parseInt(json)}`);
document.querySelector('#target').innerHTML = parseInt(json);
<div id="target"></div>

Javascript Append function won't duplicate img src on each card

I have the following code that is suppose to loop through the arrays and print a card out for each one. It works when I hardcode my img src to a path on my computer. When I try and use my image array, my cards stop duplicating. I know my array is populated because I pull from it in another place in my code. I am evidently not putting the right quotes around stuff. Can someone see anything wrong?
var names= <?php echo json_encode($Names); ?>;
var colors= <?php echo json_encode($Color); ?>;
var Images= <?php echo base64_encode($Image); ?>;
//Can use variable as selector, not that I'm using a specific selector
//Try using array of arrays and pick one to each loop over
$(document)
.ready(function() {
$.each(colors,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card0'>" +
"<div class='subcard_style box_title'>" +
"<img class='card_image' src='data:image/png;base64, " + Images[i] + "' alt='Item #1' />" +
'<div class="profile">' +
'<div class="card_number">' + value + '</div>' +
'<div class="card_name">' + names[i] + '</div>' +
'<div class="tag_row">' +
'<div class="sample_item sample_item4"></div>' +
'<div class="sample_item sample_item3"></div>' +
'</div>' +
'</div>' +
'</div> ' +
"<div class='subcard_style box_status'>" +
The quotes look fine in my eyes. But because Images is not an array
var Images= <?php echo base64_encode($Image); ?>;
this can't work
"<img class='card_image' src='data:image/png;base64, " + Images[i] + "' alt='Item #1' />"
[update]
In your php code you are using base64_encode($image[$i]). But with
var Images= <?php echo base64_encode($Image); ?>;
you are encoding the array, not the images in the array. Try this instead:
var Images = [];
<?php
for ($i = 0; $i < count($image); $i += 1) {
echo 'Images['.$i.'] = "'.base64_encode($image[$i]).'";';
}
?>
That way the value of each item in your javascript array Images is the base64_encoded
representation of the value in your php array $image.
Make sure, the spelling of $image is right. In your comment you are using $image[0] but in your code snippet it's $Image.

Jquery Clone select not working properly

In my code of wordPress I am trying to clone <select> box with its options it works but the problem is all of its option went outside ending select tag </select> I am not confirm whats wrong with it
Preview Image
HTML Output: https://jsfiddle.net/h5voq4nt/
PHP Code
$output .= '<label for="_jwppp-video-url-' . $number . '">';
$output .= '<strong>' . __( 'Media URL', 'jwppp' ) . '</strong>';
$output .= '<a class="question-mark" href="http://www.ilghera.com/support/topic/media-formats-supported/" title="More informations" target="_blank"><img class="question-mark" src="' . plugins_url('jw-player-7-for-wp-premium') . '/images/question-mark.png" /></a></th>';
$output .= '</label> ';
$output .= '<p>';
$output .= '<input type="text" id="_jwppp-video-url-' . $number . '" name="_jwppp-video-url-' . $number . '" style="margin-right:1rem;" placeholder="' . __('Video (YouTube or self-hosted), Audio or Playlist', 'jwppp') . '" ';
$output .= ($video_url != 1) ? 'value="' . esc_attr( $video_url ) . '" ' : 'value="" ';
$output .= 'size="60" />';
$output .= '<input type="text" name="_jwppp-' . $number . '-main-source-label" id ="_jwppp-' . $number . '-main-source-label" class="source-label-' . $number . '" style="margin-right:1rem;';
$output .= '" value="' . $main_source_label . '" placeholder="' . __('Label (HD, 720p, 360p)', 'jwppp') . '" size="30" />';
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
$output .= '<option name="NoAds" value="NoAds"';
$output .= ($ads_client == 'NoAds') ? ' selected="selected"' : '';
$output .= '>No Ads</option>';
$output .= '<option name="AdCode1" value="AdCode1"';
$output .= ($ads_client == 'AdCode1') ? ' selected="selected"' : '';
$output .= '>Ad Code 1</option>';
$output .= '<option name="AdCode2" value="AdCode2"';
$output .= ($ads_client == 'AdCode2') ? ' selected="selected"' : '';
$output .= '>Ad Code 2</option>';
$output .= '<option name="AdCode3" value="AdCode3"';
$output .= ($ads_client == 'AdCode3') ? ' selected="selected"' : '';
$output .= '>Ad Code 3</option></select>';
JQuery Code
<script>
(function($) {
$(document).ready(function() {
var number = <?php echo $number; ?>;
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
//CHANGE PLAYLIST-HOW-TO
var tot = $('.jwppp-input-wrap:visible').length;
if(tot > 1) {
$('.playlist-how-to').show('slow');
var string = [];
$('.order:visible').each(function(i, el) {
string.push($(el).html());
})
$('.playlist-how-to code').html('[jw7-video n="' + string + '"]');
} else {
$('.playlist-how-to').hide();
}
$('.jwppp-more-options-' + number).hide();
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
};
$('#_jwppp-video-url-' + number).on('change',function() {
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
$('.jwppp-more-options-' + number).hide();
} else {
$('.more-options-' + number).show();
}
});
});
})(jQuery);
</script>
In PHP code has
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
this has an end slash (/), please remove it.

how to insert correctly in javascript and php

Hello. I have a function to add row. I just added a second input but I don't know how to insert it correctly.
My JS code:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfieldstest[]' + '" type="text" /><br />'
);
});
});
</script>
How I insert:
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
// HERE WHERE IT'S DOEST WORK //
foreach (array_combine( $_POST['dynfields,dynfieldstest'] as $key=>$value, $key=>$value1 )) {
$values = mysql_real_escape_string($value);
$values1 = mysql_real_escape_string($value1);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Thanks for help!
I'm guessing that you're looking for a solution that will scale as more and more inputs are added to the form. Here's a simpler way. It assumes that for each dynfields there will be a corresponding dynfieldstest, and we can count the number of dynfields in order to control the loop.
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
$post_count = count($_POST['dynfields']);
for ($i=0;$i<$post_count;$i++) {
$values = mysql_real_escape_string($_POST['dynfields'][$i]);
$values1 = mysql_real_escape_string($_POST['dynfieldstest'][$i]);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Also, it's time to stop using the deprecated mysql functions. Switch to mysqli for MySQL only, or if you switch to PDO you can interface with MySQL and lots of other database types (MSSQL, Oracle, PostgreSQL, SQLite, etc...).
You should insert all new rows at once.
And use mysqli or PDO in the future, not the old mysql_* functions.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
);
});
});
</script>
PHP:
if (isset($_POST['submit_val'])) {
if (is_array($_POST['dynfields'])) {
foreach($_POST['dynfields'] as $key=>$value)
{
$hobbies = mysql_real_escape_string($value);
$client = mysql_real_escape_string($key);
$queryStr[] = "('$hobbies', '$client')";
}
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ".implode(',',$queryStr), $connection );
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
To add new input simply add
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
to the js

Categories

Resources