how can without refreshing pull data with ajax in django - javascript

I can post with ajax, but when I want to pull data without refreshing the page, I can only do it 2 times, then the button loses its function.
<div>
<input type="hidden" name="producecode" class="pcode" value="{{per.produceCode}}" />
<input type="hidden" name="useremail" class="uponequantity" value="{{user.username}}" />
<button class="btn btn-sm btn-primary upoq"><i class="fa fa-plus"></i></button></div>
and jquery
$.ajax({
type: "POST",
url: "/uponequantity/",
headers: { "X-CSRFToken": '{{csrf_token}}' },
data: {
"producecode":$(this).parent().find(".pcode").val(),
"useremail":$(".uponequantity").val(),
},
success: function() {
window.location.assign('/basket/'+"?b="+$(".uponequantity").val());
}
});
/*$.ajax({
url:'/baskett/'+"?b="+$(".uponequantity").val(),
headers: { "X-CSRFToken": '{{csrf_token}}' },
type:'POST',
success:function(result){
$('.basket').html(result);
}
});
*/
})

Just add another line to reference your second input same as the first.
$(".up").click(function(){
$(".prdtd").find("input:first- child").attr("value");
$(".pcode").val()
$(".uponequantity").val()//<-- new line for the second hidden value
}
-----------------------------------------
Update:
-----------------------------------------
OP has multiple buttons with the same class each in it's own div and wants to access the values within each div.
So, first off you need to change "pcode" from an id to class in order to get all instances. (id is for unique instances)
After that you need to be able to get the "pcode" & "uponequantity" that are associated with that button and one way of doing that is:
$(".up").click(function(){
$(this).parent().find(".pcode").val()
$(this).parent().find(".uponequantity").val()
}
Simply put, the this keyword references the clicked button.
You then get the direct parent element which would have the button and the hidden values as children.
Finally you get each specific child through the find command and do whatever you want with them.

If I understand your question correctly, you would like to get the value of both inputs in your callback.
It seems like you misspelt pdcode in your JavaScript.
Does the below code snippet help?
$(".up").click(function() {
const value1 = $(".pdcode").val();
const value2 = $(".uponequantity").val();
}

Related

How do I pass Button Value as a variable in Ajax?

I have a problem. I want to exchange certain data using PHP, MySQL and Ajax.
To do this I always have to pass the ID of a field to my backend, so I can continue working with this ID.
How do I pass the value from my button to my URL in Ajax?
What do I have to consider?
row['id'] is my variable (PHP)
HTML Code:
<a class='commentSikayet'>
<button id='commentSikayet' name='commentSikayet' value='{$row['id']}'>
Şikayet et
</button>
</a>
Ajax:
$(document).ready(function () {
$("#commentSikayet").click(function () {
$.ajax({
url: 'report_comment.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('Erfolgreich gemeldet.');
}
});
});
});
Assuming there might be more than one data sets in your page I modified your example to the following snippet. Each buttons has a data-id attribute that identifies the current dataset (the id would be supplied through your PHP script as $row["id"]):
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let data={cmt_id: $(this).data("id"),
value: $(this).prev().val()}
$.post("https://jsonplaceholder.typicode.com/comments",data)
.done(function (result) {
console.log("Erfolgreich gemeldet:",result);
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div><input type="text" value="some text">
<button name="commentSikayet" data-id="123">Şikayet et</button></div>
<div><input type="text" value="some other text">
<button name="commentSikayet" data-id="124">Şikayet et</button></div>
<div><input type="text" value="more text">
<button name="commentSikayet" data-id="125">Şikayet et</button></div>
In your backend PHP script (taking the place of the above typicode-URL) you can pick up the values from the $_POST superglobal as
$_POST["cmt_id"]; // id value
$_POST["value"];. // actual text content
Since you're listening for the click event on the button, you can access it via this in your handler function.
Add the name / value pair to your AJAX data option
$("#commentSikayet").on("click", function (e) {
e.preventDefault();
$.post("report_comment.php", {
bar: $("#bar").val(),
[ this.name ]: this.value // add name / value in here
}).done(function (result) {
alert('Erfolgreich gemeldet.');
});
});
This will include commentSikayet=rowIdValue in the POST request body which you access on the PHP side via...
$rowId = $_POST["commentSikayet"];

How to change a hidden button value

In my project, I use ajaxSubmit to upload file. And i set flUpId init value is "flUpInt".
When i click fulId first time, i can uplode file to linux server with action.php. In action.php, I set $flUpV="flUpChg", and this value return back.
I have tested in success: function(data) that alert(data.flUpV) is "flUpChg", and this value is correct. I use $('#flUpId').val()=data.flUpV; to set the hidden button of flUpId value. So "flUpInt" should be changed to "flUpChg"
When I Click fulId second time, I find flUpId is "flUpInt", it is not "flUpChg".The third time, fourth time...., flUpId is always "flUpInt".
Here is ajax code:
$(function () {
$("#fulId").wrap("<form id='fulfId' action='action.php?act=upFileCsc' method='post' enctype='multipart/form-data'></form>");
$("#fulId").change(function(){
var flUpV=$('#flUpId').val();
alert(flUpV);
$("#fulfId").ajaxSubmit({
dataType:'json',
data:{flUpV:flUpV},
beforeSend: function(){...},
uploadProgress: function(){...},
success: function(data){
$('#flUpId').val()=data.flUpV;
alert(data.flUpV);
},
error:function(xhr){...}
});
});
});
Here is html code:
<input type="file" id="fulId" name="mypic"><input type="hidden" id="flUpId" value="flUpInt" >
To set the value you need to pass it to the ,val() method as a parameter, not use assignment.
So instead of
$('#flUpId').val()=data.flUpV;
use
$('#flUpId').val( data.flUpV );
If the button is hidden you can not change it unless it is controlled by something else, something visible

Newbie to Javascript: how to avoid sending data that have not changed?

I'm a newbie Javascript learner and I want to post serialized data of input checkboxes. The data are sent to the server in order to update the corresponding field in SQL table. Later, the user can review the selections he made the first time and deselect some checkboxes. If I understand well, only the selected items will be sent, not the unselected ones. How can I send all the info I need to update the newly selected items and the newly unselected ones?
The only solution I found is to make 2 updates: the first resets to 0 all the rows and the second one sets to 1 the selected items (newly selected or not) that are sent in the serialized array. Is there a more optimal way to do the job? Ideally, I would update only the data that have changed. Is it possible?
Regards,
Patrick
If I understand it correctly you can filter the checkboxes and then you can add the unselected boxes to the parameters too.
I've found the code for that here at SO. See this question.
The demo below and here a jsfiddle is doing a ajax post only if the user changed the data. Not sure if this is what you want.
(The demo at SO is a bit modified because JSONP is required to get no CORS error.)
var data = "";
$('form').submit(function (evt) {
evt.preventDefault();
//console.log($(this).serialize());
var formData = $(this).serialize();
// source from this SO question https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
.filter(function (idx) {
return $(this).prop('checked') === false
}),
function (idx, el) {
// attach matched element names to the formData with a chosen value.
var emptyVal = "off";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
});
console.log(formData);
if ( data != formData ) { // check if user changed the data.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'POST',
//data: formData, // this will work but for jsfiddle echo the code below is required.
dataType: "jsonp",
data: {
json: JSON.stringify({
serialized: formData
}),
delay: 1
},
success: function(res) {
console.log('posted: ', res);
}
});
}
data = formData;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="first">check1</label>
<input name="first" id="first" type="checkbox" />
<label for="second">check2</label>
<input name="second" id="second" type="checkbox" />
<label for="third">check3</label>
<input name="third" id="third" type="checkbox" />
<label for="fourth">check4</label>
<input name="fourth" id="fourth" type="checkbox" />
<input type="submit" value="update" />
</form>

Take input from html field and store it in JSON object (lots of input fields)

I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code
Javascript/jQuery:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.
jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.
Helpful example: https://stackoverflow.com/a/6960586/4180481

Multiple checkboxes with unique ID's through ajax

I'm working on a website which should be done any time now, but I've got a new task to complete where I need to check check-boxes to simply archive news items. Or "blog posts" if you like.
The idea is to have a check-box on every blog post and if you check that check-box, the post should be archived. (This is in admin mode only).
I need ajax to do the job, but I haven't learned that yet. The PHP part is no problem.
Well the problem really is that I don't know how to pass the unique ID of every check-box, to the JavaScriptfunction and then to the PHP function.
OK, I have a set of blog posts, witch check-boxes, like so:
<div class="news_item">
<input name="checkbox_blog" id="checkbox1" value="1" type="checkbox" />
</div>
<div class="news_item">
<input name="checkbox_blog" id="checkbox2" value="1" type="checkbox" />
</div>
and so on. The Id's are populated from the ID from MySQL.
I have some kind of plugin for ajax checkboxes, but it will only work for one checkbox.
It's basically like this:
$("#checkbox").change(function() {
if($(this).is(":checked")) {
$.ajax({
url: 'admin/archive_it',
type: 'POST'
});
} else {
$.ajax({
url: 'admin/dont_archive_it',
type: 'POST'
});
}
});
Works great on one check-box, but I have no idea how to proceed.
Any tips?
I think it's OK that it uses two different php-scripts for checking and un-checking the blog-posts, it doesn't really matter, I only want it to start working with different check-boxes.
Thanks!
Solution:
I changed the id's to classes, and used Arun P Johny's code:
$('.checkbox_blog').change(function () {
$.ajax({
url: this.checked ? 'admin/archive_it' : 'admin/dont_archive_it',
type: 'POST',
data: {
id: this.value
}
});
});
And because I'm using CodeIgniter, and have the CSRF-security option turned on, I had to add this to the data:
<?=$this->security->get_csrf_token_name()?> : '<?=$this->security->get_csrf_hash()?>',
And now it works perfectly! Thanks all!
There is no need for an ID here, use a class attribute to group the check boxes and give the database id as the value of the checkbox
<div class="news_item">
<input name="checkbox_blog" class="checkbox_blog" value="1" type="checkbox" />
</div>
<div class="news_item">
<input name="checkbox_blog" class="checkbox_blog" value="2" type="checkbox" />
</div>
then in the write change handlers for the .checkbox_blog elements, and pass the id of the database item to to archived or not as a parameter to the server side PHP
$('.checkbox_blog').change(function () {
$.ajax({
url: this.checked ? 'admin/archive_it' : 'admin/dont_archive_it',
type: 'POST',
data: {
id: this.value
}
});
});
you are almost there, except that there were few things which you may need to take care ,like
add a generic class for all the checkboxes, so that the below event handler will work fine for all checkboxes.
there is no need to keep multiple ajax call references, although url is the only differentiator,so i have refined your code and even corrected few things which i noticed .
JS CODE:
$(".checkbox").on('change',function() {
var chkBit=$(this).is(":checked");
var url;
if(chkBit)
tarUrl='admin/archive_it';
else
tarUrl='admin/dont_archive_it';
$.ajax({
url: tarUrl,
type: 'POST',
success:function(){
//when the call is successful do something
}
});
});`
Give all your checkboxes same class and then on change of any checkbox pass the ids of the checkboxes that are selected using the data attribute(probably by iterating over all the checkboxes with the class and collecting the ids of the ones that are checked)
<input name="checkbox_blog" id="checkbox1" value="1" type="checkbox" onClick="YourFunction()" />
<input name="checkbox_blog" id="checkbox2" value="1" type="checkbox" onClick="YourFunction()" />
function YourFunction(){
if($(this).is(":checked")) {
$.ajax({
url: 'admin/archive_it',
type: 'POST'
});
} else {
$.ajax({
url: 'admin/dont_archive_it',
type: 'POST'
});
}
}
if you are dead-set on using id from checkbox, you can pass data like so: (note the change to selector $("input[id^=checkbox]")
$("input[id^=checkbox]").change(function() {
if($(this).is(":checked")) {
$.ajax({
url: 'admin/archive_it',
type: 'POST',
data: {
id: $(this).attr('id').split('checkbox')[1]
}
});
} else {
$.ajax({
url: 'admin/dont_archive_it',
type: 'POST',
data: {
id: $(this).attr('id').split('checkbox')[1]
}
});
}
});

Categories