ajax webapi call returns undefined - javascript

I am following some online ajax tutorials, the example is about calling a webapi using GET method, here is the script section on the page
<script type="text/javascript">
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
$.ajax({
type: 'GET',
url: "http://localhost:35468/api/employee",
dataType: 'json',
async: true,
success: function (data) {
ulEmployees.empty();
$.each(data, function (index, value) {
var fullName = value.FirstName + ' ' + value.LastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
}
});
});
$('#btnClear').click(function () {
ulEmployees.empty();
});
});
</script>
It should render the emoloyee first and last name within a list item in the .
<div>
<input id="btn" type="button" value="Get All Employees" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees">
</ul>
</div>
the each function iterates the on the object but it displays undefined in the html
does anyone know a solution to this ?

Solved
the problem was because the field names FirstName and LastName was incorrect,
correct field names are firstName and lastName thats why the object was not populating them in a correct manner.

Related

AJAX not sending current value of selected option

php code
<?php
if(isset($_POST['data'])) {
$file_handle = fopen('my_file.json', 'w');
fwrite($file_handle, json_encode($_POST['data']));
fclose($file_handle);
}
?>
html
<h1 id="title" class="text-lg-center text-md-center text-sm-left mb-4">test
title</h1>
<p class="lead text-lg-center text-md-center text-sm-left mb-4">test
content</p>
<button id="test" type="button" class="btn btn-lg btn-block btn-outline-
success">Publish List</button>
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="selectfont">
</select>
</div>
javascript
$(function () {
var font = 0;
var font_names = ["Montez","Lobster","Josefin Sans"];
$.each(font_names , function (index , value) {
$('<option />' , {
'value' : index,
'text' : value
})
.css({'font-family' : font_names[index]})
.appendTo("#selectfont");
});
$("#selectfont").change(function () {
var font = $(this).val();
$("p").css('font-family' , font_names[font]);
});
var htmldata = {
'content_font_type': font_names[font],
'content_font_size': parseFloat($("title").css('font-size'))
};
$("#test").click( function(){
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});
});
so what i want to ask is why in my_file.json the content_font_type and content_font_size not changing, but when i use alert() function in $("#selectfont").change it show correctly. Also, success always return empty when i use console.log and alert()
You have two problems:
When #selectfont changes, you're setting a local variable font, not the global variable, because you re-declare it with var font. Get rid of the var keyword.
You're setting htmldata when the page first loads. You need to set it when the user clicks on the button, so you get the updated values.
You don't really need the font variable at all. You can get the value of #selectfont when you're setting htmldata.
$("#test").click( function(){
var htmldata = {
'content_font_type': font_names[$("#selectfont").val()],
'content_font_size': parseFloat($("title").css('font-size'))
};
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});

Retrieving data from json File

I have a JSON file called person.json. JSON file is in the data folder.
This is the JSON data:
{
"name": "Goa Wei",
"age": 31,
"phone": "202-555-0104",
"group": 3
}
I have the html code to display information in a div class called containerDatadump when clicking on <input id="get" type="submit" value="Get"></input>. I have written the following Javascript code.
var container = $("div.containerDatadump");
$(document).ready(function () {
$("input#get").click(function () {
$.ajax({
type: "GET",
url: "data/person.json",
dataType: "json",
success: function (data) {
$.each(data, function (index, item) {
$.each(item, function (key, value) {
container.append(key + " :" + value + "</br>");
});
container.append("<br/></br>");
});
}
});
});
});
I have done this. I try my best to debug the problem but couldn't succeed.
Can anyone help me figure out what is wrong with my code? It would really help me.
My answer looks like that of forgo but i think you can improve you code a little bit by using $.getJSON instead of a regular ajax call.
$.getJSON is a shorthand ajax call for (more info):
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
I also used JSON Generator for the data (LINK) to prevent browser issues.
Your code is a much cleaner this way (in my opinion).
$(document).ready(function () {
var container = $(".containerDatadump");
$("#get").click(function () {
$.getJSON("https://www.json-generator.com/api/json/get/ceoSrTPote?indent=2", function(data){
$.each( data, function( key, val ) {
container.append(key + " :" + val + "</br>");
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="containerDatadump"></div>
<input id="get" type="submit" value="Get"></input>
I think the biggest problem is that you defined your container outside of your $(document).ready function. This means that your markup doesn't exist yet to properly get a handle on your containerDatadump class.
I made a temporary JSON file hosted on a remote server using this JSON Generator tool to test. Otherwise, I run into CORS issues in my browser.
{
"phone": "202-555-0104",
"age": 31,
"group": 3,
"name": "Goa Wei"
}
With this data, I have modified your function to simplify the loop in your ajax success handler, and I have placed the container variable assignment inside the ready function so that it works properly:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var container = $("div.containerDatadump");
$("input#get").click(function() {
$.ajax({
type: "GET",
url: "http://www.json-generator.com/api/json/get/bOxnwzyhIO?indent=2",
dataType: "json",
success: function(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key + " -> " + data[key]);
container.append("<div>" + key + " :" + data[key] + "</div><br/>");
}
}
}
});
});
});
</script>
</head>
<body>
<input id="get" type="submit" value="Get"></input>
<div class="containerDatadump" />
</body>
</html>

Table data is disappearing using jQuery

I want to populate a table with PHP script data using jQuery. I am trying as
<script type="text/javascript" src="js/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"done":1,
"searchDat" : searchDat,
},
success: function(data){
//alert( JSON.parse(data));
var array = JSON.parse(data);
var trHTML = '';
$.each(array, function(ind,value) {
console.log(value);
trHTML += '<tr><td>' + value + '</td><td>' + value+ '</td></tr>';
});
$('#Table').append(trHTML);
}
});
});
});
</script>
HTML
<table id="Table">
<tbody>
<tr><td>ID</td></tr>
<tr><td>ID2</td></tr>
</tbody>
</table>
Button
<form>
<input type="submit" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
</form>
The problem is that the table is populated for 1 second and then disappears in the webpage. What am I doing wrong?
Edit 1
<script type="text/javascript">
$("form").on('submit', function(e){
e.preventDefault();
$.ajax({
url: "http://localhost/bbcprg/getPrograms.php",
type:"POST",
data: {
"done": 1,
},
success: function(data){
//alert( JSON.parse(data));
var arrayData = JSON.parse(data);
var trHTML = '';
$.each(arrayData, function(ind,value) {
console.log(value);
trHTML += '<tr><td>' + value + '</td><td>' + value+ '</td></tr>';
});
$('#Table').append(trHTML);
}
});
});
</script>
The issue is because you've attached the event to the click of the button. This means that while your AJAX request works, the form is still being submit, and hence the page gets refreshed.
To fix this, hook to the submit event of the form instead, and call preventDefault() on the event passed to the handler. Try this:
$("form").on('submit', function(e){
e.preventDefault();
$.ajax({
url: "http://localhost/test.php",
type:"POST",
data: {
done: 1,
searchDat: searchDat,
},
dataType: 'json',
success: function(data) {
var html = data.map(d => '<tr><td>' + d + '</td><td>' + d + '</td></tr>').join('');
$('#Table tbody').append(html);
}
});
});
Also note that you can simplify the logic which builds the HTML to append by using map() on the data array. You also don't need to manually call JSON.parse() if you specify the correct dataType on the $.ajax request. I've also assumed that searchDat is defined outside the function.
Finally I'd suggest you place an id on the form to make the selector less generic, and also you should move the inline style rules in to an external stylesheet.
change
<input type="submit" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
to this
<input type="button" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>

ajax form submits blank description to only first ids

I have below code for submitting the form with ajax but only first instances out of 5 comment box are being submitted for balance I am getting discription=" and also being inserted to the wrong id. here is my code and live example. I want to allow users to comment on any items
http://way2enjoy.com/app/jokestest-991-1.php
$output .='<div id="'.$idd.'" align="left" class="messagelove_box" ><div class="content_box_1">
<div class="content_box_2z"><sup class="joke_icon"></sup></div>
<div class="content_box_3_title"></div>
<div class="content_box_3_text">'.nl2br($cont).'</div>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr(\'action\');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden'. $idd.'").value;
$.ajax({
url: url,
data:{
\'action\':\'addComment\',
\'comment\':comment,
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
\'action\':\'getLastComment\',
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
$(\'#jokes_comment\').val("");
console.log(result[0].description);
$("#header ul").append(\'<li>\'+result[0].description+\'</li>\');
},
error: function(){
alert(\'failure\');
}
});
},
error: function(){
alert(\'failure\');
}
});
return false;
}
</script>
<div id="header" class="content_box_31_text"><ul id="commentlist" class="justList">'.$contpp.'</ul></div>
<form method="post" action="check/process2.php" class="button-1" onSubmit="return ajaxSubmit(this);"><input type="hidden" value="'. $idd.'" id="joke_id_hidden'. $idd.'"><input type="text" id="jokes_comment" value="" name="jokes_comment">
<input type="submit" value="comment"></form>
</div></div>
';
The code posted doesn't tell the full story, but looking at the URL mentioned does. The snippet you've posted is being repeated over and over again, identically in the page. That means that each definition of the ajaxSubmit function overwrites the previous one, and that you have multiple input elements all with the same id. No wonder the page is confused as to what to do. You only need one submit function, if it's written properly it can handle all the different comment inputs. And your comment inputs can't have the same id each time, but they can have the same CSS class, and since they are all within the form, when we submit a specific form, we know the context we are working in, and jQuery can automatically find all the fields in the form for us, without us having to write code to access them all individually.
So..with that design in mind, define your javascript like this, and make sure it only gets rendered once in your entire page output. I've re-written it slightly to take advantage of the easier syntax provided by jQuery.
$(".comment-form").submit(function(event) {
event.preventDefault(); //prevent the default postback behaviour
var form = $(this);
var jokeID = form.find(".joke_id").val();
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data: $(this).serialize(), //automatically finds all the form fields and puts the data in postback-friendly format
success: function(result) {
//I'm not convinced you need this second ajax call - can't you just write the contents of the input box directly into the list? But I'll leave it here in case you want it
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data:{
"action":"getLastComment",
"joke_id": jokeID
},
success: function(result) {
form.find(".jokes_comment").val("");
$("#header-" + jokeID + " ul").append("<li>" + result[0].description + "</li>");
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
});
Secondly, make the PHP that generates the comment markup for each joke look like this:
<div id="header-'.$idd.'" class="content_box_31_text">
<ul id="commentlist" class="justList">'.$contpp.'</ul>
</div>
<form method="post" action="check/process2.php" class="button-1 comment-form">
<input type="hidden" value="'. $idd.'" name="joke_id"/>
<input type="hidden" value="addComment" name="action" />
<input type="text" class="jokes_comment" value="" name="comment" />
<input type="submit" value="comment">
</form>

How to send multiple variables through ajax?

The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});

Categories