remove quotation mark in ajax response - javascript

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>

Related

Adding a filter search button to w2ui grid

For my w2ui grid, I want to have a few search buttons to filter the data is pre-defined ways. (e.g. a "Big West" button to search for rows with "Big West" as the conference.
<button class="w2ui-btn" onclick="var obj = w2ui['grid']; obj.search({ field : 'conference', value : 'Big West', operator : 'contains', type: 'text' });">Big West</button>
When I click this button, the data doesn't change. Ideally, the first click would do the search, and clicking it again would take the search away.
if you use w2ui grid it has wonderful search button , but you need to do customize in the data source file to filter rows I paste a script with
PHP and its work perfect for w2ui grid, and will simplify the whole process, and use it as backend with suitable customize for your work :
$action = $_REQUEST[request];
$action = json_decode($action, true);
$vlimit = $action['limit'];
$voffset = $action['offset'];
$str = "";
$err = "";
$sql = "";
switch ($action['cmd']) {
case 'get':
if (isset($action['search']) && is_array($action['search'])) {
foreach ($action['search'] as $s => $search) {
if ($str != "")
$str .= " " . $action['searchLogic'] . " ";
$field = $search['field'];
switch (strtolower($search['operator'])) {
case 'begins':
$operator = "LIKE";
$value = "'" . $search['value'] . "%'";
break;
case 'ends':
$operator = "LIKE";
$value = "'%" . $search['value'] . "'";
break;
case 'contains':
$operator = "LIKE";
$value = "'%" . $search['value'] . "%'";
break;
case 'is':
$operator = "=";
if (!is_int($search['value']) && !is_float($search['value'])) {
// $field = "LOWER($field)";
// $value = "LOWER('".$search['value']."')";
$value = "'" . $search['value'] . "'";
} else {
$value = "'" . $search['value'] . "'";
}
break;
case 'between':
$operator = "between";
$value = "'" . $search['value'][0] . "' and '" . $search['value'][1] . "'";
break;
case 'more':
$operator = ">";
$value = "'" . $search['value'] . "'";
break;
case 'less':
$operator = "<";
$value = "'" . $search['value'] . "'";
break;
default:
$operator = "=";
$value = "'" . $search['value'] . "'";
}
$str .= $field . " " . $operator . " " . $value;
}
$sql = "select * from [table] "
. " WHERE ~search~ limit $vlimit offset $voffset ";
$sql = str_ireplace("~search~", $str, $sql);
}
else
{
$sql = "select * from [table] ";
}
echo '{"status": "error","message":"' . $sql . '"}';
break;
$stm = $conn->query($sql);
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
$number = $stm->rowCount();
$json = json_encode($result, JSON_UNESCAPED_UNICODE);
header("Content-type: application/json");
echo '{"total" : "' . $number . '","records" : ' . $json . '}';
break;
case 'delete':
$rec_id = $action['selected'][0];
$sql = "DELETE FROM [table] WHERE rec_id = :recid";
$stmt = $accountdb->prepare($sql);
$stmt->bindParam('recid', $rec_id);
try {
$stmt->execute();
echo '{"status" : "success"}';
break;
} catch (Exception $err) {
echo '{"status": "error","message":"' . $err->getMessage() . '"}';
break;
}
case 'save':
/**/
break;
default:
$err = 'default error';
echo '{"status": "error","message":"' . $err . '"}';
break;}

jQuery not pushing JSON-data

I have the following script which is supposed to pull data and display it in a HTML table:
$('#search_filter_button').click(function (e) {
e.preventDefault(); // Stop form submission
var county = $('#filter_county').val(),
kp_type = $('#filter_kp_type').val(),
getUrl = window.location,
baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
html_tr = '';
$.ajax({
type: 'GET',
url: baseUrl + "/reports/get_report.php?county=" + county + "&kp_type=" + kp_type,
dataType: "JSON",
success: function (data) {
console.log(data);
for (i = 0; i < data.length; i++) {
html_tr += '<tr>\n\
<td>' + data[i].name + '</td>\n\
<td>' + data[i].Abbrv + '</td>\n\\n\
<td>' + data[i].partner_name + '</td>\n\\n\
<td>' + data[i].facility_name + '</td>\n\\n\
<td>' + data[i].county + '</td>\n\\n\
<td>' + data[i].no_kps + '</td>\n\\n\
<td>' + data[i].activity_stamp + '</td>\n\</tr>';
}
$('#tbody_append').empty();
$('#tbody_append').append(html_tr);
}, error: function (data) {
}
});
});
My get_report.php file looks like this:
include '../database/db_connect.php';
$mysqli = mysqli_connect($host_name, $user_name, $password, $database);
$county = $_GET['county'];
$kp_type = $_GET['kp_type'];
// get the records from the database
$result = mysqli_query($mysqli, "SELECT * FROM `no_individaul_kps_contacted` where county='$county'");
$count_row = mysqli_num_rows($result);
if ($count_row >= 1) {
// display records if there are records to display
while ($user_data = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo json_encode($user_data);
}
} else {
// show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
mysqli_close($mysqli);
This pulls the information and echoes it back in JSON ENCODE format. But my JavaScript is not returning a success.
Please advise what am I doing wrong.
Collect the user data into array inside the while loop and move json_encode($data) outside the while loop:
$select = "SELECT * FROM `no_individaul_kps_contacted` where county='$county'";
$result = mysqli_query($mysqli, $select);
$data = [];
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);

PHP jQuery "unterminated string literal" error in onclick handler

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);
}

execute javascript from dom in ajax response

I have a page which loads it's content from ajax response. The problem is that ajax igonres all my scripts from the head tag in my html page. Is there any way to make those javascript files to execute in my ajax response?
ajax:
$(document).ready(function () {
$(".all").click(function () {
var all = $(this).attr("id");
if (all != '') {
$.ajax({
type: "POST",
url: "php/searchbrowselist.php",
data: "all=" + all,
async: true,
success: function (option) {
var $this = $("#browsemusic")
$this.html(option);
$('#sortable1, #sortable2').sortable({
connectWith: ".connected"
}).disableSelection();
}
});
}
});
});
php:
<?php
include ('dbcon.php');
if (isset($_REQUEST['all']) && $_REQUEST['all'] != '') {
// ===============================Button "ALL"====================================
unset($_REQUEST['kw']);
unset($_REQUEST['genre']);
$query = "select * from music";
$result = mysqli_query($link, $query) or die(mysqli_error());
echo '<ul id="sortable1" class="connected">';
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
echo '</ul>';
}
elseif (isset($_REQUEST['kw']) && $_REQUEST['kw'] != '') {
// ============================= Search for music ================================
$kws = $_REQUEST['kw'];
$kws = mysqli_real_escape_string($link, $kws);
$query = "select * from music where title like '%" . $kws . "%' or artist like '%" . $kws . "%'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
echo '<ul id="sortable1" class="connected">';
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
echo '</ul>';
}
elseif (isset($_REQUEST['genre']) && $_REQUEST['genre'] != '') {
// =====================================Browse By Genre ===========================================
$genre = $_REQUEST['genre'];
$genre = mysqli_real_escape_string($link, $genre);
$gquery = "select music_id from musicgenre where genre_id = '$genre'";
$results = mysqli_query($link, $gquery) or die(mysqli_error($link));
$music = array();
while ($id_result = mysqli_fetch_array($results)) {
$music[] = $id_result['music_id'];
};
echo '<ul id="sortable1" class="connected">';
foreach($music as $song) {
$query = "select * from music where music_id = '$song'";
$result = mysqli_query($link, $query) or die(mysqli_error());;
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
};
echo '</ul>';
}
else {
// ================================ Default =========================================
$query = "select * from music";
$result = mysqli_query($link, $query) or die(mysqli_error());
echo '<ul id="sortable1" class="connected">';
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
echo '</ul>';
};
?>
html:
<div id="browsemusic">
<?php include ( 'php/searchbrowselist.php'); ?>
</div>
so, the php file gets some values from ajax and loads the results in my div. I need it to also execute my scripts loaded in the head:
<head>
<script src="js/berniecode-animator.js"></script>
<script src="js/soundmanager2.js"></script>
<script src="js/360player.js"></script>
</head>

Multiple select value alerts half value

I would like Javascript to alert the whole employee name (first and last names) but with this code, it only shows the first name for some reason. Any Ideas on how to fix this problem?
Here's my code:
if ( $even1 % 2)
echo "<option value=". $employee_firstname . " " . $employee_lastname . ">". $employee_firstname . " " . $employee_lastname . "</option>";
else
echo "<option value=". $employee_firstname . " " . $employee_lastname . ">". $employee_firstname . " " . $employee_lastname . "</option>";
The javascript:
var List = document.getElementById('slcEmp');
var x = 0;
for (x = 0; x < List.length; x++) {
if (List[x].selected) {
alert(List[x].value);
}
}
You need to put the attribute value in quotes, since it contains a space:
echo "<option value='". htmlentities($employee_firstname) . " " . htmlentities($employee_lastname) . "'>". $employee_firstname . " " . $employee_lastname . "</option>";
^ ^
You should also use htmlentities() in case the name contains special characters (e.g. O'Leary).

Categories

Resources