Need to add direct checkout instead of adding to the cart in opencart 2.3.0.2 - opencart

Orignal code from opencart:-
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
// Need to set timeout otherwise it wont update the total
setTimeout(function () {
$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
}, 100);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
},
I tried to edit these way but it had no effect on the front end everything was same
check below i tried replacing the code here:-
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
if (json['redirect']) {
location = json['redirect'];
}
//here i replaced the code
if (json['success']) {
window.location='index.php?route=checkout/checkout';
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
},
can anyone kindly help me out with these opencart 2.3.0.2 problem..??

This should work, I'm on 2.3.0.2 and have multiple stores using this in the Success statement to redirect to the cart page after clicking add to cart.
window.location.href = "index.php?route=checkout/cart";
Obviously you'd want to change it to:
window.location.href = "index.php?route=checkout/checkout";
Good luck!

replace the redirect function where you already changed with the code below
window.location='index.php?route=checkout/checkout';
with this code, this will redirect to your checkout.
location.href='index.php?route=checkout/checkout';

Related

TypeAhead: error message instead of suggestions data

I am using typeahead library, it's fetching the data successfully. But not loading the data into the suggestions list, instead its showing the unable to find any company that match current query every time.
Here is my code:
$('#js-typeahead').typeahead({
highlight: true,
minLength: 1
}, {
displayKey: ['title'],
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
templates: {
empty: [
'<div class="empty-message">',
'unable to find any company that match current query',
'</div>'
].join('\n'),
suggestion: function(data) {
return '' + data.title + '';
}
}
});
Here is the fetched data
Please tell me what am I doing wrong here.
[SOLVED]: Here is my final code...
$('.js-typeahead').typeahead({
hint: false,
highlight: true,
minLength: 1
}, {
displayKey: 'title',
source: (new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '{{ route("admin.{$parent['route']}.auto-complete") }}',
prepare: function (keywords, settings) {
return $.extend({}, settings, {
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({
keywords: keywords,
_token: '{{ csrf_token() }}'
})
});
}
}
})),
templates: {
empty: '<div class="empty">No result found</div>',
suggestion: function (data) {
return '<div>' + data.title + '</div>';
}
},
}).on('typeahead:asyncrequest', function(event) {
$('.js-typeahead').before('<i class="fas fa-spinner fa-spin loading"></i>');
}).on('typeahead:asyncreceive', function(event) {
$('.js-typeahead').prev('.loading').remove();
}).on('typeahead:selected', function(event, selection) {
// window.location.href = selection.token;
});
I hope this may come in handy for someone...
You're code is practically correct. And the best thing is that you can also get the result without using bloodhound.
from the initial code you state, you are calling it synchronously. thats why it does not yield any result.from typeahead docs. here is the highlight
Expected to be a function with the signature (query, syncResults, asyncResults). syncResults should be called with suggestions computed synchronously and asyncResults should be called with suggestions computed asynchronously (e.g. suggestions that come for an AJAX request)
so your initial code part
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
are running synchronously, and because you are fetching data from ajax, you should make it asynchronously like this (i added asyncresult)
source: function(keywords, result, asyncresult) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
asyncresult($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
hope it helps!

django csrf error in fetch api ajax

I want to replace my jquery ajax code with es6 fetch api under django framework
this is my jquery ajax code
var csrf = $('meta[name="csrf_token"]').attr('value')
//comment vote
$("#comment_box").on('click', "a.vote-up", function() {
var voteID = parseInt(this.id.split("-")[1]);
$.ajax({
url : "/vote_json/",
type : "POST",
dataType: "json",
data : {
"comment_id": voteID,
"vote": $('#up-' + voteID).attr('value'),
csrfmiddlewaretoken: csrf
},
success : function(json) {
$('#up-' + voteID).html('<i class="chevron vote up icon"></i>' + json.vote);
$('#up-' + voteID).popup({
position : 'top center',
content : json.msg,
on : 'manual'
});
$('#up-' + voteID).popup('show');
setTimeout(function (){$('#up-' + voteID).popup('hide');}, 3000);
},
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
and this code is es6 fetch api
let csrf = document.querySelector('meta[name="csrf_token"]').getAttribute('value');
//comment vote
[].forEach.call(document.querySelectorAll('a.vote-up'), function (voteup) {
voteup.addEventListener('click', function () {
let voteid = parseInt(voteid.id.split("-")[1]);
fetch('/vote_json/', {
method: 'POST',
body: JSON.stringify({
comment_id: voteid,
vote: document.querySelector('#up-' + voteid).getAttribute('value'),
csrfmiddlewaretoken: csrf
})
}).then(function (response) {
return response.json();
}).then(function (json) {
document.querySelector('#up-' + voteid).innerHTML = '<i class="chevron vote up icon"></i>' + json.vote
document.querySelector('#up-' + voteid.popup({
position : 'top center',
content : json.msg,
on : 'manual'
}),
document.querySelector('#up-' + voteid).popup('show'),
setTimeout(function () {
document.querySelector('#up-' + voteid).popup('hide'), 3000
})
)
})
})
}
and this code is my view in django
def vote(request):
comment_pk = request.POST.get('comment_id')
vote = request.POST.get('vote')
comment = Comment.objects.get(pk=comment_pk)
if vote == 'true':
comment.up += 1
comment.save()
response_dict = dict(vote=comment.up)
elif vote == 'false':
comment.down -= 1
comment.save()
response_dict = dict(vote=comment.down)
return HttpResponse(json.dumps(response_dict), content_type='application/javascript')
the problem is that in jquery code everything is working but in es6 django responsed "CSRF verification failed. Request aborted." and I tested fetch ajax code in Get method without body block and another django view in this mode works fine
Copy pasted from here.
The solution was in the getCookie() method.
fetch("/graphql", {
method: "POST",
credentials: "same-origin",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
"Accept": "application/json",
'Content-Type': 'application/json'
},
body:JSON.stringify(query)
})
And of course the method has to be on the same page. Taken from Django Docs.
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

redirect after add wishlist in opencart 1.5

I need to redirect to page account/wishlist after I added wishlist without click the popup button in opencart 1.5.
I think I need to add :
$this->redirect($this->url->link('account/wishlist'));
but I don't know where I should put it.
Can somebody help me what should I do with this?
Thanks
If you want to redirect account/wishlist then open your common.js located on catalog/view/javascript and find addToWishList() function.
function addToWishList(product_id) {
$.ajax({
url: 'index.php?route=account/wishlist/add',
type: 'post',
data: 'product_id=' + product_id,
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, .information').remove();
if (json['success']) {
$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
$('#wishlist-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
url = $('base').attr('href') + 'index.php?route=account/wishlist'; // Add this line
location = url; // Add this line
}
}
});
}

Can't get data from model to appear in template Ember.js

My code is here: http://jsfiddle.net/FNn4R/4/ I can't get the outgoings model (a model with messages outbound) to display in the template.
HTML
<script type="text/x-handlebars" data-template-name="messages">
Hello <b>{{App.username}}</b><br />
{{#each outgoings in model}}
<h4>{{outgoings.vehicle_reg}}</h4>
<p>{{outgoings.message_subject}}</p>
{{/each}}
</script>
JS
App.MessagesRoute = Ember.Route.extend({
model: function() {
return App.Outgoings.all();
},
renderTemplate: function() {
this.render('header-messages', {
into: 'application',
outlet: 'header'
});
this.render('messages', {
into: 'application',
outlet: 'content'
});
}
});
App.Outgoings = Ember.Object.extend();
App.Outgoings.reopenClass({
all: function() {
var outgoings = [];
var apiPage = "messages";
var parameters_string = "action=outgoing";
var url = "http://do-web-design.com/clients/carbuddy/index.php/api/";
var url = url + apiPage + "?" + parameters_string + "&username=" + "will" + "&password=" + "1234";
// console.log(url);
var response = $.ajax({
type: "GET",
url: url,
dataType: "text json",
success: function(data){
return data;
// return JSON.parse(data)
alert('Its working'); //It will alert when you ajax call returns successfully.
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' | ' + errorThrown);
}
}).done(function(response) {
response.forEach( function (outgoing) {
outgoings.push( App.Outgoings.create(outgoing) );
});
});
return outgoings;
}
});
My Ajax call is getting data but its just not copying it into the model and or sending it to the template.

Facebook Javascript SDK show value of array

I'm trying to show the tags of a checkin in facebook javascript sdk, but shows only [object Object] because it is an array, I tried several ways to show this array, but could not.
The following code:
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>New JavaScript SDK</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
window.fbAsyncInit = function() {
FB.init({
appId: '274371602680881',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
button.innerHTML = 'Uninstall';
FB.api('/me/checkins', function(response) {
console.log('Got your check-ins: ', response);
if (!response.error) {
//displayCheckIns(response.data, document.getElementById('checkins'));
var markup = '<div class="data-header">Your last five check-ins:</div>';
for (var i=0; i < response.data.length && i < 5; i++) {
var checkin = response.data[i];
//alert(checkin.tags);
//alert(checkin.tags.length);
//alert(checkin.tags.name);
//alert(checkin.tags[0]);
//alert(checkin.tags[0].name);
markup += '<div class="place">'
+ '<div class="picture">Foto: <img src="http://graph.facebook.com/' + checkin.place.id + '/picture"></div>'
+ '<div class="info">'
+ '<div class="from">From: ' + checkin.from.name + '</div>'
+ '<div class="tags">Tags: ' + checkin.tags + '</div>'
+ '<div class="place">Place: ' + checkin.place.name + '</div>'
+ '<div class="place-location">Place Location: ' + checkin.place.location.latitude + ", " + checkin.place.location.longitude + '</div>'
+ '<div class="application">Application: ' + checkin.application.name + '</div>'
+ '<div class="created_time">Created time: ' + checkin.created_time + '</div>'
+ '<div class="likes">Likes: ' + checkin.likes + '</div>'
+ '<div class="check-in-msg">Mensagem: ' + (checkin.message || '') + '</div>'
+ '<div class="comments">Comments: ' + checkin.comments + '</div>'
+ '</div>'
+ '</div>';
}
document.getElementById('user-checkins').innerHTML = markup;
}
});
});
button.onclick = function() {
FB.api({
method: 'auth.revokeAuthorization'
}, function(response) {
window.location.reload();
});
/*
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});*/
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture" style="margin-right:5px"/>' + response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {
scope:'user_status'
});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
});
</script>
</head>
<body>
<div id="fb-root"></div>
<h2>Updated JS SDK example</h2><br />
<div id="user-info"></div>
<div id="user-checkins"></div>
<p><button id="fb-auth">Login</button></p>
</body>
</html>
I tried a few ways, such as:
checkin.tags // shows [object Object]
checkin.tags.length // shows undefined
checkin.tags.name // shows undefined
checkin.tags[0] // shows undefined
checkin.tags[0].name // Can not read property 'name' of undefined
This happens with tags, likes and comments. The others that are NOT array works fine, like "checkin.place.name", and even "checkin.place.location.latitude" brings the correct value.
I did an "console.log(JSON.stringify(checkin.tags));" and it returns:
{"data":[{"id":"100001702765878","name":"Mauricio Forte Neto"},{"id":"100001174670611","name":"Mario Celso"}],"paging":{"next":"https://graph.facebook.com/402127889842448/tags?access_token=AAAD5ih3qDDEBAIo3nB8P3ZCAwXrivw5lunDRAUvkRZCCFZBUy5au3ImicViq80HHVZC29hLDit6QwlZCXZB5WEBkDF3Pp2DrnUGWLrAwhpWddLoliyFDqd&limit=25&offset=25&__after_id=100001174670611"}}
Please, help.
Thanks in advance.
Since it's an object and has data in it, I have to request the data type in it.
What I been missing is to add an ".data" like:
checkin.tags.data[0].name
Now it works!!!