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);
}
}
});
Related
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>');
});
}
});
});
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
I have a problem, my app have an issue when reading more than one value, when there are two it returns zero.
Example:
I get:
male:
{"name":"alexanderbb10","pic":"ico/nopic.png"}
{"name":"admin","pic":"ico/nopic.png"}
$.ajax({
type: "GET",
url: "http://p********************************/explore.php?usr="+******************+"&what="+strUser,
dataType: "json",
data: dataString,
success: function(data)
{
$('#explorediv').append('<div id="pic" data-bb-type="item" data-bb-img="' + data.pic + '" data-bb-title="' + data.name + '">' + data.name + '</div>').show('fast');
}
});
But it only shows one result.
How can i make sure it shows all results?
The server side is php
wrapper two object in an array
{male: [{"name":"alexanderbb10","pic":"ico/nopic.png"}, {"name":"admin","pic":"ico/nopic.png"}]}
var result = JSON.parse(xhr.responseText);
for (var i = 0, len = result.male.length; i < len; ++i) {
// result.male[i];
}
your is an invalid JSON:
male: {"name":"alexanderbb10","pic":"ico/nopic.png"} {"name":"admin","pic":"ico/nopic.png"}
if returned data from the ajax request is an array of object, like
[
{"name":"alexanderbb10","pic":"ico/nopic.png"}
{"name":"admin","pic":"ico/nopic.png"}
]
for show all the element inseide of the data you must cicle all the array element, try to change the success function like this:
function(data) {
for(var k in data){
$('#explorediv').append('<div id="pic" data-bb-type="item" data-bb-img="' + data[k].pic + '" data-bb-title="' + data.name + '">' + data[k].name + '</div>').show('fast');
}
}
Hi I am getting an error while implementing the following.
When I click on the "save" button in following code:
<td width="20%"> <input id="save" onClick="updateMouseInfo();" type="button" value="Save" /></td>
I want to call the mouse_id parameter from getMouseInfo() function to updateMouseInfo() and I am getting the error that mouse_id is undefined, so please help me with the solution.
function getMouseInfo(mouse_id)
{
var dataString = {auth_token: sessionStorage.auth_token, id: mouse_id};
var mh_url = MH_HOST + '/mice/get_mouse_info.json';
alert("Inside Mouse Get Info");
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
//for (var info_count = 0, info_len = data.length; info_count < info_len; info_count++ );
//{
alert("Inside for loop");
//var mouse_info = data.cage.mice[info_count];
var ear_tag = document.getElementById("ear_tag");
var age = document.getElementById("age");
var genotype = document.getElementById("genotype");
var owner = document.getElementById("owner");
//var born = document.getElementById("born");
//var euthanize = document.getElementById("euthanize");
//var note = document.getElementById("note");
ear_tag.innerHTML = data[0].ear_tag;
age.innerHTML = data[0].age;
genotype.innerHTML = data[0].genotype_id;
owner.innerHTML = data[0].owner_id;
//born.innerHTML = data[0].dob;
//euthanize.innerHTML = data[0].dob;
//note.innerHTML = data[0].dob;
//}
},
error: function (data)
{
alert("fail");
}
});
}
//update mouse info
function updateMouseInfo(mouseid)
{
var ear_tag = $('#input_ear_tag').val();
var age = $('#input_age').val();
var genotype = $('#input_genotype').val();
var owner = $('#input_owner').val();
var dataString = {auth_token: sessionStorage.auth_token, id: mouseid, mouse:
{ear_tag: ear_tag, age: age,}};
var mh_url = MH_HOST + '/mice/update.json';
alert("Inside Mouse update Info");
console.log('Data String='+ dataString.auth_token + 'Mouse id=' + dataString.id);
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
document.getElementById('ear_tag').innerHTML = "<div" + ear_tag + "'>" + ear_tag + "</div>";
document.getElementById('age').innerHTML = "<div" + age + "'>" + age + "</div>";
document.getElementById('genotype').innerHTML = "<div" + genotype + "'>" + genotype + "</div>";
document.getElementById('owner').innerHTML = "<div" + owner + "'>" + owner + "</div>";
},
error: function (data)
{
alert("fail");
}
});
}
I am getting the following error in the browser console.
m_id=99
Data String=pvHxzkr3cys1gEVJRpCDMouse id=undefined
Whereas the id should be 99 in the above case it is showing undefined.
You are calling the updateMouseInfo function in the following manner:
onClick="updateMouseInfo();"
if you want to have same mouseid value which is taken by getMouseInfo() function when you call updateMouseInfo(),you will have to globalize getMouseInfo()
Hope it works.
From the below function I am getting results. Now I want to put that result into a div. So how should I put the result into a div?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: {
action: 'alllist'
},
dataType: 'json',
success: function (msg) {
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
}
}
});
});
You can append the result in to div with the format you like but a simple way of adding would be. You can use append() function to keep the added html with new html for each iteration of loop.
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$('#divId').append("Name: " + uname + "," + "Title: " + vtitle +
"Id: " + vid + "," + "Thumb: " + vthumb + "<br />");
}
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: { action:'alllist'},
dataType: 'json',
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$("#container").html("Username: " + uname + "<br />Video Title: " + vtitle + "<br />Vide ID: " + vid + "<br />Video Thumb: " + vthumb);
}
}});
});
If your div exists:
jQuery('div selector').append(uname+' '+vtitle+...whatever variable and format);
If not
jQuery('element selector to put the div in').append('<div id="aID" class="some classes">'+uname+' '+vtitle+...whatever variable and format...+'</div>');
you can do this:
success: function(msg){
$.each(msg, function(i, item){
$('#divid').html('User Name : '+item.user_name+
'Video title : '+item.video_title+
'Video Id : 'item.video_id+
'Video Thumb : 'item.video_thumb );
});
}