1

So, I have the original AJAX function:

dataType: 'json',
data : { action: something , id: id}, 
success: function(data) {
    var my_title= data.title; // values: "post1,post2,post3"      
    var my_name = data.name;  // values: "steve,mike,sean"
    var my_html ='<div class="'+ my_title +'">'+ my_name +'</div>' 
    jQuery('.my_class').append(my_html); 
}

So, I have two variables (my_titles and my_name) each with 3 values (n number values).

Then, I want to use these individual values for my_html variable and append them in the .my_class.

The result will be as follow:

 <div class="my_class">
    <div class="post1">Steve</div>
    <div class="post2">mike</div>
    <div class="post3">sean</div>
 </div>

So, I tried to edit my AJAX function as below:

dataType: 'json',
data : { action: something , id: id}, 
success: function(data) {
   jQuery.each(data,function (i,n){     
        var my_title= n.title;
        var my_name = n.name;               
        alert("Title:" + my_title);             
    });
}

I am getting undefined as the result.

Any help? thanks!

2 Answers 2

2

You should do it like following.

jQuery.each(data.title, function (index){        
    var my_title = this; // change here `this` instead of `data.title`               
    alert("Title:" + my_title);             
});

If data.title is a string. You need to split data.title and then iterate through it like following.

jQuery.each(data.title.split(','), function (index){        
    var my_title= this;               
    alert("Title:" + my_title);             
});

Update: Do like following in ajax success.

var length=data.title.length;
for (var i=0; i<length; i++) {    
    var my_title= data.title[i];
    var my_name = data.name[i];               
    alert("Title:" + my_title); 
    alert("Name:" + my_name);             
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the reply. i made an edit to the original post. I realized that I had the form wrong to start with.
1

Assuming data.title is an array

jQuery.each(data.title, function (index){        
    var my_title= data.title[index];               
    alert("Title:" + my_title);             
});

1 Comment

Thank you for the reply. I made changes to the original post. Could you take a look at it for me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.