PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 9, 2022

[FIXED] How to use insertBefore and appendChild with a jQuery AJAX server side rendered html result

 September 09, 2022     ajax, appendchild, javascript, jquery, prepend     No comments   

Issue

I basically need to use insertBefore and appendChild with a Server Side rendered HTML page jQuery AJAX result. I get the error: "Failed to execute 'inserBefore' on 'Node': parameter 1 is not of type 'Node'."

var parent_elem = $('#parent_elem');
$.ajax({
    type:'POST',
    url:'example.com/my_ajax_call',
    data: {"my_data":my_data},
    success:function(data){
        parent_elem.prepend(data); //THIS IS THE JQUERY SOLUTION BUT I NEED PURE JS WHILE USING JQUERY AJAX REQUEST
    },
    fail:function(data){
        console.log(data);
        console.log('failed to load page');
    }
});

what I am trying to do is this:

var parent_elem = document.getElementById('parent_elem');
$.ajax({
    type:'POST',
    url:'example.com/my_ajax_call',
    data: {"my_data":my_data},
    success:function(data){
        parent_elem.inserBefore(data, parent_elem.firstChild); //THIS IS WHAT I NEED BUT IT THROWS ERROR "Failed to execute 'inserBefore' on 'Node': parameter 1 is not of type 'Node'."
    },
    fail:function(data){
        console.log(data);
        console.log('failed to load page');
    }
});

Solution

If you want to turn HTML string into a node you can use jQuery function around it:

var node = $("<h1>hello world</h1>")

So in your case:

parent_elem.inserBefore($(data)[0], parent_elem.firstChild); 


Answered By - IT goldman
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing