JQuery doesnt work with new inserted data - javascript

My script returns the data (ul list) but JQuery doesnt work with new inserted data.
JQuery
$(".tablecategoryname").on('click', function(){
var $a = $(this).closest('li').attr('id');
var $c = $(this).closest('li');
$.ajax({
type: "POST",
url: "functions.php",
data: {subcategory:$a},
cache: false,
success: function(data)
{
$(data).hide().insertAfter($c).slideDown(400);
}
});
});
Why cant JQuery work with the new items with tablecategoryname class ??

You'll need delegated event handlers with dynamic elements:
$(document).on('click', '.tablecategoryname', function(){
var $c = $(this).closest('li'),
$a = $c.attr('id');
$.ajax({
type: "POST",
url: "functions.php",
data: {subcategory : $a},
cache: false,
success: function(data) {
$(data).hide().insertAfter($c).slideDown(400);
}
});
});
replace document with closest non-dynamic parent!

Related

cart data not update in shopify using ajax

I have a Problem in Shopify.
I want update cart quantity on button click using ajax but it will give error like
{"status":404,"message":"Cart Error","description":"Cannot find variant"}
Here is my ajax code,
$('.adjust-plus').click(function(){
var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');
jQuery.ajax({
type: 'POST',
async: false,
url: '/cart/update.js',
data: { updates: { varient : qty } },
dataType: 'json',
success: function() { location.href = '/cart'; }
});
});
currently in both variable value come so no any error in value.
but when id add code like:
$('.adjust-plus').click(function(){
var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');
jQuery.ajax({
type: 'POST',
async: false,
url: '/cart/update.js',
data: { updates: { 15082896588867 : 2 } },
dataType: 'json',
success: function() { location.href = '/cart'; }
});
});
then cart updated successfully.
Firstly, remove async: false as it's very bad practice and not needed here as you're using the success callback properly.
The issue itself is because you cannot use variables as the keys of an object with the syntax you're using. To get around this you can use bracket notation, like this:
$('.adjust-plus').click(function() {
var $quantity = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity');
var qty = $quantity.val();
var varient = $quantity.data('id');
var data = { updates: {} };
data.updates[varient] = qty;
jQuery.ajax({
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function() {
location.href = '/cart';
}
});
});

Use AJAX response to update select option

This code can fetch data from a database then return it to a select option:
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
$('#bus_type').html(data.type);
}
})
});
The AJAX is successful and returning the JSON but the select option is still returning blank instead of the data coming from AJAX. What am I doing wrong?
Example output of data:
{
"id":"575",
"bus_name":"THIS LOVE",
"type":"RERE",
"address":"SDF"
}
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
// If the option is in the select
$('#bus_type').find('option[value="'+data.id+'"]').prop('selected', true);
// Or if the option is not there yet
var $option = $('<option></option>').html(data.type).attr('value', data.id).prop('selected', true);
$('#bus_type').append($option); // Adds the new option as last option
$('#bus_type').prepend($option); // Adds the new option as first option
}
})
});
Assuming your HTML is:
<select id="bus_type">
<!-- no content yet -->
</select>
and your response is :
{
"id":"575",
"bus_name":"THIS LOVE",
"type":"RERE",
"address":"SDF"
}
Then your success() method would just print the following:
<select id="bus_type">
RERE
</select>
which is not a valid HTML for a <select>.
Your JS should look like this for it to work:
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
$('#bus_type').html("<option value='"+ data.type +"'>"+ data.type +"</option>");
}
})
});
Or like this if you want to preserve the existing options:
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
$('#bus_type').append("<option value='"+ data.type +"'>"+ data.type +"</option>");
}
})
});
The success() method would print the following:
<select id="bus_type">
<option value="RERE">RERE</option>
</select>
If you would provide us some HTML I could edit my answer to your specific needs.

Post files with AJAX + jQuery with input element ID

I am trying to POST form data with AJAX + jQuery using the code below
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
data.append("file_"+i, file_data[i]);
}
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input) {
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
Here submit1 is a button on form form_id
This code is working fine, however the below line
data.append("file_"+i, file_data[i]);
as you can see posts the file with id of file_0, file_1 and so on. How can I get this to be the actual id of the input element rather than being a generic file_0, file_1 etc ?
Thanks for reading this
If you are using jQuery then why not something like this
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
Entire Code :-
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>

jQuery remove element on ajax success

I have <button> with ajax on it, and want to remove it after successful request.
<script type="text/javascript">
$(".approve").click(function(){
var el, image_id = $(this).data('image-id');
$.ajax({
type: "PATCH",
dataType: "json",
data: { "approved": "True"},
url: "/ml/api/image/" + image_id + "/?format=json",
success: function(data){
$(this).remove();
}
});
});
</script>
But this doesn't work…
The context in the success callback is different from the context of the click event meaning this no longer refers to the button DOM element. Just select the button again and it would remove it:
$(".approve").click(function(){
var el = $(this), image_id = $(this).data('image-id');
$.ajax({
type: "PATCH",
dataType: "json",
data: { "approved": "True"},
url: "/ml/api/image/" + image_id + "/?format=json",
success: function(data){
el.remove();
}
});
});
Another way is to pass context property to ajax:
$(".approve").click(function(){
var image_id = $(this).data('image-id');
$.ajax({
context: this,
type: "PATCH",
dataType: "json",
data: { "approved": "True"},
url: "/ml/api/image/" + image_id + "/?format=json",
success: function(data){
$(this).remove();
}
});
});
This is my methode. Easy.
var element = $(this);
$.ajax({
success: function(){
element.remove();
}
});

Ajax post method not working

I am currently creating a website and am having trouble using AJAX to post my data. I have a button and when clicked the following code is processed...
var name = document.getElementById('name').innerHTML;
var text = document.getElementById('text').innerHTML;
$.ajax({
type: "POST",
url: "php/post.php",
data: { postName: name, postText: text},
success: function() {
$('#paragraph').html("worked");
}
});
This definitely opens the post.php page but it is not passing through the desired data. Am I doing something wrong?
Thanks in advance
What do the variables name and text contain? Rather than doing
var name = document.getElementById('name').innerHTML;
var text = document.getElementById('text').innerHTML;
You can do:
var name = $("#name").val();
var text = $("#text").val();
You may need to pass the datatype object too:
$.ajax({
type: "POST",
url: "php/post.php",
data: { postName: name, postText: text},
dataType: "json",
success: function() {
$('#paragraph').html("worked");
}
});
var name = $('#name').text();
var text = $('#text').text();
$.ajax({
type: "POST",
url: "php/post.php",
data: { postName: name, postText: text},
dataType: 'json',
success: function() {
$('#paragraph').html("worked");
}
});
I guess you are not preventing the default button click behaviour. Probably you should use the preventDefault function on the button click to stop processing the default form posting. Also make sure you have the content present inside your form elements with the Id name and text
$(function(){
$("#yourButtonId").click(function(e){
{
e.preventDefault();
var name = $('#name').html();
var text = $('#text').html();
if(name!="")
{
$.ajax({
type: "POST",
url: "php/post.php",
data: { postName: name, postText: text},
success: function() {
$('#paragraph').html("worked");
}
});
}
else
{
alert("Why should i do ajax when content is empty!");
}
});
});
var name = document.getElementById('name').value,
text = document.getElementById('text').value,
postData = JSON.stringify({ postName: name, postText: text});
$.ajax({
type: "POST",
url: "php/post.php",
data: postData,
success: function() {
$('#paragraph').html("worked");
}
});
You will need to include a reference to json2.js for this to work in older browsers. You can download it here : https://github.com/douglascrockford/JSON-js

Categories