Adding quantity of products along with add to cart url in magento - magento-1.8

I have the following add to cart button and input field button in magento.I want to add to cart a product using ajax
<input name="qty" type="text" class="input-text qty" id="qty" maxlength="12" value="<?php echo $this->getMinimalQty($_product)== null?1:$this->getMinimalQty($_product) ?>"/></span>
<p><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" link='<?php echo Mage::helper('checkout/cart')->getAddUrl($_product);?>'><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
I want to pass the add to cart url along with quantity of product through ajax. i have tried the following
<script type="text/javascript">
jQuery(document).ready(function($)
{
$('.btn-cart').click(function()
{
var addtocarturl=$(this).attr("link");
alert(addtocarturl);
jQuery.ajax({
type: 'post',
url: addtocarturl,
success: function(response) {
}
});
});
});
Doesnt seem to work...any suggestions?

Related

Why isn't my title being inserted into my database?

I'm trying to insert the title from my input form into my caption column in my database and then display it with the post. The image and delete buttons display, however the title does not.
Here is my route in my server.js:
app.post('/newPost', isLoggedIn, uploads.single('inputFile'), (req, res) => {
console.log('On POST route');
// get an input from user
let file = req.file.path;
console.log(file);
cloudinary.uploader.upload(file, (result) => {
console.log(result);
db.post.create({
caption: req.body.title,
image_url: result.url,
userId: req.body.id
})
// Render result page with image
}).then((post) => res.render('index', { image: result.url }));
})
Here is my newPost.ejs which contains the form:
<div class="postSection">
<form action="/" method="POST" enctype="multipart/form-data">
<input type="title" placeholder="Write a Caption:" id="postText">
<input type="file" name="inputFile" id="inputFile">
<input type="submit" class="btn btn-primary" id="postSubmit" value="Post">
</form>
</div>
And, finally here is my index.ejs page in which it will display:
<div>
<% posts.forEach(function(post) { %>
<h1><%= post.caption %></h1>
<img class="images" width="700px" height="500px" src="<%= post.image_url %>" alt="uploaded image">
<form action="/<%= post.id %>?_method=DELETE" method="POST">
<input id="deleteButton" class="btn-danger" type="submit" value="Remove idea" >
</form>
<br>
<% }) %>
</div>
Can anyone spot why the title isn't being inserted into my database and also why it isn't displaying?
One option to debug is console.log the req.body and search for the text you sent as the title.
I think that the title is in req.body.postText or you should add a name tag to your title input and that will be the name in your req.body.
Let me know if this helps!

I can't change the value in the database - array

I need to update the comment status, i.e. the name of the "approve" field. To this end, I created the AJAX script also the backend seems correct because it receives a message after clicking the button. I don't know why I can't save the "approve" value to the database. Please help. I use NodeJS, MongoDB, Express, and EJS for frontend.
My database:
My frontend:
<% post.comments.forEach(function (comment) { %>
<tr>
<td> <%= comment._id %> </td>
<td> <%= comment.username %> </td>
<td> <%= comment.comment %> </td>
<form method="post" onsubmit="return doApprove(this);">
<input type="hidden" name="post_id" value="<%= post._id %>" />
<input type="hidden" id="comment_id" name="comment_id">
<td> <input class="approve-comment" type="checkbox" name="approve" value="true">
<button class="btn btn-info" value="Approve"/>
</td>
</form>
<% }) %>
</tr>
</table>
</div>
<script>
function doApprove(form) {
var formData= {approve:form.approve.value};
$.ajax({
url: "/do-edit-comment",
method: "POST",
data: formData,
success: function (response) {
formData._id =response._id;
alert(response.text);
}
});
return false;
}
</script>
My backend:
app.post("/do-edit-comment", function (req,res) {
blog.collection("posts").updateOne({
"_id": ObjectId(req.body.id),
"comments._id": ObjectId(req.body.id)
},{
$set: {
"comments": {approve: req.body.approve}
}
}, function (error,document) {
res.send({
text: "comment approved"
});
});
});
To update a single element from an array, what you need is the $[<identifer>] array update operator. For the scenario described in your question, the update query in the server should be something like this:
blog.collection("posts").updateOne(
{ "_id": ObjectId(req.body.post_id), },
{ $set: { "comments.$[comment].approve": req.body.approve } },
{ arrayFilters: [{ "comment._id": ObjectId(req.body.commentId) }] },
function (error, document) {
res.send({
text: "comment approved"
});
}
)
EDIT(Front-end issues/fix)
So I figured there are some issues with the front end code too. This edit attempts to explain/fix those issues.
Issues:
1. The backend expects a commentId in the request object(req.body.commentId) to be able to identify the comment to update but you are not sending that from the front end.
2. The backend needs the id of the post to uniquely identify the post to update, but you are not sending that from the front end.
3. The approve value in the form data sent from the front-end is a string and it would always be "true". This is not what you want, you want to send a boolean value(true or false) depending on if the checkbox is checked or not.
Fix:
Update the form template to this:
<form method="post" onsubmit="return doApprove(event);">
<input type="hidden" name="post_id" value="<%= post._id %>" />
<input type="hidden" id="<%= comment._id %>" name="comment_id" />
<td> <input class="approve-comment" type="checkbox" name="approve" value="true">
<button class="btn btn-info" value="Approve"/>
</td>
</form>
Changes:
- The doApprove handler attached to the submit event of the form is now called with event instead of this.
- I updated the value of the id attribute for the input#name="comment_id" element to the actual comment._id value.
And in the script tag, update the doApprove function to this:
function doApprove(event) {
event.preventDefault();
const form = event.target;
var formData = {
approve: form.approve.checked, // form.approve.checked would be true if the checkbox is checked and false if it isn't
post_id: form.post_id.value, // The value of the input#name=post_id element
commentId: form.comment_id.id, // The id attribute of the input#name=comment_id element
};
$.ajax({
url: "/do-edit-comment",
method: "POST",
data: formData,
success: function (response) {
formData._id =response._id;
alert(response.text);
}
});
return false;
}
I hope that helps.

Clear Search on Semantic-ui

How do I get the selected result of a search field of Semantic-UI?
Using onSelect event, I can get the selected result, but this does not work when clean the field with the backspace.
Using field.search('get result') also not return the result blank as expected.
You can get the selected result like this:
onSelect:function(result){
console.log(result)
}
Having a sample HTML form with 2 inputs like this (one hidden):
<form id="search-box-form">
<input type="hidden" name="search" value="" />
<div class="ui search location-search">
<div class="ui icon input">
<input class="prompt" type="text" placeholder="Search locations..." />
<i class="search icon"></i>
</div>
<div class="results"></div>
</div>
</form>
The same way you use onSelect to populate your hidden field, you can use onResultsClose to clear your hidden input. Caveat: onResultsClose will run before semantic puts the value on it's own field, hence the need to use timeout function.
jQuery(document).ready(
function() {
jQuery('.location-search')
.search({
source : content,
searchOnFocus : true,
minCharacters : 0,
onSelect: function(result, response) {
var value = result.value;
$('#search-box-form').find('input[name=search]').val(value);
},
onResultsClose: function(){
setTimeout(function() {
if (jQuery('.location-search').search('get value') == '') {
$('#search-box-form').find('input[name=search]').val('');
}
}, 500);
}
})
;
}
);

cant make the gmaps.js search functions

i have made this simple app with gmaps.js but i need the search functions like they show it here:
http://hpneo.github.io/gmaps/examples/geocoding.html
i looked at the source code and all but it aint working.. The search button reloads the page...
my code is a follows:
<script>
$('#geocoding_form').submit(function(e){
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
}
}
});
});
</script>
<form method="post" id="geocoding_form">
<label for="address">Address:</label>
<div class="input">
<input type="text" id="address" name="address" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="map"></div>
the rest is loaded in from scripts.js you can see it in sourcecode. Why is this happening and how can i fix this?
The web app is located here, http://travelers.work/trein/
You need to change
map.setCenter(latlng.lat(), latlng.lng());
to
map.setCenter(latlng);
because the search returns a LatLng object as a result, and that's what is needed as an input for setCenter.
Here's a JS demo with your code: http://jsfiddle.net/DuRhR/3/
EDIT after comments:
Alternatively, you can pass to setCenter a LatLngLiteral
map.setCenter({lat: latlng.lat(), lng: latlng.lng()});

Can't update user model in express?

I'm trying to do a put request to update a user model but instead my router just sends another get request.
Here's my router
router.get('/update', isLoggedIn, function(req, res) {
res.render('update.ejs', {
user : req.user // get the user out of session and pass to template
});
});
router.put('/update', function(req, res) {
var username = req.body.username;
var profile_type = req.body.prof_type;
var pic = req.body.profile_pic;
var aboutme = req.body.whoami;
console.log(req.body.whoami);
User.findById(req.params.id,function(err, userup){
if (!userup)
return next(new Error("Couldn't load user"));
else {
userup.username = username;
userup.prof_type = profile_type;
userup.profile_pic = pic;
userup.whoami = aboutme;
userup.save(function(err) {
if (err)
console.log('error on update');
else
console.log('successful update');
});
}
});
res.redirect('/profile');
});
Here's my html input form
<form action="/update" method="put">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username">
</div>
<div class="form-group">
<h2> Pick a type of profile</h2>
<input type="radio" class="form-control" name="prof_type" value="true">Tutor<br>
<input type="radio" class="form-control" name="prof_type" value="false">Student
</div>
<div class="form-group">
<label>Link to profile picture</label>
<input type="text" class="form-control" name="profilepic">
</div>
<div class="form-group">
<label>About me</label>
<textarea name="whoami" class="form-control">Enter text here </textarea>
</div>
<button type="submit" class="btn btn-warning btn-lg">Update</button>
</form>
I've also tried changing them to be /update/:username, however, after I click the update button with the fields, I GET this address
http://localhost:3000/update?username=bob&prof_type=false&profilepic=bob&whoami=bob
Not sure why I'm not updating the model or even why it's not putting. Any help is much appreciated, thanks!
HTML only supports GET and POST requests. See the specification for details:
The method and formmethod content attributes are enumerated attributes
with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET
method. The keyword post, mapping to the state POST, indicating the
HTTP POST method. The invalid value default for these attributes is
the GET state. The missing value default for the method attribute is
also the GET state. (There is no missing value default for the
formmethod attribute.)
You can use the PUT method only with an ajax request. For example in jQuery:
$.ajax({
url: '/update',
type: 'PUT',
success: function(result) {
// Do something with the result
}
});

Resources