Categories: javascript, php, jquery, ajax

PHP doesn't see new elements created with jQuery and AJAX

3 answers

I faced an issue since I can't get a just created element with a PHP script.

I have a list of tags loaded with PHP:

<ul>   <li>     <input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="4">     Some tag   <li> <ul> 

Thanks to AJAX I append another element inside the UL

jQuery(document).ready(function($) {   $('.add-tag-btn').click(function(event) {     var tag_title = $('.tag-search').val();     $.ajax({       url: 'add-tag.php',       type: 'POST',       dataType: 'json',       data: {         'tag_title': tag_title       },       success:function(result){         $('.tag-search').val('');         $('.new-tags').append('<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="'+result.tag_id+'">'+tag_title+'</li>');          console.log(result.tag_id);       }     });   }); }); 

Thus I have a new UL

<ul>   <li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="4">Value #4</li>   <li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="5">Value #5 (new value generated with jQuery and AJAX)</li> </ul> 

But once I submit the form, only the existed value is added to DB.

if (isset($_POST['submit'])) {     ....     bla bla bla     foreach ($_POST['check_list_tags'] as $value) {         $arr2[] = $value;         }     bla bla bal } 

Looks like that PHP can't handle a new value without the page reloaded. At the same time, I add


dynamically and that works just perfect.

Can anyone explain me how to force PHP to see the newly created elements (the elements that were appended to the existed HTML by the means of jQuery).

Thanks everyone for the assistance.


This is how I add the "checked"

jQuery(document).ready(function($) {   $('.adm-checkbox').click(function(event) {     if (this.checked) {       this.setAttribute("checked", "checked");       console.log('checked');     } else {       this.removeAttribute("checked");     }   }); }); 

This is how the form looks like:

<form class="" action="<?php echo $router->url ?>" method="post" enctype="multipart/form-data"> ..... <ul class="new-tags">  </ul> <ul>    <?php foreach ($admin->getAdmTags() as $value): ?>       <li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="<?php echo $value['id'] ?>"><?php echo $value['title'] ?></li>     <?php endforeach; ?> <ul> </form> 

UPD # 2:

May be the reason is that I use two separate functions in jQuery for "checked"??!?!

$('.adm-checkbox').click(function(event) {     if (this.checked) {       this.setAttribute("checked", "checked");       console.log('checked');     } else {       this.removeAttribute("checked");     }   }); 


$('.adm-tags').on('click', '.adm-checkbox', function(event) {     if (this.checked) {       this.setAttribute("checked", "checked");       console.log('checked');     } else {       this.removeAttribute("checked");     }   }); 

I do it because onclick doesn't work for the newly created elements.

P.s: It doesn't matter where I put a newly created "li"...

Thank everyone for participation. I've created a new page and did everything again. And now it works. Now I need to find the mistake in my full code.

All answers to this question, which has the identifier 61169911

The best answer:

Name attributes can be arrays so the name isn't the issue - HTML input arrays

I think the reason is as you mentioned, the checked attribute needs to be added to all of the inputs otherwise the value won't be sent in the request.

If the inputs were text or number for example, then the checked attribute wouldn't be needed.

The same would apply to radio inputs, or the selected attribute for a select menu.

TLDR, add checked:

$('.new-tags').append('<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="'+result.tag_id+'" checked>'+tag_title+'</li>'); 

That is of course, if it should be automatically checked and not reliant on the user checking it manually.

I may have to change this answer based on if this is a traditional form submission or an ajax submission not using a form.

I don't know how to close the topic. It works with the newly created code. Once I find out the mistake in my full code, I will reply with the explanation of my mistake.

When you send a form though either POST or GET every input needs a unique name. From you code it looks like you add a new input element with a name attribute that has the same value as the already existing element.

I suspect if you add the new element with a unique name value it should work. You could incorporate that into you JavaScript code by having a counter for the number of input elements with name X and then add a number. And you would need to do a similar thing in your PHP.

Edit: Apparently you can have name attributes with the same name if you use '[]' after the name, thank you @martincarlin87

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type is referenced as an interface from”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data