How do I write the AJAX to post data - javascript

Fiddle
I am trying to learn AJAX from a tutorial.
I am able to grab the data I want and populate it in the DOM pretty easily.
What I'm struggling with is using 'POST' to edit it.
I created a simple page that lists 'friends' and 'ages' that pulls that data from here
http://rest.learncode.academy/api/learncode/friends
The names and ages populate correctly, but the code I'm writing to 'POST' to it is not.
Here is my javascript
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/learncode/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
</script>
HTML
<div class="large-12 columns" id="ajaxContainer">
<h1>
AJAX Container
</h1>
<h3>
Friends
</h3>
<ul id="friends">
</ul>
<h3>Add a friend</h3>
<p>
Name:
<input type="text" id="name" />
</p>
<p>
Age:
<input type="text" id="age" />
</p>
<button id="add-order"> submit</button>
</div>

I am guessing as to what you actually want, but it seems that you want the page to populate with whatever friends are currently in the database on first load, and then when you click add-order button, it adds new friends and updates your list. The first thing is that you are trying to POST to the learncode name, which you can't do. Change where it says "yourname" in the URLs below to something else. Here is what you should do:
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
$.ajax({
type: 'POST',
data: {"id":3, "age": $age.val(), "name":$name.val()},
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function () {
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
$friends.html("");
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +'
</li>');
})
},
error: function () {
alert("error loading data");
}
});
},
error: function () {
alert("error loading data");
}
});
});
});
</script>

See the part that says
type : "GET"
-?-
change it to
type : "POST"
Then, the url parameter is what you are POSTing to-
And you are not actually sending any data -!
So, try this:
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'POST',
url: 'http://yourWebsite.com/someScriptToHandleThePost.php',
data: [{"id":1,"name":"Will","age":33},{"id":2,"name":"Laura","age":27}],
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
Then, you're going to need a PHP script to handle the POSTed data and return a response, which gets passed in the data param in success:function(data){}
start out with something simple, like this:
<?php
print_r($_POST);
?>
and change your success function to:
success: function(data) {
$("body").append("<pre>"+data+"</pre>");
}
and that should get you on the right track....

Related

Returning data from asynchronous function through callback comes as undefined

The function gets the data from URL and then passes it to another function where the listing is done dynamically based on users in the list of URL. I tried callback but I am getting the following error service.js:9 Uncaught TypeError: callback is not a function
This is the function in one js file:
function GetData(callback, passdata) {
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/users',
success: function (response) {
debugger;
console.log(response);
return callback(response, passdata);
}
});
}
This is the function in another js file (wherein I want to list the data from the URL):
$(document).ready(function () {
var getData = GetData();
var $data = $('#dataDisplay');
function listData(response, passdata) {
var data = response;
var passeddata = passdata;
$.each(data, function (i, users) {
$data.append('<li>' + '<span>' + users.name + '</span>' + '<br> <span>' + users.email + '</span>' + ' </li>');
});
//adds li dynamically
$("li").append('<i class="material-icons delete">' + "delete" + '</i>');
$("li").append('<i class="material-icons edit">' + "edit" + '</i>');
}
});
You can use anonymous function in document ready =>
GetData(function(result){
// can do further things here..
console.log(result);
}, passdata);
this should fix your error.
For me this worked
function GetData(callback) {
debugger;
$.ajax({
type: 'GET',
url: ' http://localhost:3000/users',
success: function (response) {
console.log(response);
callback(response);
}
});
}
In another js file call the function back and pass the response parameter for that is where the array of the API was saved.
GetData(function (response) {
debugger;
var data = response;
var $data = $('#dataDisplay');
$.each(data, function (i, users) {
$data.append('<li>' + '<span class="table .table-striped .table-hover">' + users.first_name + '</span>' + ' <span class="table .table-striped .table-hover">' + users.email + '</span>' + ' </li>');
});
//adds li dynamically
$("li").append('<i class="material-icons delete ">' + "delete" + '</i>');
$("li").append('<i class="material-icons edit ">' + "edit" + '</i>');
});
});
How can JavaScript know that listData is the callback function if you don't specify it?
You just declared the listData function, but you aren't using it anywhere. There is not any sort of magic that will do it for you :)
Just change
var getData = GetData();
To
var getData = GetData(listData, 'something');

JSON to HTML not rendering into HTML via ID

I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?
thanks.
Script.js:
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
var items = [];
$.each(data, function (key, val) {
items.push('<li id=" ' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
And the JSON:
{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}
My HTML is just an a href that spits out the click ID:
Get JSON
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
<button>Get JSON data</button>
By Using this Method You can Easily get Your JSON value In HTML
Try this one :)
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data){
var html = "<ul>";
items = data.map(function(obj){
html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
});
html += "</ul>";
$('body').append(html);
I would try with some like this
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
// uncomment line below if data is a single JSON
// data = [data]
var items = [];
// we create a list where we will append the items
var list = document.createElement("ul");
data.forEach(function(item){
// we create a list item
var listItem = document.createElement("li");
// we set the attributes
listItem.setAttribute("id", item.id ); // item.id or the property that you need
// we add text to the item
listItem.textContent = item.mesi;
// We append the list item to the list
list.appendChild(listItem);
});
// we append the list to the body
$("body").html(list);
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
Try like this:
success: function(data){
var items = '';
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
for multiple objects
success: function(datas){
var items = '';
$.each(datas, function (i,data) {
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
output
<ul>
<li id=" id">1</li>
<li id=" mesi">mesima 0</li>
<li id=" done_bool">1</li>
<li id=" id">2</li>
<li id=" mesi">mesima 1</li>
.
.
</ul>
Try like this:
$(function() {
$('#clickme').click(function() {
// fetch json file
$.ajax({
url : 'data.json',
dataType : 'json',
// please confirm request type is GET/POST
type : 'GET',
success : function(data) {
// please check logs in browser console
console.log(data);
var ulHtml = "<ul>";
$.each(data, function(key, obj) {
ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
});
ulHtml += "</ul>";
// please check logs in browser console
console.log(ulHtml);
$('body').append(ulHtml);
},
error : function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
alert(textStatus);
}
});
});
});
<button id="clickme">Get JSON data</button>
I log json data and created ul html, Please check logs in browser console
I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
Get JSON
<script>
$(function() {
$('#clickme').click(function() {
//fetch json file
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
// the HTML output for each item
var done = (val.done_bool === '1') ? 'true' : 'false';
items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
</script>
</body>
</html>
data.json
[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]
I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/
Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add
method: 'GET'
to your ajax request. I think this is a big deal in making ajax request.

Javascript breaks after div refresh

I have an ajax function, which submits the data and refreshes the div after the data has been updated. The problem is that the jQuery elements within the div breaks after the form has been submitted, and the div has been refreshed.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit" ,function(){
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function(msg){
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(function() {
$('a[id^="teamname"]').editable({
ajaxOptions : {
type : 'post'
}
});
});
$(document).ready(function() {
$('select[id="swap"]').change(function(){
$( "#saveprogress" ).show("fade");
});
});
You need to use event delegation to support dynamically added elements also you need to initialize the plugin again once the div is refreshed
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit", function () {
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function (msg) {
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission and pass a callback which will initialize the plugins
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh", createEditable);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(createEditable);
function createEditable() {
$('a[id^="teamname"]').editable({
ajaxOptions: {
type: 'post'
}
});
}
$(document).ready(function () {
//use event delegation
$(document).on('change', 'select[id="swap"]', function () {
$("#saveprogress").show("fade");
});
});

How to extract and add the JSON data received as a AJAX response to the HTML select drop down using jQuery?

I've following HTML code :
<select id="student" name="student" class="form-control"></select>
The jQuery-AJAX function I've written for adding the options to the above HTML select control is as follows :
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
From PHP file I've received a big array encoded into JSON format(i.e. the result variable from jQuery-AJAX function). For your reference I'm showing below only the first four records from that array. In HTML select control actually I want to show all the elements from this array.
[{"id":2,"stud_name":"John Dpalma","stud_address1":"277 Eisenhower Pkwy","stud_address2":"","stud_city":"Edison","stud_state":"New Jersey","stud_country":"USA","stud_zipcode":"07039","stud_email":"abc#gmail.com","created_at":1409739580,"updated_at":1410253832},
{"id":3,"stud_name":"Anthony Gonsalvis","stud_address1":"520 Division St","stud_address2":"","stud_city":"Piscataway","stud_state":"NJ","stud_country":"USA","stud_zipcode":"07201","stud_email":"pqr#gmail.com","created_at":1409740530,"updated_at":1410255590},
{"id":4,"stud_name":"James Bond","stud_address1":"6 Harrison Street, 6th Floor","stud_address2":"Ste-2324","stud_city":"New York","stud_state":"NY","stud_country":"USA","stud_zipcode":"10013","stud_email":"xyz#gmail.com","created_at":1409757637,"updated_at":1412263107},
{"id":9,"stud_name":"Mary Jane","stud_address1":"2112 Zeno Place","stud_address2":"CA","stud_city":"Venice","stud_state":"CA","stud_country":"","stud_zipcode":"90291","stud_email":"utp#gmail.com","created_at":1409908569,"updated_at":1410254282}]
In HTML select control I want to set the values in following manner(consider first two records from above array)
<select id="student" name="student" class="form-control">
<option value="">Select Store</option>
<option value="2">John Dpalma, 277 Eisenhower Pkwy, Edison</option>
<option value="3">Anthony Gonsalvis, 520 Division St, Piscataway</option>
</select>
You might have observed from the expected output above that I want to set the value of option as a id from array and the text that I want to display is comprising of stud_name+stud_address1+stud_city
How should I manage this for all the elements from the JSON data in my code?
Also please guide me in showing the loading option into the select control until the response from PHP comes.
Please provide me some help.
success: function(result, success) {
var $select = $('#student');
$.each(result, function (i, option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
$('<option>', {
value: option.id,
text: txt.join(', ')
}).appendTo($select);
});
},
or with $.map (slightly more efficient):
success: function(result, success) {
var options = $.map(result, function (option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
return $('<option>', {
value: option.id,
text: txt.join(', ')
});
});
$('#student').append(options);
},
In PHP file echo the following in a loop:
echo '<option value="">'.$stud_name.', '.$stud_address1.', '.$stud_address2.', '.$stud_city.', '.$stud_state.', '.$stud_country.'</option>';
Then attach this result to the select dropdown with jQuery through the ajax success.
Here is my solution. This checks address 2 and adds it to the options accordingly.
JS code:
for(var i=0;i<result.length;i++){
if(result[i]["stud_address2"]==""){
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', ' +result[i]["stud_city"] +'</option>');}
else{
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', '+ result[i]["stud_address2"]+ ', ' +result[i]["stud_city"] +'</option>');
}
}
Here is a working DEMO
This is exactly what you need!
$(document).ready(function(){
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$.each(result,function(index,item){
$label = item.stud_name +', ' + item.stud_address1 +', ' + item.stud_city;
$('#student').append('<option value="'+ item.id +'">'+ $label +'</option>');
});
},
error: function() {
alert("Error is occured");
}
});
});
It's a matter of iterating over the JSON you receive from the server, creating option tags for each record, then appending them to the select element:
var response = [{"id":2,"stud_name":"John Dpalma" ... }]
$.each(response, function (index, record) {
if (!record.stud_address2){
var stud_address2 = "";
} else {
var stud_address2 = record.stud_address2;
}
$('<option>', {
value: record.id,
text: record.stud_name + ", " + record.stud_address1 + ", " + record.stud_city + ", " + stud_address2
}).appendTo("#student");
});
Demo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
function __highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "ig");
return s.replace(matcher, "<strong>$1</strong>");
}
$(document).ready(
function() {
$("#suggest").autocomplete(
{
source : function(request, response)
{
$.ajax({
url : 'URL',
dataType : 'json',
data : { term : request.term },
success : function(data)
{
//alert(data[0].title);
response($.map(data, function(item) {
//alert(item);
return {
label : __highlight(item.title, request.term),
value : item.title
};
}));
}
});
},
minLength : 3,
select : function(event, ui)
{
if(ui.item){
$(event.target).val(ui.item.value);
}
//submit the form
$(event.target.form).submit();
}
}).keydown(function(e) {
if (e.keyCode === 13)
{
$("#search_form").trigger('submit');
}
}).data("autocomplete")._renderItem = function(ul, item)
{
return $("<li></li>").data("item.autocomplete", item).append(
$("<a></a>").html(item.label)).appendTo(ul);
};
});
</script>

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

Categories

Resources