Accessing value of dynamically created elements with javascript in PHP code - javascript

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>)

Related

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.

Add a dynamic form field after pressing a button

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>

Generating multiple AJAX codes for dynamically generated elements in Javascript,

I have a script which dynamically generates form elements with their corresponding ID, for e.g.
response from MySQL db says - 4, then
<form ID="form0">
<Input>....
<Button type="submit>....
</form>
<form ID="form1">
<Input>....
<Button type="submit>....
</form>
<form ID="form2">
<Input>....
<Button type="submit>....
</form>
<form ID="form3">
<Input>....
<Button type="submit>....
</form>
once this list of forms are generated, I have an AJAX code which detects the submit buttons and send the input values off to db via PHP page, something like this below,
$(document.body).on('submit', '#form' ,function(e){
e.preventDefault();
var postData = $("#form").serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});
So my question is that, for the list of forms, I have to somehow generate multiple of this AJAX code for form0, form1, form2, form3.. and because I can't anticipate how many forms will be generated, I can't just write one AJAX code like the one above.. is there anyway to dynamically generate AJAX codes for dynamically generated multiple forms?
Give the form a class that identifies it as a form to be handled by your AJAX handler. Then, inside the handler, reference this to get the form element that is being submitted.
<form ID="form0" class="js-ajax-form">
<input>....
<button type="submit>....
</form>
Handler
$(document).on('submit', '.js-ajax-form' ,function(e){
e.preventDefault();
var postData = $(this).serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

How to read <input type="hidden"...> in JavaScript on subsequent page?

One first page:
A form SUBMIT goes to a subsequent page.
VBscript can see the hidden value with ... Request("myName") ...
How do I do the same thing in JavaScript.
alert(window.location.search);
or
alert(window.top.location.search.substring(1));
return nothing.
Well, you dont. When you submit a form it sends the values to a server, and the "server-side" reads that in vbscript as Request (Requested). If you want to let the requested value accessible to the Javascript, your server-side (subsequent) page must write that Request data back to the client-side, in other worlds, you have to write the requested value directily in the HTML that will be send back to the client browser.
Ex: In your ASP (Server-Side Subsequent VBScript file) you should write
Response.Write ("<script type=""text/javascript"">alert('" & Request("Data") & "')</script>")
<input type='hidden' id='hiddenId'/>
jQuery:
var value = $('#hiddenId').val();
alert(value);
Or
var value = document.getElementById('hiddenId').value;
alert(value);
In your form, you have to have the method set to GET.
<form method="GET" action="somepage">
<input type=hidden name=myHiddenValue />
</form>
Then on the next page, you can parse the search part of the url with a function like this.
function parseSearch(search, key) {
search = search.substring(1), items=search.split("&");
for (var i=0; i<items.length; i++) {
var item = items[i], parts = item.split("=");
if (parts[0] === key) {
return parts[1] || true;
}
}
}
parseSearch(location.search, "myHiddenValue"); // returns the hidden value
live demo

Categories

Resources