简体   繁体   中英

Update dynamically created object value without page refresh

This maybe a stupid question (it's not true that there are no stupid questions).. but here goes. I will lay out what I'm doing:

1) user logs into a page and the first that that happens is that a list of objects from a MySQL database is pulled using php. it's returning an array of objects via json_encode().

Then the page dynamically builds a DOM element for each object and is appended into a container via jQuery $('container').append(.....>. This happens through a loop and a php variable that gets assigned as a javascript variable.. the important parts of the code:

 for(var i = 0, len = userObjects.length; i < len; i++){
     var currentObject = userObjectsObjects[i];
     var isCurrentFavorite = isFavorite(currentObject.isFavorite);

     var ratings = buildRatingString(currentObject.ratings, currentObject.raters);

    if(count % 4 !=0){
        $(".content").append('<div class=col-md-3>.............');   
        count++;
    }else if(count % 4 == 0){
        $(".content").append('<div class=col-md-3>........');
        count++;
    }
    $(".content").append('</div></div>');
}

This builds a DOM element and places the corresponding currentObject. into the proper place and displays it on the page.

All of that is fine and dandy. Not ideal (i'm open to suggestions on how to optimize that process because it seems convoluted to me), but it works.

My issue:

A user can click on a heart to add to their favorites. The click hits a function where a check is done to see if the object is currently favorited and takes appropriate action with the ajax call.

Currently the only way I know how to get the objectId is by setting it as the id for the Favorites button. When the button (which is hidden and the heart icon is in it's place) is clicked, it send that information to the function toggleFavorites() and the information is sent to the database.. ie..

<button type="button" id="'+currentObject.objectId+'"></button>  

The code: (objId is the assigned id from the button above ^^^^^)

function toggleFavorite(objId, isFav){
var value = isFav;
var objectId= objId;

    var toTable = '';
    if(value == 'Y'){
        toTable = 'N';
    }else if(value == 'N'){
        toTable = 'Y';
    }
ajaxIt(toTable, recipeId);
    function ajaxIt(toTable, objectId){
                $.ajax({
                        type: 'post',
                        url: '../PHP/update_favorite.php',        
                        data: {isFavorite: toTable, objectId: objectId},      
                        success: function(){
                             if($('#heart' + objectId).hasClass("redClass")){
                                    $('#heart' + objectId).addClass('grayClass')                                      
                                    $('#heart' + objectId).removeClass("redClass");

                                }else if($('#heart' + objectId).hasClass("grayClass")){
                                    $('#heart' + objectId).removeClass("grayClass");
                                    $('#heart' + objectId).addClass('redClass');


**I WANT TO UPDATE THE OBJECT IN HERE**
                                }  

                }
            });
    return false;        
    }

}

This variable is set depending on if the object is currently a favorite.. ie. at the time of the initial object pull. so, if it's currently a favorite and the user clicks the heart.. var toTable would = 'N' (remove from favorites).. and vice versa.

I am manually setting the heart color in the ajax success function, but I need to change the actual object because I have ran into this issue:

If the object is currently a favorite it is denoted by isFavorite: 'Y' when the object is pulled. You click the heart and ajax correctly sends a 'N' to the table.. i have confirmed that works. And the heart is turned from red to gray. If you click the heart to add to favorites again without page refresh isFavorite is still 'Y' (a new object was not pulled with the updated table values) and it sends a 'N' to the table still.

Is it possible update a dynamically created object like this so that when the toggleFavorite() function is called, it has the correct table values?

Sorry this was so wordy... I don't have the programming knowledge or vocabulary yet to be more succinct.

The implementation that you have is actually convoluted and can be simplified using any front-end framework like angular 1/2/4/5 or reactjs or others.

For using plain JQuery, you should update the object instead of updating the DOM. After updating the object, you already know which DOM corresponding to the id you have to update and update the same. Or make a function which will take new object and re-render the whole DOM part. First is preferable. I know this is just some pseudo logic but this is so simple that it should not require any explanation. I will be happy to chat to explain more. Also if you use a framework, it'd be dead simple. Just try looking at any framework hello world example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM