1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

problems updating the DOM after http request, no framework

Discussion in 'jQuery' started by iago111, Mar 23, 2021.

  1. #1
    Hello,
    I would like to let a button disappear after I have deleted the relevant data (in connection with that button) from the db. A small delete button within the bigger button should trigger its dissappearance.
    The delete button dissapeares but not the parent button.
    What could be the problem here? Thanks a lot!

    The small button within the bigger butten is it's 4th child! text, span, button, button

     $('button.cross').on('click',function(event) {
    
           event.stopPropagation();
           sectionID = ($(this).attr("data-sectionid"));
    
           if(confirm("Deleting a section will also delete all CPs of this section. Are you sure you want to proceed?")) {
    
            self = this;
    
           $.ajax({
    
            type:'POST',
            url:'./http.php?action=delSection',
            data: "sectionId=" + sectionID,
    
             success: function (result) {
    
                  
                  //THIS WORKS:
                  $(self).css("display","none");
    
                  //THIS DOES NOT WORK
                  $(self).parent().css("display","none");
    
                      },
                       error: function(xhr,status,error) {
    
            var errorMessage = xhr.status + ': ' + xhr.statusText
             alert('Error - ' + errorMessage);
            },
         
              
           });
    
             }
          
    
       });      
    Code (JavaScript):
     
    iago111, Mar 23, 2021 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #2
    I'd have to see the markup you are manipulating and/or the page in question to truly weigh in properly, but I think the first big mistake is the mind-numbingly dumbass rubbish known as jQuery, in particular how it taught you everything except how to manipulate the DOM or to do much of anything properly. Such rubbish as it's parent() redundancies, how you're using CSS instead of actually removing things, etc, etc, is just making you work harder, not smarter.

    I really wonder what the blazes is in the kool-aid that makes people think idiocy like jQuery is worth using in the first blasted place.

    Q: is the delete button IN the section to be deleted? If so, why not delete the section AND the button simultanously ripping them out of the DOM with parentNode.removeChild? Doesn't look like this is stuff you should be hiding, looks like stuff you should be DELETING.
     
    deathshadow, Apr 3, 2021 IP
  3. iago111

    iago111 Member

    Messages:
    99
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    33
    #3
    Yes, that sounds good! I solved it with a refesh withing the result handler: window.location.href = "./index.php";

    You know what the point is, I don't get JS in my brain, this is why I also started with vue.js and react.js
    These compononents that are used within these frameworks behave like objects, in Java or PHP.
    Objects can interact, exchange data etc. (I can visualize that in my brain)

    And with objects I don't mean something like this:

    var myObject = {
        sProp: 'some string value',
        numProp: 2,
        bProp: false
    };
    Code (JavaScript):


    Vanilla JS is a big mess for me! You have that prototype chain and with ES6 you can also instantiate objects but it's a mess anyway!
    ES6 makes everything even a bigger mess!
     
    iago111, Apr 6, 2021 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #4
    No clue what that has to do with the presented script or your original question. :p

    The problem with JavaScript isn't that it's hard to understand, it's that it's so easy thanks to crappy documentation, crappy specification writing, to THINK these alternatives are going to make your life any simpler. Thus people dive for off the shelf "components" that are in point of fact more code and harder to work with than the vanilla code. Yet because we all stumble on certain mental hurdles at the start, it's easy to THINK the framework or other such nonsense saved time.

    It generally doesn't.

    Objects / ES6 classes are actually pretty simple. The programming model they are based on was created to simplify many tasks and make them EASIER to understand. The problem is that with JavaScript lacking proper pointers, it's harder to explain its concepts. Particularly object trees.

    I'm often shocked at how things like the DOM tree are so hard to understand. Things like parentNode, firstElementChild, nextElementSibling, and so forth are relatively simple concepts.

    Just to show what I mean, let's say what you have is a table with a bunch of TR where the final TD contains your remove buttons.

    Driveby coding, may be typo's

    
    <table id="shoppingCart">
    	<caption>Shopping Cart</caption>
    	<thead>
    		<tr>
    			<th scope="col">Name</th>
    			<th scope="col">Quantity</th>
    			<th scope="col">Unit Price</th>
    			<th scope="col">Total</th>
    			<td></td>
    		</tr>
    	</thead><tbody>
    		<tr>
    			<th scope="row">Engraved Flower Antique Finish E<i>b</i> Alto Saxophone</th>
    			<td>1</td>
    			<td>219.99</td>
    			<td>219.99</td>
    			<td><button type="button" title="remove" value="974">&#x1F5D9;</button></td>
    		</tr><tr>
    			<th scope="row">Yamaha 5C Alto Sax Mouthpiece</th>
    			<td>1</td>
    			<td>29.99</td>
    			<td>29.99</td>
    			<td><button type="button" title="remove" value="432">&#x1F5D9;</button></td>
    		</tr><tr>
    			<th scope="row">Lazarro #2 Alto Saxophone Sax Reeds, box of 10</th>
    			<td>2</td>
    			<td>13.99</td>
    			<td>27.98</td>
    			<td><button type="button" title="remove" value="1788">&#x1F5D9;</button></td>
    		</tr>
    	</tbody><tfoot>
    		<tr>
    			<th scope="row" colspan="4">Shipping<br><em>Free for order over $50</em></th>
    			<td>0.00</td>
    		</tr><tr>
    			<th scope="row" colspan="4">Grand Total</th>
    			<td>277.96</td>
    		</tr>
    	</tfoot>
    </table>
    Code (markup):
    NOT that I'd have scripting only buttons in the markup, but if one did....

    
    for (var button of document.querySelectorAll(
    	"#shoppingCart button[title=remove]"
    )) button.addEventListener('click', cartRemoveClick);
    
    function cartRemoveClick(event) {
    
    	if (!confirm("Are you sure you want to delete this item?")) return;
    
    	var
    		button = event.currentTarget,
    		data = new FormData(),
    		x = new XMLHttpRequest();
    
    	data.append("productNumber", button.value);
    
    	x.onload = () => {
    		switch (x.status) {
    			case 200:
    				var e = button.parentNode;
    				while (e.tagName !== "TR") e = e.parentNode;
    				e.parentNode.removeChild(e);
    				return;
    			// add other handlers here if desired
    		}
    		alert(
    			"Unable to Delete, Server Reported " +
    			x.status + ': ' + xhr.statusText
    		);
    	});
    
    	x.open("POST", "cart.php?action=delete");
    	x.send(data);
    
    } // cartRemoveClick
    
    Code (markup):
    It's actually less code than the jQuery one, and IMHO a lot clearer as to what's going on there.

    First off, notice that we can leverage how BUTTON's value can be different than its content. One of the big reasons to use BUTTON instead of INPUT type="button". We still set type="button" so that they don't try to submit any forms when clicked. (the default is SUBMIT!)

    In the script we go through and grab all the <button>remove</button> inside our shopping cart, and add our event handler.

    The handler does the confirmation first with a return, this way the code doesn't have to parse through to the end and can just exit. No more "else".

    I declare the local variables up-front together whenever possible. I grab the button off of "this.currentTarget" since we need it inside our AJAX handler.

    The "data" variable is a FormData object which is a easy, secure, and reliable way to pass data server side. Note, if you're trying to ajax a whole form, you can pass the FORM element to "new FormData()" and it will pull all the applicable values.

    Finally "x" as our XMLHttpRequest. The onload handler checks for 200. I used a switch as I often leverage the different error states to report what's going on without needing to process the entire response body. The 200 state looks for the TR that's a ascendent of the button, and removes it from the table. Otherwise alert the failure.

    Once that's set, open the request, and send the data.

    NOT rocket science, NOT any harder than what jQuery suckers people into thinking is better.

    NOTE, also not IE9/earlier compatible since I use ".onload" ... OH FREAKING WELL!

    In a lot of way's that's one of jQuery's "problems" -- they are still adding extra wrapping methods to fix things that no longer need fixing. Something I've only recently soured on, so I can't fault them entirely for that.
     
    Last edited: Apr 9, 2021
    deathshadow, Apr 9, 2021 IP
  5. iago111

    iago111 Member

    Messages:
    99
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    33
    #5
    If you say so!? To be honest I wouldn't try that http request with my debit card / PIN data.

    Yes it is, it is ONE http request of perhaps 30 or 40 of a business site. Can you abstract that client /server communication, so
    that I can easily check everything within one file?

    You concentrate on one specific case and you come up with a very good solution. But that solution is restricted to that ONE case.

    React, angular and vue (I'm not talking about jquery!!) help to make things more abstract. (And you do NOT have to care about the DOM
    or updating the DOM with these frameworks at all, they are managing the DOM!!)

    I'm here and I'm asking you about a specific case, and you give me a specific answer. But what if come here and ask you
    how to implement a complex business logic or graphic interface?
     
    iago111, Apr 10, 2021 IP