I'm trying to build a product compare module with a bootstrap 4 dropdown.
Inside that dropdown there are products listed with some info. When you click delete at a product then a function called updateCompareis loaded. This function loads json data and updates the compare list. This all works fine except when there's only one product listed. When I click delete on the last item then the function throw errors.
So what I have is this:
function updateCompare(){
$.get(compareUrl + '?format=json', function(e) {
products = [];
$.each(e.compare.products, function(index, product) {
// ... code to build products ....
products.push(productHtml);
});
products.join('');
$('#compare .compare-inner .empty').html(products);
})
}
$(function(){
// delete product from compare
$(document).on("click", "#compare .remove", function(e) {
e.preventDefault();
var vid = $(this).closest('.item').data('vid');
var url = compareUrl + 'delete/' + vid;
$.ajax({
type: "POST",
url: url,
success: function(msg){
updateCompare()
}
});
});
});
The error I get is TypeError: a is undefined
What I tried in updateCompare is things like:
function updateCompare(){
$.get(compareUrl + '?format=json', function(e) {
products = [];
if(e.compare.products.length > 1 ){
$.each(e.compare.products, function(index, product) {
// .... code to build products
});
} else {
$('#compare').dropdown("dispose")
}
But above throws an error like: TypeError: e.compare.products is undefined
Also I tried:
if(e.compare.products.length > 1 || e.compare.products != NULL || e.compare.products != false ){
But that throws an error e.compare.products is undefined.
I've been working on this way too long so perhaps I miss something very simple. I just can't see it anymore :(
Any help greatly appreciated!!
As per request
Empty compare json:
{
"compare":false
}
JSON with 3 products:
{
"compare":{
"products":[
{
"id":39687158,
},
{
"id":39687161,
},
{
"id":39687164,
}
]
},
}
Related
I'm using MVC pattern in my project and I have controller product with method delete($slug)
On my page (~/show/basket) I have products that user wants to buy. There's a 'delete' button and when he clicks on that button I want to delete that product from SESSION and remove from current page.
I was trying with jquery ajax function:
$(document).ready(function() {
$('.on-delete').on('click', function() {
var path = '/ITAKADEMIJA_zavrsni_rad/3-itcomm/';
var slug = $(this).data('slug');
$.ajax({
url: $(location).attr('host') + path + 'product/delete/' + slug,
success: function(res) {
console.log(res);
},
error: function(err) {
console.log('ERROR!');
}
});
});
});
and then I have a method delete inside product controller
public function delete($slug)
{
$cardModel = $this->model('Card');
if ($slug === null) {
header("Location:" . BASE_ROOT . '/show/products');
} else if ($cardModel->getProduct($slug)) {
$product = $cardModel->getProduct($slug);
$cardModel->removeProduct($product);
header("Location: " . BASE_ROOT . '/show/basket');
}
}
public function removeProduct($product)
{
if (isset($_SESSION['products'][$product->slug]))
{
unset($_SESSION['products'][$product->slug]);
}
}
Now the problem is:
I'm getting this error:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'App\Controllers\Show' does not have a method 'index' in C:\Users\nikol\Dropbox\www\ITAKADEMIJA_zavrsni_rad\3-itcomm\app\Core\App.php on line 50
Nothing happens, that product is still in session. It looks like that function wasn't even called.
I would like to call the function, that function should remove product from session and from that page.
I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}
I have a select menu that, when a user makes a selection, it fires off an AJAX request to a PHP script to query a database and return a value that matches the selection and inserts this into an associated input field.
This is all working well, however I now need to cater for the possibility that an empty result might be returned (up until now a matching result was always returned). If that is the case it needs to delete the value from the associated input field/clear this input field.
Here's what a successful AJAX request returns (JSON data):
[{"senderMobile":"0412 345 678"}]
and here's what an empty result returns:
[{"senderMobile":""}]
Here's the AJAX code that calls the PHP script and updates the input field:
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
I gather I need to update this section to include an option that if there is no data to simply clear out the #smsFrom input field:
} else {
console.log( data[0].smsFrom );
$("#smsFrom").val(data[0].senderMobile);
but I'm stumped at this point.
You just need to check if senderMobile has a value. Try this:
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else if (data[0] && data[0].senderMobile) {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
} else {
$("#smsFrom").val(""); // or .html(""); I didn't get what kind of element is this...
}
You can try checking the response data for an empty string.
Code should look like this:
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else {
if(data[0].senderMobile == ""){
$("#smsFrom").empty();
continue;
}else {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
}
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
I have a list of items obtained upon querying a database. Result of the query is treated with jsonifyand finally obtained via getJson, by doing the following:
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output="<ul>";
for (var i in data.appts) {
output+="<li>" + data.appts[i].labo + "</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
});
So far so good...
Now I need to give the possibility to delete each of the above listed items, by calling (for example ) the following Flaskfunction:
#app.route('/appointments/<int:appointment_id>/delete/', methods=['DELETE'])
def appointment_delete(appointment_id):
appt = db.session.query(Appointment).get(appointment_id)
db.session.delete(appt)
db.session.commit()
return jsonify({'status': 'OK'})
Unfortunately I have no clue on how it's possible to bridge these two pieces of code. Since I've being struggling on that for a while, I would appreciate any help that will allow me to get out of the mud... Thanks a lot.!
EDIT according to #dcodesmith's comment
The getJSON response:
{
"appts":[
{
"id":1,
"day":"Mardi",
"labo":"l1",
"modified":[
"21/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"28/01/2014"
]
},
{
"id":4,
"day":"Vendredi",
"labo":"l1",
"modified":[
"22/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"31/01/2014"
]
}
]
}
Changes required
Firstly, edit your output HTML to include an anchor tag which should have a data-id attribute with the appts id assigned to it.
Create a click event on the anchor tag in your list of appts
Code
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output = "<ul>";
for (var i in data.appts) {
var appt = data.appts[i];
output += "<li>" + appt.labo + "delete</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
$(document).on('click', 'a.delete', deleteAppt);
function deleteAppt(e){
e.preventDefault();
var $this = $(this),
id = $this.data('id'),
url = "/appointments/" + id + "/delete/";
$.ajax({
url: url,
type: 'POST',
data: {id: id}
})
.done(function(data, textStatus, jqXHR){
if (data.status === 'OK'){
// if successful remove deleted row
$this.parent('li').remove();
}
})
.fail(function(jqXHR, textStatus, errorThrown){
//log your error here, if any is caught. This will be very helpful for debugging
})
}
});
Note: I know nothing about Flask, but this should work Ceteris Paribus
When i use blur function on textbox to check duplicate name using jquery ajax working fine.
Here is code:
function duplicate(data){
//alert(data); //successfully gives the value from the text input
$.post("test.php", {name: data}, function (data){
if(data){
alert('duplicate name');
}
});
}
$(function() {
$("#name").blur(function(){
var data = $("#name").val();
duplicate(data);
});
});
The problem is it show alert message, in some case we submit with duplicate name itself so there is no use of checking duplication.
Let me know the solution to check duplicate name using onsubmit function ( jquery ajax or javascript ).
Your question is confusing because you're using the same variable name, data, outside of your request as well as in the request callback.
I'm not sure if you're asking to check for duplication based on data that has already been submitted and is back on the page, data that exists on the server, or if the data's simply "yes".
Based on the code you provided, it would appear that data is considered to be duplicated if the server returns yes once the POST completes.
Either way, maybe this will help:
$(function() {
$('#name').blur(function() {
duplicate($('#name').val());
});
});
function duplicate(sData) {
var sDuplicateValue = ...; // assign this whatever constitutes a duplicate value
if(isDataDuplicate(sData, sDuplicateValue)) {
// you have duplicate data
}
$.post('test.php', { name: sData }, function(sResposeData) {
/* because of question ambiguity, i don't know if you want to compare
* sData and sResponseData, or sResponseData and "yes." if it's the latter,
* just do isDataDuplicate(sResponseData, "yes"); otherwise, do this:
*/
if(isDataDuplicate(sData, sResponseData) {
// it's the same..
}
});
}
function isDataDuplicate(sData, sDuplicateValue) {
if(sDuplicateValue === null) {
return sData === 'yes';
} else {
return sData === sDuplicateValue;
}
}
I'll do something like this:
$(function() {
$("#name").blur(function(){
var value = $("#name").val();
$.post(
"checkDuplicates.php",
{ name: value},
function (data){
if( data.response === 'yes'){
$("#name").css({
'border': '1px red solid'
}).parent().append('This name already exists');
} else {
return false;
}
},
'json'
);
});
});