how to use ajax in shopping cart session - node js - javascript

I want to insert and delete products in my shopping cart without refreshing the page. I'm trying to use ajax in my code but I can't understand what I'm doing wrong. For example, this code should insert something in the data field? Please help me in this question
Below it's my ajax code:
$(function() {
$("#cart_id").click(function(e){
e.preventDefault();
var product;
$.ajax({
type: "GET",
data: product,
url: 'http://localhost:8888/add-to-cart-forward/:id',
success: function(response) {
console.log(response);
}
});
});
});
This it's my node JS code
router.get('/add-to-cart-forward/:id', function (req, res, next) {
var cart = new Cart(req.session.cart ? req.session.cart : {});
Product.findById(productId, function (err, product) {
if (err) throw err;
cart.add(product, product.id);
req.session.cart = cart;
console.log(req.session.cart);
res.render('shop/description', product);
});
});

Alredy done. Its work now. Thanks for attention. I didnt change my node js file, only ajax. This is my ajax code.
$(document).on('click','#cart_id',function(e){
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: "GET",
data: id,
url: '/add-to-cart-forward/' + id,
success: function() {
console.log(id)
}
});
});
I just changed some fields and separated "id". I wish somebody can use it

Related

How to get nested JSON data values with a "data-" attribute?

I'm trying to create an elegant way of binding json data to html using data-attributes without having to write a bunch of custom code or using an external library/framework.
I can get this to work just fine without nested data and re-writing my function a little.
The problem is that it's reading my data-api-value as a string..so I'm trying to find the correct way to convert it. I'm open to other suggestions/ work-arounds though.
Here's the code in a (codepen)
Here's a dumb'd down version of the code
function getApiData(apiUrl, callback) {
apiData = $.ajax({
type: 'GET',
url: apiUrl,
dataType: 'json',
success: function(json) {
callback(json.data);
},
error: function(req, err) {
console.log(err);
},
contentType: "application/json; charset=utf-8"
});
}
function dataAPIrealtime() {
const url = 'https://someapi/v1/exchange/getinstrument/bitmex/XBTUSD';
getApiData(url, function(apidata){
$('[data-api]').each(function() {
let api = $(this).data("api");
let value = $(this).data("apiValue");
let data = apidata + value;
if (data || data != data) {
$(this).html(data);
}
});
});
}
/* Run Functions
*********************************/
$(document).ready(function() {
dataAPIrealtime();
setInterval(dataAPIrealtime, 1000); // Refresh data every 1 second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-api="exchange/getinstrument" data-api-value="[instrument][symbol]"></span>

Insert record in mongoDB then update it - Node.Js

I am new to nodeJS and MongoDB
I want to add a record to the database on the javascript event of PageLoad, then during the visit of the user i add values to this object and then update it in the collection depending on an ID i assigned to this record. I am doing it like the following:
Front-end :
document.addEventListener('DOMContentLoaded', async() => {
var ID = function () {
return '_' + Math.random().toString(36).substr(2, 9);
};
jsLibrary.generateObject().then((objectName) => {
objectName.pageLoadTimeStamp = + new Date();
objectName.identifier = ID;
$.ajax({
type:'POST',
url:'/add',
data:JSON.stringify(objectName),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
window.onpagehide = function(){
objectName.PageHideTimeStamp = + new Date();
$.ajax({
type:'POST',
url:'/update',
data:JSON.stringify(objectName),
contentType: "application/json; charset=utf-8",
dataType: "json"
})
};
As you can see i am assigning an ID to an object i'm receiving from a library, then logging the timestamp for pageload and sending it back-end to add it to the database. Then on the event of pageHide I am saving the timestamp of the user leaving the page, and i want to update the record in the collection to re-add it depending on its ID
Back-end: My app.js file
app.post('/add', function(req, res)
{
objName = (req.body);
db.components.insert(objName, function(err,res)
{
if(err){
console.log(err); }
console.log("SUCCESS");
});
});
app.post('/update', function(req, res)
{
objName = (req.body);
db.components.update( { identifier: objName.identifier }, objName, true )
console.log("updated");
});
I get on my console both the values SUCCESS and updated
But when i check the values in my collection; they don't seem to be updated. The pageHideTimeStamp doesn't exist.
The problem is probably with the update, I want to replace the whole record with a new one depending on the ID.
IS there a better practice? Sorry i'm new to this. Thank you
PS: its not practical for me to pass through every parameter i added to this object while updating. There are other parameters I'm adding other than PageHideTimeStamp and there could be more with time
the condition for updating should have only the check you need to apply like it should be ,
let cond = {'id' : '22'} or cond = {'name' : 'sss'} ,
you are using req.body whole object as condition you can try code like this
db.update(condition,data,this.table,function (err,refresh) {
if(err){
//console.log('err controler', refresh)
callback(err, null);
return;
}
//console.log('updated ', refresh)
callback(null,refresh);
});
Use $set for update data
db.components.update( { identifier: objName.identifier }, {$set : objName},function(err,result){
console.log('updated')
})

How to use KnockoutJS to save data into SQL database?

Good day everybody. I have a question about how to use the right way to save data into SQL database through KnockoutJs. The record are display well in the table. It should be able to save the data via this pop-up Modal. But after I click the Create button in that modal, it only pop-up a failed Message. Can anybody please help me to solve this problem? Thank you very much.
Below is extract from main js file about Save function
var data = ko.toJSON(self.Profiles());
$.ajax({
type: 'POST',
url: '/ajaxCall/insertProAjax',
data: "{ Customer:" + ko.utils.stringifyJson(self.Name) + ",customerRemove:" + ko.utils.stringifyJson(self.CustomerRemove) + "}",
contentType: "application/json",
success: function (data) {
alert("Record has been saved Successfully");
MarkCustomerAsSaved();
$('#AddNewModel').modal('hide');
},
error: function () {
alert("Failed");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
Below is extract from the ViewModel about save function
var Customer = {};
Customer.Id = c.Id;
Customer.Name = c.Name;
Customer.Age = c.Age;
Customer.Address = c.Address;
if (isNewRecord === false) {
$.ajax({
type: "PUT",
url: "/api/CustomerAPI/" + c.Id,
data: Customer
})
.done(function (resp) {
self.Message("Record Updated Successfully ");
self.reset();
})
.fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
if (isNewRecord === true) {
isNewRecord = false;
$.ajax({
type: "POST",
url: "/api/CustomerAPI",
data: Customer
})
.done(function (resp) {
self.Message("Record Added Successfully ");
self.reset();
loadData();
}).fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
Knockout and Javascript (in this manner) are being processed client side. You will need to create something on the back end to accept your data payload and save it to the database. If you want to stay in the JavaScript family, I would recommend
node.js. Alternatively this is where php, or C# would come into play.

How can I ajax only html table rows instead of sending the entire form inputs?

I have tried to ajax using post to jsp script my html table rows for weeks now with no success.Can anyone please guide me on this?Below is what I have done so far.
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
$('#notSoCoolGrid > tr').each(function(event) {
event.preventDefault();
var postData = {
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
};
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData.$('input, select').serialize() ,
success: function(msg){
alert("submitted");
}
});
});
});
If I correctly understand your need, you want to transmit the content of your rows, each in the form showed in your current postData.
So this can be made at once for all rows (instead of ajaxing successively each of them).
It might be something like this:
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
event.preventDefault();
var postData = [];
$('#notSoCoolGrid > tr').each(function(event) {
postData.push(
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
);
});
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData,
success: function(msg){
alert("submitted");
}
});
});
});
Note that I choosed (the simplest way, IMO) to make a simple array of rows, where each one is an object like you already structured them.
Last point: I notice you specified async: false.
I don't know why you did that, and so I kept it unchanged.
But note that it's not recommended, and is being on the road to become deprecated.
I finally was able to solve this issue,for that I want to post my answer it might be helpful for someone out there.My previous code was submitting a form before even ajax call being triggered and I have to use Classes instead of IDs to identify my rows.I had to change the code completely to be able to submit the form
$('#btn').click(function(e) {
e.preventDefault();
$('#notSoCoolGrid tr').each(function(i, tr) {
var postData = {
paymentId : $('.paymentId', tr).val(),
id : $('.deald', tr).val(),
pType:$('.pType', tr).val(),
pAmt:$('.pAmt',tr).val(),
currency:$('.currency',tr).val(),
pInvDate:$('.pInvDate',tr).val(),
pRecDate:$('.pRecDate',tr).val(),
comments:$('.comments',tr).val()
}
$.ajax({
async: false,
type: "post",
url: "/update_deal_pmt_script.jsp",
data: postData
})
.done(function(response) {
console.log(response);
})
.fail(function(x, status, error) {
alert("Error: " + error);
});
});
});

Laravel ajax delete request

so here is my delete button
<button class="btn btn-danger btn-xs btn-delete delete" value="{{$post->id}}">Delete</button>
then the ajax request
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "DELETE",
url: "{{route('delete_post')}}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
the route
Route::get('delete_post','PostController#getDeletePost');
then the controller:
public function getDeletePost($post_id)
{
$post = Post::where('id', $post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}
so please help me identfy why nothing really happens when i press the delete button
I have modified you javascript, first issue in your code is,you must either use get request or post request, second issue you are not using named route in order call url for ajax like {{ route() }} , it should be {{ url('path') }} or name your route..
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "get",
url: "{{ url('/') }}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
You are sending a DELETE request type in your Ajax call, which would require a _method parameter with a value of DELETE added to your AJAX data. Your route is a GET route, so that is why you are seeing no action
Another problem is in your blade syntax you are referencing a named route 'delete_post', but that is your URL, not the route name. You have not named the route from what you have posted
Try updating this line in your routes file and that should allow the request to make it to your controller method.
Route::post('delete_post','PostController#getDeletePost')->name('delete_post');
Now you have to change your Ajax request type to
type: "POST"

Categories

Resources