I have a e-commerce system. And i'm adding products to my cart like on screenshot
When i click to add to cart button. I'm showing a shopping cart notification which is bootstrap popover. The main problem is when i decide to another product i recived same notification.
I'm writing "Product A is added." When i do that in every different product adding it writes Product A is added. Adding i correct but notification is wrong.
Here is my jQuery Code...
$('.quick-add-cart').click(function(){ //Sepete Ekleme İşlemi yapıyoruz.
$('#cart-popover').attr('data-content','');
productID = $(this).parents('.productbit').attr('id');
$.ajax({
type: "POST",
url: "ajax/add_to_cart.php",
dataType: 'json',
data: {
productID : productID
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Bağlantı sağlanamadı.\n Lütfen internet bağlantınızı kontrol ediniz.');
} else if (jqXHR.status == 404) {
alert('Sayfa bulunamadı. [404]');
} else if (jqXHR.status == 500) {
alert('Sunucu Hatası [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.'+ jqXHR.responseText);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax istemi durduruldu.');
} else {
alert('Beklenmeyen Hata.\n' + jqXHR.responseText);
}
},
success: function (data) {
if (data.insert_count > 0) {
cart_old_count = $('#cart_count').text();
cart_new_count = parseInt(cart_old_count,10) + data.insert_count;
$('#cart_count').text(cart_new_count);
}
$('#cart-popover').attr('data-content',data.queryresult).popover('show');
setTimeout(function() {
$('#cart-popover').popover('hide');
}, 5000);
}
});
});
And here is my add_to_cart.php
require_once '../includes/class/class.cart.php';
include_once '../locale.php';
session_start();
$C = new Cart();
//Sepete Ürün Ekliyoruz
if (isset($_POST['productID'])){
if (!isset($_SESSION['userid'])) {
$jsonData['queryresult'] = "Sepete Ekleme Yapabilmek için Bayi Girişi Yapmalısınız !";
} else {
$productid = $_POST['productID'];
$product = $C->get_product_fields('product', $productid);
$jsonData['update_count'] = 0;
$jsonData['insert_count'] = 0;
$cart_error = FALSE;
if ($C->is_in_cart($productid)) {
if ($C->update_cart($productid))
$jsonData['update_count'] += 1;
else {
$jsonData['queryresult'] = $C->cart_errors($productid);
$cart_error = TRUE;
}
} else {
if ($C->add_to_cart($productid))
$jsonData['insert_count'] += 1;
else {
$jsonData['queryresult'] = $C->cart_errors($productid);
$cart_error = TRUE;
}
}
if ($cart_error === FALSE) {
if ($jsonData['insert_count'] == 1){
$jsonData['queryresult'] = "Bir paket ".$product." eklendi.";
}
if ($jsonData['update_count'] == 1){
$jsonData['queryresult'] = "Bir paket daha ".$product." eklendi.";
}
if ($jsonData['insert_count'] == 0 && $jsonData['update_count'] == 0){
$jsonData['queryresult'] = "Ürünü sepete ekleme sırasında hata oldu.";
}
}
}
header('Content-type: application/json');
echo json_encode($jsonData);
}
related issue: Twitter bootstrap js popover content doesn't update when data-content attribute is updated
Two changes are required to solve your problem:
Instead of .attr('data-content', data.queryresult), you should use .data('content', data.queryresult)
You need to use .popover('destroy') before updating the content, this prevents popover from getting lost with async processing.
Here is a sample code, I have used setTimeout to simulate the Ajax call:
function displayPopover(msg) {
$('#cart-popover').popover('destroy');
$('#cart-popover').data('content',msg).popover('show');
setTimeout(function() {
$('#cart-popover').popover('hide');
}, 5000);
}
// add first product to cart
setTimeout(function() { displayPopover('product 1') }, 2000);
// add second product to cart
setTimeout(function() { displayPopover('product 2') }, 4000);
You can see it in action here: http://jsbin.com/UXAxEBE/1/
tip: when you have such type of error where you don't know whether the problem is at php or javascript side, you should try to console.log(data.queryresult) in your javascript to validate that php returns the correct content and that your problem is at client side.
Related
I am trying to fill a dropdown using Ajax and PHP with JQuery. For some reason, I always get a Parse JSON Error.
JS file
function loadRolesToDropDown() {
var url = 'controller/get_all_roles.php';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
success: function (data) {
var len = data.length;
$("#roledropdown").empty();
for (var i = 0; i < len; i++) {
var roleId = data[i]['roleId'];
var roleName = data[i]['roleName'];
$("#roledropdown").append("<option value='" + roleId + "'>" + roleName + "</option>");
}
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internal Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknown Error.\n' + x.responseText);
}
}
});
}
get_all_roles.php
$roleDaoImpl = new RoleDaoImpl($pdo);
$roleDaoImpl->getAllRoles();
Implementation of getAllRoles()
function getAllRoles()
{
$roleList[] = "";
try {
$SQL = "CALL getAllRoles()";
$sp_getAllRoles = $this->connection->prepare($SQL);
$sp_getAllRoles->execute();
$resultSet = $sp_getAllRoles->fetchAll(PDO::FETCH_ASSOC);
foreach ($resultSet as $row) {
$roleId = $row['role_id'];
$roleName = $row['role_name'];
$roleList[] = array("roleId" => $roleId, "roleName" => $roleName);
}
echo json_encode($roleList);
} catch (PDOException $e) {
die($e->getMessage());
}
}
And when I tried to echo what's return by json_encode($roleList); I get the ff:
["",{"roleId":1,"roleName":"Administrator"},{"roleId":2,"roleName":"Teacher"},{"roleId":3,"roleName":"Student"}]
What is the correct way to parse the php object array return by php?
Thank you.
In your php function getAllRoles
function getAllRoles()
{
$roleList[] = ""; // -> should be $roleList = [];
In your get_all_roles.php if you are getting such type of result from query then this code will work
$resultSet = array(0=>array('role_id'=>1,'role_name'=>'Administrator'),1=>array('role_id'=>2,'role_name'=>'Teacher'),2=>array('role_id'=>3,'role_name'=>'Student'));
foreach ($resultSet as $row) {
$roleId = $row['role_id'];
$roleName = $row['role_name'];
$roleList[] = array("roleId" => $roleId, "roleName" => $roleName);
}
echo json_encode($roleList);
I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.
$(document).ready(function () {
$("#comments_form").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'process_in.php',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
var x = jQuery.parseJSON(result);
alert(x.f);
},
});
});
})
<?php
include ('connection.php');
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
}
function xssafe($d)
{
$x = filter_var($d, FILTER_SANITIZE_STRING);
return $x;
}
A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception.
Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.
$.ajax({
type: 'POST',
url: 'process_in.php',
dataType: 'JSON',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
console.log(result.f);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
You can learn how to debug the code and check your error logs
Now lets get to your code, there are many possible cases that you are not getting the value.
It could be your php code or it could be your jquery.
In php to check whether its returning a valid json hit the url in browser like this
http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo
As in your php code you haven't return any value so add an else part for the
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
} else {
echo json_encode(['error'=>'Invalid request']);
}
My site works like this:
User has a balance stored in a database under column named currency. He earns currency then after earning enough he goes to another page to get accounts in exchange of these currencies. I set up everything but something is bugging me since an hour. If user has enough currencies and he retrieve an account, he can refresh and retrieve another account and even though he doesn't have enough currencies my system is still giving him his account on firefox but not on chrome (There are the browser I have tested until now) I'm handling this with session, ajax, and php to handle the delivery and here is the codes:
1. In the file below: I check how much the user has currencies and assign an ability session which will then be checked when retrieving the accounts. User can either get an account with currency amount of 250 or 1000 or 2500 and I am checking how much currency he can have on account:
<?php session_start();
unset($_SESSION["ability"]);
$unames = $_SESSION['username'];
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database-name", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyamount = $row['currency'];
}
if ($currencyamount<250){
$_SESSION["ability"]= 'zero';
echo $_SESSION["ability"];
}
elseif ($currencyamount<1000) {
$_SESSION["ability"]= 'one';
echo $_SESSION["ability"];
}
elseif ($currencyamount<2500) {
$_SESSION["ability"]= 'two';
echo $_SESSION["ability"];
}
else {
$_SESSION["ability"]= 'three';
echo $_SESSION["ability"];
}
?>
I then have the jquery file listening to this php file, for its echos, which will if the user has an ability of 1 allow him to get an account with 250 currencies, if he has an ability of 2: 1000 currencies, if he has an ability of 3: 2500 currencies. If he has ability 0, he won't get any account if he tries, it alerts him to refresh and if he tries to get two accounts or more without refreshing (Did this because I wanted to unset the session when the page loads again then set them because the abilities may change) The script also deletes each account the user got from the database.
$(document).ready(function () {
var ability = 'zero';
var click = 0;
$.ajax({url: "ability.php"}).done(function( html ) {
ability = html
});
$('#currency2500').click(function(){
if (click==0){
if (ability != 'zero') {
function show_account() {
$.ajax({
type: "POST",
url: "select1.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency250').click(function(){
if(click==0){
if (ability != 'zero') {
var id=$(this).data("id3");
$.ajax({
url:"delete1.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
function show_account() {
$.ajax({
type: "POST",
url: "select2.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
var id=$(this).data("id3");
$.ajax({
url:"delete2.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
function show_account() {
$.ajax({
type: "POST",
url: "select3.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
var id=$(this).data("id3");
$.ajax({
url:"delete3.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
}
});
});
Here is the php file that will deliver the account with 250 currencies to the user, there is also the ones which are the same for 1000, 2500 and with just the value 250 changed. if its called by jquery:
<?php
session_start();
$link = mysqli_connect( 'localhost', 'database-username', 'database-password', 'database' );
$action=$_POST["action"];
if($action=="showroom") {
$query="SELECT * FROM tablename LIMIT 1";
$show = mysqli_query($link, $query) or die("Error");
echo "<p id='paragraph' style='font-size:22px;font-weight: bold;'>Here is your 250 currencies account:</p>";
echo "<table style='position:relative;bottom:30px;' border='2px'><tr><td>Email</td><td>id</td></tr>";
while ($row = mysqli_fetch_array($show)) {
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['id'] . "</td></tr>";
}
echo "</table>";
$unames = $_SESSION['username'];
$query2 = "UPDATE users SET currency=currency-250 WHERE username='$unames'";
$update = mysqli_query($link, $query2);
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyvalue = $row['currency'];
}
unset($_SESSION['currencynumber']);
$_SESSION["currencynumber"]=strval($currencyvalue);
}
?>
Then the page which users gets in: ( Only a part from it )
<?PHP
session_start();
if( !isset($_SESSION['username']) ) {
header ("Location: login.html");
}
<div id="accountinfo"></div>
<input type="button" id="currency2500" value="Get 2500 currencies" />
<input type="button" id="currency1000" value="Get 1000 currencies" />
<input type="button" id="currency250" value="Get 250 currencies" />
So: If using firefox: I can refresh 2-4 times until i can't get accounts anymore and my balance will be negative after getting those accounts. Maybe there is a way that if the balance gets negative to cancel the operation and not show anything to the user? Or how can it be solved? I am using sessions to track.
I have this code , iam trying to use javascript to stop executing but its not working with javascript , any suggestions ? Am just trying to stop executing if the return was false from the javascript
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if (r == true) {
return true;
} else {
return false;
}
}
check();
</script>
<?php
}
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run)die("error".mysql_error());
I am adding sample code to give you an idea, how you could use AJAX Call with it.
<?php
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if(r) {
// Add additional parameter
// You could use POST method too. Use whatever make sense to you.
var urlLink = 'http://www.example.com/warehouse/record.php?from=<?php echo $from?>&to=<?php echo $to?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
return 'You have successfully added new record!';
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
</script>
<?php } ?>
<?php
// -- New File: record.php File
//
// You might wanna add the check, that it's the legit request and all the PHP Validation
$form = $_GET['from'];
$to = $_GET['to'];
$qty = $_GET['qty'];
$codeid = $_GET['codeid'];
$uid = $_GET['uid'];
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run) die("error".mysql_error());
else return 'success';
?>
I cannot get this script work. I try to warn if login that user entered is available. But I cannot manage this script to work:
$( "#myRegForm" ).submit(function( event ) {
var errors = false;
var userAvi = true;
var loginInput = $('#login').val();
if( loginInput == ""){
$("#errorArea").text('LOGIN CANNOT BE EMPTY!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if(loginInput.length < 5 ){
$("#errorArea").text('LOGIN MUST BE AT LEAST 5 CHARACTERS!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if (loginInput.length >=5) {
$.post('checkLogin.php', {login2: loginInput}, function(result) {
if(result == "0") {
alert("this");
}
else {
alert("that");
}
});
}
if (errors==true) {
return false;
}
});
Everything works fine until loginInput.length >=5 else block. So I assume there is a problem with getting answer from PHP file, but I cannot handle it, though I tried many different ways. Here is checkLogin.php's file (note that jQuery script and PHP file are in the same folder):
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}
else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo "0"; // for you to use if(if(result == "0") you should send a string
} else {
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
?>
You're literally sending the string 'loginInput'.
change
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) {
to
$.post('checkLogin.php', {login2: loginInput}, function(result) {
Edit
I would just comment out everything except the following for now and see if that at least works
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) { // put loginInput back in quotes
alert('#'+result+'#'); // # to check for whitespace
});