Jquery not working while process dynamically - javascript

The below code works for me
function gethotelsbydestination(dest_id) {
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
$("#divid").html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
$("#divid").append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
But when i use below code not returns anything.divv is the id of an dropdown passed from php page
function gethotelsbydestination(dest_id, divv) {
var divdrp = "$('#" + divv + "')";
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
divdrp.html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
divdrp.append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
The problem is var divdrp="$('#"+divv+"')";
Any Solution please

You can't concatenate directly. Use this:
divdrp = $('#' + divv);
instead of this:
var divdrp = "$('#" + divv + "')"; // it is not a jquery object

Related

How to prefill fields using jquery

Hi I'm trying to figure out how to fill all fields using ajax call, it successfully doing by selecting category, it loads all related sub_categories.
But sub_sub_category fields are empty. Only when I choose sub_category option it will load all sub_sub_categories, but I want all prefilled once category has been changed. I don't mind to leave like this, but problem is if I have only single sub_category I can not select any sub_sub_category even if they have any I tried to convert to function and call them but no success.
Code below:
<script>
$(document).ready(function() {
get_sub_sub_category();
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if(category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/"+category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="'+ value.id +'">' + value.sub_category_name + '</option>');
});
get_sub_sub_category();
},
})
} else {
alert('danger');
}
});
function get_sub_sub_category() {
$('select[name="sub_category_id"]').on('load change', function () {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/"+sub_category_id,
type: "GET",
dataType: "json",
success: function (data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function (key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
}
});
</script>
You might want to consider the following.
$(function() {
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if (category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/" + category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_category_name + '</option>');
});
$('select[name="sub_category_id"]').trigger("change");
},
})
} else {
alert('danger');
}
});
$('select[name="sub_category_id"]').on('change', function() {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/" + sub_category_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
});
This defined the callbacks for both. For category, when it is changed, it triggers change event on sub-category. This in turn will cascade the loading of the next Select.

How to pass return value in Javascript to the Controller

This is my Javascript code that gets the value from the query string
function getUrlVars() {
var name = [], hash;
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
hash = url[i].split('=');
name.push(hash[0]);
name[hash[0]] = hash[1];
var hid =hash[1];
return pid;
}
}
var hid = getUrlVars()['pid'];
This is my URL: http://localhost:33454/Product?pid=1
[HttpGet]
[Route("api/product/getproducts/{pid}")]
public IActionResult Product(int pid)
{
var selectProducts= (from p in _db.Products
where p.ProductId == pid
select p).ToList();
return Ok(selectProducts);
}
This is my AJAX for printing the list to the html
var $view = $('.table')
$(function () {
$.ajax({
type: 'GET',
url: '/api/product/getproducts/{pid}',
datatype: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});
Are there any issues with my code. Sorry, I know this might be a really simple question to you all. I'm new to programming.
Thanks in advance.
The API URL is not being constructed properly for the AJAX call.
//...code omitted for brevity
var hid = getUrlVars()['pid'];
//...
var $view = $('.table');
$(function () {
$.ajax({
type: 'GET',
url: '/api/product/getproducts/' + hid, //<<<<
datatype: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});
Change your code to this.
[HttpPost]
public IActionResult Product(int pid)
{
var selectProducts= (from p in _db.Products
where p.ProductId == pid
select p).ToList();
return Json(selectProducts, JsonRequestBehavior.AllowGet);
}
And this should be:
Replace {ControllerName} with your controller's name with no curly braces
For example: url: '/Clients/Details'
var $view = $('.table')
$(function () {
$.ajax({
type: 'POST',
url: '/{ControllerName}/Product',
data: JSON.stringify({ pid: hid}),
dataType: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});

Nested ajax call with an value from the first into the seconds Ajax call's url

I want to do live search and I need to use an id value from the first ajax call inside the second one.
I get the info when I type fast into the search, but if I search again or continue, I get this and the outer ajax wont be called again.
GET
http://api.themoviedb.org/3/movie/366924/videos?api_key=KEYHERE…9a6ebe&callback=jQuery1102017797202615180896_1472038138300&_=1472038138301
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val(),
movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
}
})
.then(function() {
$.each(resultArray,
function (index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function () {
$("#myList").append("stuffs");
}
});
});
});
}
$(this).change();
});
Try This -
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val();
var movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
$.each(resultArray,
function(index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function() {
$("#myList").append("stuffs");
}
});
});
}
});
}
$(this).change();
});

Simple ajax request

I am new to ajax and am trying to get the following script working. I just want to take info from a json object and print it to the document.
Here is the JSON file called companyinfo.json:
{
'id':1,
'name':'Stack'
}
The Ajax request looks like this:
ar xhr = false;
var xPos, yPos;
$(function(){
var submitButton = $("#dostuff");
submitButton.onclick = sendInfoRequest;
});
function sendInfoRequest (evt) {
if (evt) {
var company1 = $("#companyInput1").val;
var company2 = $("#companyInput2").val;
}
else {
evt = window.event;
var company = evt.srcElement;
}
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
data: company1,
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
return false;
}
console.log(data.id);
To start simple. I just console.log the data.id to see if the script returned a value from the json file.
To write it to the document I would do something like this, calling the showContents function in the callback function above:
function showContents(companyNumber) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseXML;
$("." + data.companyName.toLowerCase + companyNumber).innerHTML(data.companyName)
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
}
}
I'm pretty new to Ajax, but hopefully that makes some sense. Thanks
if you are trying to get something i think you should add
type:"GET"
on your $.ajax it should look like this.
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
type:"GET",
contentType: "application/json; charset=utf-8",
data: company1, //What is your purpose for adding this?
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
Im not sure about this in your code:
var company1 = $("#companyInput1").val; //should it be with ()??
var company2 = $("#companyInput2").val; //should it be with ()??
should it be with () like this one:
var company1 = $("#companyInput1").val();
var company2 = $("#companyInput2").val();
The easiest way to get and parse JSON is to use $.getJSON
// you need to use a map as your data => {key : value}
$.getJSON("companyinfo.json", {company : company1}, function(data){
console.log(data);
var items = []; // new Array();
$.each(data, function(key, val){
items.push('<li id="' + key + '">' + val + '</li>');
});
// do something with items
});
you can do like this:
$.getJSON("getJson.ashx", { Index: 1 }, function (d) {
alert(d);
});

what is [object Object]?

why instead giving data(value) of database give me the [object Object]?
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
$(".list_name").append('<p>' + data + '</p>');
$('.list_name p a').click( function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
});
results url is:(json_encode()) :
[{"name":"333333"},{"name":"\u0633\u0644"},{"name":"\u0633\u0644\u0627\u0633\u06cc"},{"name":"\u0633\u0644\u0627\u0633\u0633"},{"name":"\u0633\u0644\u0627\u0645"}]
update: full code:
$('.auto_complete').keyup(function () {
var id = '#' + this.id;
var alt = $(id).attr('alt'); var id = $(this).attr('id'); var name = $(this).attr('name');
var url = alt + id + '/' + name;
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
data is not a string, but a JSON object, which is basically a Javascript Object. You access it as you would any JS object/array (looks like your result string is an array)
So you can do something like this: data[1].name
data is a list (It is javascript object).
toString( list ) in javascript gives "object Object"
data[0].name will return "333333"
To make a string from a complex object write your own function.
It looks like your Ajax call is returning an array of structures. Each element in the array is a name-value pair. Given that data is an array, the first element is data[0] so you might do something like:
var firstElem = data[0];
var firstName = firstElem.name;
alert("The first name is: " + firstName);
If you want to add all of the names into your html, you would need to loop through the array, each time appending the current element.
If you wanted to show all names, you could do
var names = "";
for (var i=0; i<data.length; i++) {
var elem = data[i];
names = names + elem.name + ", ";
}
I would rewrite it in the following way
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
}
});

Categories