Ajax call returns undefined in html


#1

Hi guys, another question please. So i am making my AJAX call and all. It seems successful and all cos the array prints to the console. But when i check the elements that the information should be appended to, they return undefined. Here is my code

<div class="page" data-page="page-contact">
<div class="page-content">
	<div style="text-align: right;padding:20px;">
        <a href="#" onclick="onClickContactEdit({{contact['id']}})">Edit</a>  &nbsp;
        <a href="#" onclick="onDeleteContact({{contact['id']}})">Delete</a>                  
	</div>
	<div id='mnu_contact'>
		<div id="ul_sub_menu">
	</div>    	
</div>
$('#mnu_contact').on('click', function () {
curSelPage = "contacts";
$('#nav_title').text('Contacts');
showMainMenu(false);
$.get( SERVER_URL+'/contacts.json', function(r_data) {
    var contacts = r_data;
    console.log(contacts);
    for (i in contacts) {
       $('#ul_sub_menu').append('<li><a href="#" class="item-link" onclick="selContact('+contacts[i]['id']+')"><div class="item-content">'+contacts[i]['name']+'</div></a></li>');
    } 
});    

});


#2

@nolimits4web @Frooplet @rapgithub help please


#3

I think it is not

contacts[i][‘id’]

but

I[‘id’] and i[‘name’]

Maybe add a console.info inside the for loop


#4

i assume you mean something like this

('+contacts['id']['name']+')

Well i inputed that and the console hit me with cannot read property ‘name’ of undefined. How about i bring the json format forward


#5

Provide more details, full page code and that page route, and all the related scripts


#6

Here is the full app.js code with the routes. The code i inherited is a version 1.6
var SERVER_URL = “http://localhost:65534”;

var myApp = new Framework7({
template7Pages: true,
precompileTemplates: true, //
domCache: true,
template7Data: {
context: {“title”:“Pizza”,“description”:“description data-context-name”},
},
preprocess: function (content, url, next) {
next(content);
}
});

// Export selectors engine
var $$ = Dom7;

// Add main view
var mainView = myApp.addView(’.view-main’);

var curSelPage = “”;
var curContactID;
var curConvArray;

// Just just do reload on app load
// mainView.router.load({reload: true, url: ‘index.html’});

$(’.login-screen #btn_signin’).on(‘click’, function () {
var f_data = {
email: $(’#txt_email’).val(),
password: $(’#txt_password’).val()
}

$.ajax({
      url: SERVER_URL+'/sessions',
      data: f_data,
      cache: false,
      dataType: 'json',
      type: 'POST',
      crossDomain : true,
      xhrFields: {
          withCredentials: false
      },
      success: function(r_data){
        if(r_data['success']==true) {
          console.log(r_data['user']['email']);
          curContactID = r_data['user']['id'];
          myApp.closeModal('.login-screen');
        }
        else {
          alert("Login info incorrect!")
        }
      },
      error: function(error){
        console.log(error);
        alert("Error. Login failed.");
      }
});

});

$(’#mnu_call’).on(‘click’, function () {
curSelPage = “cur_call”;
// Get current call
$.get( SERVER_URL+’/current_call.json’, function(r_data) {
var call;
if(r_data==null)
call = null;
else if (r_data[‘statuses’].last[‘status’] == ‘in-progress’)
call = r_data;
mainView.router.load({
url: ‘pages/cur_call.html’,
context: {
callinfo: call
}
})
});

$('#nav_title').text('Current Call');

});

$(’#mnu_conv’).on(‘click’, function () {
curSelPage = “conversations”;
$(’#nav_title’).text(‘Conversations’);
showMainMenu(false);
//show conversation list
$.get( SERVER_URL+’/conversations.json’, function(r_data) {
var convs = r_data;
curConvArray = convs;
for (i in convs) {
$(’#ul_sub_menu’).append(’

  • ’+convs[i][‘item_type’]+’
  • ’);
    }
    });

    });

    //contacts
    $(’#mnu_contact’).on(‘click’, function () {
    curSelPage = “contacts”;
    $(’#nav_title’).text(‘Contacts’);
    showMainMenu(false);
    $.get( SERVER_URL+’/contacts.json’, function(r_data) {
    var contacts = r_data;
    console.log(contacts);
    for (i in contacts) {
    $(’#ul_sub_menu’).append(’



  • ‘+contacts[i][‘name_full’]+’


  • ');
    }
    });

    });

    $(’#mnu_setting’).on(‘click’, function () {
    curSelPage = “settings”;
    $(’#nav_title’).text(‘Settings’);
    mainView.router.load({
    url: ‘pages/settings.html’,
    context: {
    }
    })
    });

    function selContact(contact_id) {
    $.get( SERVER_URL+’/contacts/’+contact_id+’.json’, function(r_data) {
    var contact = r_data;

        mainView.router.load({ 
            reload: true, 
            reloadPrevious: false,
            url: 'pages/contacts.html', 
            context: {"contact":contact},
        });
    });  
    

    }

    function selConversation(conv_id, sel_i) {
    //Get conversation info;
    var convinfo = curConvArray[sel_i];
    mainView.router.load({
    reload: true,
    reloadPrevious: false,
    url: ‘pages/conversations.html’,
    context: {“convinfo”:convinfo},
    });

    }

    function showMainMenu(main_flag) {
    if(main_flag) {
    $(’#div_sub_menu’).hide();
    $(’#ul_sub_menu’).empty();
    $(’#main_menu’).show();
    }
    else {
    $(’#div_sub_menu’).show();
    $(’#ul_sub_menu’).empty();
    $(’#main_menu’).hide();
    }
    }

    function onClickAdd() {
    if(curSelPage==“contacts”) {
    mainView.router.load({
    url: ‘pages/’+curSelPage+’_edit.html’,
    context: {contact:[]}
    })
    }
    }

    function onClickContactEdit(contact_id) {
    $.get( SERVER_URL+’/contacts/’+contact_id+’.json’, function(r_data) {
    var contact = r_data;

        mainView.router.load({ 
            reload: true, 
            reloadPrevious: false,
            url: 'pages/contacts_edit.html', 
            context: {"contact":contact},
        });
    });  
    

    }

    function onUpdateContact(contact_id) {
    var f_data = {
    name: $(’#txt_contact_name’).val(),
    company: $(’#txt_contact_company’).val(),
    customer: ‘t’
    }

    var url = "/contacts";
    //update contact
    if(contact_id) {
        url = "/contacts/"+contact_id;
    }
    
    $.ajax({
          url: SERVER_URL + url,
          data: f_data,
          cache: false,
          dataType: 'json',
          type: 'POST',
          crossDomain : true,
          success: function(r_data){
            console.log(r_data);
    
            if(r_data['success']==true) {
                mainView.router.load({ 
                    reload: true, 
                    reloadPrevious: false,
                    url: 'pages/contacts.html', 
                    context: {"contact":r_data['contact']},
                });
            }
            else {
              alert("Update info failed!")
            }
          },
          error: function(error){
            console.log(error);
            alert("Error. Update failed.");
          }
    });    
    

    }

    function onDeleteContact(contact_id) {
    if (confirm(‘Are you sure you want to delete this?’)) {
    $.ajax({
    url: SERVER_URL + ‘/contacts/’+contact_id,
    cache: false,
    dataType: ‘json’,
    type: ‘DELETE’,
    crossDomain : true,
    success: function(r_data){
    console.log(r_data);

                if(r_data['success']==true) {
                    mainView.router.load({ 
                        reload: true, 
                        reloadPrevious: false,
                        url: 'pages/profile.html', 
                        context: {},
                    });
                }
                else {
                  alert("Delete info failed!")
                }
              },
              error: function(error){
                console.log(error);
                alert("Error. Delete failed.");
              }
        });    
        
    }
    

    }

    mainView.router.load({
    url: ‘pages/profile.html’,
    context: {

    }
    

    })
    showMainMenu(true);

    // Login
    // var ls = myApp.loginScreen(’.login-screen’);
    // myApp.closeModal(’.login-screen’);

    Here is the html

        <div class="page" data-page="page-contact">
    <div class="page-content">
    	<div style="text-align: right;padding:20px;">
            <a href="#" onclick="onClickContactEdit({{contact['id']}})">Edit</a>  &nbsp;
            <a href="#" onclick="onDeleteContact({{contact['id']}})">Delete</a>                  
    	</div>
    	<div id='mnu_contact'>
    		<div id="ul_sub_menu">
    	</div>    	
    </div>
    

    and for illustration, a sample of the json

    [{"id":6,"address_pretty":"100 Kian Villages, Wisozkton, NY 52960"}]},{"id":223,"name_full":"Abel Mueller","name_preferred":null,"name_pretty":"Abel Mueller","company":null,"notes":null,"phones":[],"emails":[],"addresses":[]},{"id":296,"name_full":"Adalberto Cremin","name_preferred":null,"name_pretty":"Adalberto Cremin","company":null,"notes":null,"phones":[],"emails": ... ]

    #7

    The closing tag of

    <div id="ul_sub_menu">
    

    seems to be missing. Try replacing it by

    <div id="ul_sub_menu"></div>

    #8

    one thing that i noticed is you must be careful when you’re working with id … f7 sometimes keeps the old template in the document … so if you work with id you migh be attaching data to hidden html code from previous page

    to avoid this you disable cache in pagination … or work with class try
    console.log( $('#ul_sub_menu').length);

    and see how many ul with this id you have in the document
    also as other have mentioned you haven’t closed your tag


    #9

    okay guys, thanks for the thoughts.

    What i have done is to follow the template laid down in a sample app i saw somewhere done version 1.2.0; a screenshot of the index.html is attached to the bottom of this post.

    I just have two questions:

    Firstly, how do i make multiple pages have access to template7 and the json being fed from the API: The app i am referencing has only one page so this isn’t much of a problem.

    Secondly, my app doesn’t log in when i input this code

    // Compile and render
    var compiledTemplate = Template7.compile(template);

    but when i remove it, it loads. What could be the problem?