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.
Related
I have a dynamically generated select tag and then after that, I have to make an ajax call to query some values and loop thru it and dynamically generate the options tag. But for some reason, I cant append an option tag to my select tag. This is not the issue of asynchronicity right?
const firstElemTd = $('#none td:first-child');
firstElemTd.append(`<select id="the-select"></select>`);
const selectTag = $(`#the-select`);
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
selectTag.append($('<option>', {value: balyu.name}).text(balyu.name));
});
}
});
Create the selectTag as a jQuery object first. You can then append to it.
$(function(){
const $firstElemTd = $('#none td:first-child');
const $selectTag = $('<select></select>');
//append the selectTag to the td
$firstElemTd.append($selectTag);
//now that the selectTag is a distinct jQuery object you can append to it. EG:
var response = [{"name":"a"},{"name":"b"},{"name":"c"}];
$.each(response, function(key, balyu) {
$selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
});
/* The same thing in the ajax response should work too.
(commented out here for the snippet)
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
$selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
});
}
});
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="none"><tr><td></td></table>
You're constructing your $.each incorrectly
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
selectTag.append($('<option></option>',
{value: balyu.name,
text: balyu.name}
));
});
}
});
You could also go with another approach:
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
selectTag.append($('<option></option>'
.val(balyu.name)
.text(balyu.name));
});
}
});
Either way will give you what you're looking for.
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';
}
});
});
My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});
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
Hi I've got a simple question. I've this code below, i use ajax three times in very similiar ways the only things that change are the data passed and the id of the target. Is there a way to group these instructions in a simple one?
Thx
D.
$('#fld_email').focusout(function() {
var request_email = $(this).val();
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=firstname&email="+request_email,
beforeSend: function(){$('#fld_firstname').addClass('ac_loading');},
success: function(msg){$('#fld_firstname').val(msg);$('#fld_firstname').removeClass('ac_loading'); }
});
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=lastname&email="+request_email,
beforeSend: function(){$('#fld_lastname').addClass('ac_loading');},
success: function(msg){$('#fld_lastname').val(msg);$('#fld_lastname').removeClass('ac_loading');}
});
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=phone&email="+request_email,
beforeSend: function(){$('#fld_phone').addClass('ac_loading');},
success: function(msg){$('#fld_phone').val(msg);$('#fld_phone').removeClass('ac_loading');}
});
}
);
try:
$('#fld_email').focusout(function() {
var request_email = $(this).val();
processAjax("fld=firstname&email="+request_email, '#fld_firstname');
processAjax("fld=lastname&email="+request_email, '#fld_lastname');
processAjax("fld=phone&email="+request_email, '#fld_phone');
});
function processAjax(data, id){
$.ajax({type:"GET",
url: "autocomplete.asp",
data: data,
beforeSend: function(){$(id).addClass('ac_loading');},
success: function(msg){$(id).val(msg).removeClass('ac_loading');}
});
}
Use an object and the for control structure:
var fields = {firstname:1, lastname:1, phone:1};
for (field in fields) {
$.ajax({
type:"GET",
url: "autocomplete.asp",
data: "fld=" + field + "&email=" + request_email,
beforeSend: function() {
$('#fld_'+field).addClass('ac_loading');
},
success: function(msg) {
$('#fld'+field).val(msg);
$('#fld'+field).removeClass('ac_loading');
}
});
}