Add a dynamic form field after pressing a button - javascript

I have a form with a simple button $builder->add('language_switcher', ButtonType::class); which should simply, if pressed, add another field. To do that, I used Symfony's cookbook http://symfony.com/doc/current/form/dynamic_form_modification.html
$builder
->get('language_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function () use ($builder, $options) {
$preparedOptions = $this->prepareOptions($options['data']['productCustomizations']);
$builder->add('lang_switcher'), ChoiceType::class, $preparedOptions);
}
);
When now submitting it via AJAX
<script>
var $button = $('#xyz');
$button.click(function() {
var $form = $(this).closest('form');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
success: function(html) {
console.log(html);
$('#xyz').replaceWith($(html).find('#lang_switcher'));
}
});
});
</script>
I'm getting the error Buttons do not support event listeners. So I tried it out with a hidden field. I added the hidden field to the Form, set the EventListener to it, and added this data to my AJAX request
data[$('#id_of_hidden_field').attr('name')] = 1;
However this did nothing. The example in the cockbook is after submitting a choice field so I don't know how to adapt it to my needs. I couldn't use a SubmitType, because then it would submit the form, right? I just want to have it with a simple button.
The problem is, that, when I do a console.log(html) I don't see the new html element, so it seems like I'm not getting to the EventListener which is weird, because if I dump contents inside the listener I'm getting some data. It just seems like I'm not getting it inside the response

Ok, got it. The problem was that I used the builder inside the POST_SUBMIT event but I had to use a FormInterface. Since I couldn't add it AFTER submit I had to buy the same callback function as in Symfony's cookbook
$formModifier = function (FormInterface $form, $preparedOptions) {
$form->add($this->childIdentifier, ChoiceType::class, $preparedOptions);
};
And then the listener is built like this
$builder
->get('lang_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier, $options) {
$preparedOptions = $this->prepareOptions($options);
$formModifier($event->getForm()->getParent(), $preparedOptions);
}
);

<script type="text/javascript">
function inputBtn(){
var input=document.createElement('input');
input.type="file";
input.name="img[]";
input.multiple="multiple";
//without this next line, you'll get nuthin' on the display
document.getElementById('target_div').appendChild(input);
}
</script>
<button id="ifile" onclick="inputBtn();">create</button>
<form action="test.php" method="post" enctype="multipart/form-data">
<div id="target_div"></div>
<input type="submit">
</form>

Related

prevent page reload when calling php with ajax

I have a php function that I call using ajax and then handle the response with ajax. However, I want to prevent the page from reloading.
I have index.php containing a call to function1(), and it includes ajaxcall.js and jquery
Then my functions.php:
function function1(){
echo '
<form id="myform" action="" method="post" enctype="multipart/form-data">
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this)" placeholder="type an anime name" title="Type in a name">
</form>
<div id="table_recentanime" class="hscroll">
<table dir="ltr" id="myTable">';
// echo some table rows
}
if (isset($_POST['callyoukai_search'])) {
//echo "!!!" . $_POST['callyoukai_search'] . "the post value in php!!!!!!";
//echo
youkai_search($_POST['callyoukai_search']);
}
function youkai_search ($search_word){
// use $search_word to do a database query
return $result;
}
my ajaxcall.js
function searchfiltersajax(search_word){
if(event.key === 'Enter') {
console.log("yes");
console.log(search_word.value);
document.getElementById("myform").addEventListener("Keypress", function(event){
event.preventDefault()
});
jQuery.ajax({
url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
type: 'post',
data: { "callyoukai_search": "1"},
success: function(response) { var container = document.getElementById("myTable");
container.innerHTML = response;
console.log('php gave javascript '); console.log(response); console.log('php gave javascript '); }
});
console.log ("done");
}
}
My ajax call works fine. It calls the php function with the desired search_word, and the search results replaces the div content just like I want. However, right after this, the page reloads.
How do I prevent the reload? I tried preventDefault(), but the way I used it didn't work.
Thanks in advance
Inlining event handlers is a bad practice. But if you need it at least add the event keyword. Change from:
to:
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"
Moreover, don't add the same event handler (i.e.: Keypress) inside another: in this way you are adding more and more times the same event handler. Instead, use the event parameter.
I'd suggest to use the addEventListener() or .on():
$('#myInput').on('keydown', function(e) {
searchfiltersajax(this, e);
});
The snippet:
function searchfiltersajax(search_word, e) {
if (event.key === 'Enter') {
e.preventDefault();
console.log("yes");
console.log(search_word.value);
jQuery.ajax({
url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
type: 'post',
data: {"callyoukai_search": "1"},
success: function (response) {
var container = document.getElementById("myTable");
container.innerHTML = response;
console.log('php gave javascript ');
console.log(response);
console.log('php gave javascript ');
}
});
console.log("done");
}
}
<form id="myform" action="google.com" method="post" enctype="multipart/form-data">
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"
placeholder="type an anime name" title="Type in a name">
</form>
<div id="table_recentanime" class="hscroll">
<table dir="ltr" id="myTable">
<tbody>
</tbody>
</table>
</div>
The function searchfiltersajax takes one parameter named search_word. The first if-statement then checks an event-variable. This variable is declared nowhere in your code, so the code inside the if-statement will never get executed.
To verify this I would recommend to add debugger; as first statement inside the searchfiltersajax function. Then open the debugging console in the browser and reload the page. Do not forget to remove the debugger; statement once you are finished. If you know how to set breakpoints in the javascript debugger, you should not use debugger; statements at all.
As far as I understand you try to prevent a form to be submitted to the server but send an ajax call instead. There are several answers on StackOverflow for this topic, e.g. Prevent users from submitting a form by hitting Enter . You could use a code like this to achieve your goals (taken from the link):
$(document).on("keypress", "form", function(event) {
return event.keyCode != 13;
});
Last but not least, I would suggest not to include raw HTML sent by any server (even your own) to your page:
container.innerHTML = response;
Instead try to send a JSON object containing the information you wish to present and transform this object into HTML elements via JavaScript. This way you have a cleaner interface for data exchange and have to change on piece of code to change styling or other presentation aspects.

Accessing value of dynamically created elements with javascript in PHP code

I created some textbox dynamically with javascript.
here is javascript code:
$(document).on('click','#AddHaContactNumberButton',function(e){
e.preventDefault();
var outerDiv = document.getElementById("HaContactDiv");
var textboxDiv = document.createElement('div');
textboxDiv.className = 'inputs';
var input = document.createElement('input');
input.type = "text";
input.setAttribute('name','numbersshowbox[number]');
textboxDiv.appendChild(input);
numberinfoDiv.appendChild(textboxDiv);
outerDiv.appendChild(numberinfoDiv);
});
Now, I want to access these textbox values in php code on submit button click and then save it to database.
here is html code:
<FORM ID="AddFORM" NAME="AddFORM" ACTION="./admin.php" METHOD=POST><br>
<div class="clear">
<INPUT CLASS="button" TYPE=SUBMIT NAME="AddHaContactNumberButton" VALUE="Add" ID="AddHaContactNumberButton">
</div>
<div class="left-text-align relative-position">
<INPUT CLASS="button" TYPE=SUBMIT NAME="AddHaContactButton" VALUE="Save" ID="AddHaContactButton">
</div>
</FORM>
my php code:
if ($AddHaContactButton == "Save") {
$test = $_REQUEST['numbersshowbox[number]'];
}
the problem is $test is null. I searched and found that since javascript is client side and php is server side I cannot get the value in php unless I use ajax request. So I wrote ajax request as below:
$(document).on('click','#AddHaContactButton',function(e){
e.preventDefault();
currentForm = document.getElementById("AddFORM");
var numberarray= currentForm.elements['numbersshowbox[number]'];
if (numberarray != null) {
var arry = [];
for (var i = 0; i < typearray.length; i++) {
arry.push([typearray[i].value, numberarray[i].value]);
$.ajax({
url: 'savePhoneNumbersInDatabase.php',
type: 'GET',
data: { numbersArray: arry},
success: function(data){
currentForm.submit();
}
});
}
});
Now it is working fine but the problem is that I want to save data in database in postback. I mean I want page to be refreshed after clicking submit button.
If your goal is to simply refresh the page after the click event and $.ajax() call, add the following to end of the success callback in the ajax options:
location.reload();
Beyond simply answering your question, I believe it would be best practice to attach the ajax call to the submit event of the form, rather than the click event of the button. Unless there's a compelling reason you're not doing that already. Something like:
$('#AddFORM').submit(<submit handler>)

Ajax call goes only one time ASP.Net MVC5

I am writing an AJAX function in ASP.Net MVC5 and I am getting a problem that the form AJAX request goes only one time. It is a search page. After I choose the filter I press search I get the correct result. However if I changed the filter and click the search submit again, nothing will happen.
var ajaxFormSubmit = function() {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var target = $($form.attr("data-enbw-target"));
target.replaceWith(data);
debugger;
});
return false;
};
$("form[data-enbw-ajax='true']").submit(ajaxFormSubmit);
<form method="get" id="documentForm" action="#Url.Action("Index", "DocumentSearch")" def data-enbw-ajax="true" data-enbw-target="#documentSearchResult">
<button type="submit" id="submitbtn" name="submitbtn" tabindex="100" class="k-button">
<img src="~/Content/search_small_icon.png" />
#WebResources.DocumentSearchButton
</button>
</form>
#Html.Partial("Results", #Model)
public ActionResult Index(DocumentSearchInput model)
{
if (Request.IsAjaxRequest())
{
return PartialView("Results", result);
}
return View(result);
}
I do not get any error. and when I get a debugger; in javascript. the new data is correct. can you please help me.
You are replacing the form in your ajax success. As such, the new form will not have the submit binding on it. If you truely want to do this you will have to rebind to the new form, or possibly use a delegate instead.
$('parentSelector').on('event', 'childSelector', function(){});
parentSelector - A parent element of the child that pre-exists the child element and should typically not be removed/created during the page lifespan.
childSelector - A selector for the element that will be created/changed/removed at some point in the lifespan of the page.
I found the answer.
the problem wasn't with the submit. the problem was with re-writing the data.
$.ajax(options).done(function (data) {
$("#documentSearchResult").empty();
$("#documentSearchResult").html(data);
});
simply, I empty the div then write inside.

How to submit a form with specific fieldset

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

Perform JavaScript on submit of form

I use a JavaScript to load new pages on my webpagepage. looks like this:
function loadpage(page,div) {
$.get(page, function(data) {
$(div).html(data)
});
};
So when i submit my form, I want to use that function to load the php-page you normally would set as your "action" attribute in the form-tag. So how do I get the form to POST or GET(doesen't really matter) all its content and use the function.
Now, when I write:
<form action="javascript:loadpage('bla.php','#content');" method="post">
...
</form>
it loads bla.php the way i want it to but no data is being passed byt the POST...
Is there a solution to this problem? Thank you very much in advance.
see form.onsubmit event
Using your method, you would do it as follows:
Javascript:
function loadpage(page, div, form) {
var GETdata = '';
if ( form ) GETdata = $(form).serialize();
$.get(page, GETdata, function(data) {
$(div).html(data)
});
};
HTML:
<form action="javascript:loadpage('bla.php','#content', this);" method="post">
...
</form>
A better way would be to use non-obtrusive Javascript. Remove the inline javascript:
<form id="theForm" action="" method="post">
...
</form>
and bind your event handler from within your Javascript code:
$('#theForm').submit(function(e){
e.preventDefault();
loadpage('bla.php','#content', this);
});

Categories

Resources