How to bind AJAX method's result value with html.? - ajax

AJAX method
Now , I want the count variable to bind with html and need help as i don't have enough knowledge of AJAX
$.ajaxSetup({
beforeSend: function (xhr) {
var token = localStorage.getItem('ngStorage-premier_agent_token')
var value = 'Bearer ' + JSON.parse(token)
xhr.setRequestHeader('Authorization', value);
}
});
$.ajax({
url: "/api/activity/listcount",
type: "GET",
success: function (data) {
console.log(JSON.stringify(data))
var count=data.count;
}
});

added a container where you want to print your HTML, like a div
<div></div>
and then append the result to that div on your success function
$.ajax({
url: "/api/activity/listcount",
type: "GET",
success: function (data) {
console.log(JSON.stringify(data))
$("div").append("result is" + data.count);
}
});

Related

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Cant access spotify object

i want to display the albums of an artist that i passed from my api controller
the request is here.
I can access the info object, but when i access the albums object it returns undefined
<script>
$(function () {
$('table tr').click(function () {
var id = this.id;
$.ajax({
type: "GET",
url: '/api/author/GetName/' + id,
contentType: "text/plain charset-utf-8",
data: id,
dataType: "json",
success: function (data) {
getDetails(data.name);
}
});
}
);
});//End ready
function getDetails(art) {
$.ajax({
type: "GET",
url: 'http://ws.spotify.com/search/1/track.json?q='+ art ,
dataType: 'json',
success: function (data) {
$('#summaryDisplay').empty();
$('#summaryDisplay').append((JSON.stringify(data.albums)) + '<br/>');
alert(JSON.stringify(data.info));
},
error: function (data) {
$('#summaryDisplay').html('<h3>Error in retrieval</h3>');
}
});
}
You are accessing the wrong URL in your code. Use album instead of track.
{
// [...]
url: 'http://ws.spotify.com/search/1/album.json?q='+ art,
// [...]
}

Parameter is not passing by ajax call

I have an ajax call to a function in my controller. I need to pass a parameter to that function but it is not happening. My ajax call:
$("#BTN_Plus").click(function () {
var CurrentPage = #Model.CurrentPage;
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify(CurrentPage),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
});
The function in my controller:
public PartialViewResult ListerIncidentsHotline( int page = 1)
{
int NextPage = 1 + page;
const int PageSize = 10;
int NumDossier = StructureData.DonneNumDossier((string)Session["Utilisateur"], (string)Session["MotDePasse"]);
IEnumerable<IncidentHotline> ListeIncidents = StructureData.DonneIncidentsHotline(NumDossier);
int NbreIncidents = StructureData.DonneNombreIncidents(NumDossier);
ViewBag.NombreIncidents = NbreIncidents;
var viewModel = new IncidentsPageInfo()
{
NumPages = (int)Math.Ceiling((double)ListeIncidents.Count() / PageSize),
CurrentPage = NextPage,
PageSize = PageSize,
Incidents = ListeIncidents.Skip((NextPage - 1) * PageSize).Take(PageSize),
};
return this.PartialView(viewModel);
}
When I make an alert of the variable CurrentPage, it shows me the right value, but when it comes to the ajax call, i get an error saying that the parameter is null. Can't figure out what's wrong with that.
well as a data you need to pass a numerable value with the name of page, change your ajax data
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify(CurrentPage),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
change data to data: {page: CurrentPage}
This is much easier....
$.get("/Accueil/ListerIncidentsHotline", { CurrentPage: #Model.CurrentPage } ).
done(function (data) {
$("#Affichage").html(data);
});
Obviously the problem came out of my ajax call. So I have to concatenate the name of the parameter with its value inside the method JSON.Stringify, as below:
$("#BTN_Plus").click(function () {
var CurrentPage = #Model.CurrentPage;
alert(CurrentPage);
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify({ page: CurrentPage }),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
});

display values returned by json

I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.

using success event ofjquery / ajax to fill and set dropdownlist value

i have a Ajax request to Fill an edit form like..
function FillLiveDetail(event, LiveID)
{
$.ajax
({
type: "POST",
url: MyUrl + '/GetLiveDetail',
data: '{LiveID: "' + LiveID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
var LiveDetail = data.d;
$('#ClassName').val(LiveDetail[0].Title);
$('#ClassDesc').val(LiveDetail[0].Desc);
$('#SearchKey').val(LiveDetail[0].Keys);
$('#Date').val(LiveDetail[0].Date);
$('#Hour').val(LiveDetail[0].Hours);
$('#Minute').val(LiveDetail[0].Minuts);
$('#AM_PM').val(LiveDetail[0].AmPm);
$('#Duration').val(LiveDetail[0].Duration);
$('#rdbLivePrivacy).prop('checked',true);
CategoryList(event, 'MyddlCategory');
$('#MyddlCategory').val(LiveDetail[0].CategoryID);
}
});
}
function CategoryList(event, ddl_Category_ID)
{
var ddl_Category = $('#'+ddl_Category_ID);
event = event || window.event || e.srcElement;
event.preventDefault();
$.ajax
({
type: "POST",
url: ServiceUrl +'/FillAllCategories',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
var MyCategoryList = data.d;
$(ddl_Category).html('<option value="0" selected="selected">All Category</option>');
for(var m=0; m<MyCategoryList.length; m++)
{
var row = ['<option value="'+MyCategoryList[m].CategoryID+'">'+MyCategoryList[m].CategoryName+'</option>'].join('\n');
$(ddl_Category).append(row);
}
}
});
}
My problem is, I can not change the definition of my function CategoryList() because i used it at many places in my project...
In this context the success: event of CategoryList() function Fire when success: event of FillLiveDetail() function completes that is why i am unable to set the value of MyddlCategory...
please suggest me any thing that may work..
Close the selector quote in this line $('#rdbLivePrivacy').prop('checked',true);
Try setting async property of ajax call to false
$.ajax
({
type: "POST",
async: false,
url: ServiceUrl +'/FillAllCategories',
...

Resources