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);
});
Related
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>
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...
});
});
});
Instead of redirecting the user to a new page, I want to add an overlay over the form. Somehow, the following code returns the overlay twice.
AJAX
$(document).ready(function ()
{
$('#form_informations').submit(function ()
{
$.get('php/formulaires.php', $(this).serialize(), function (data)
{
$('#form_informations').append('<div id="conf_informations" class="confirm"><p><img src="img/check.png" /><br /><?=FORMULAIRE_SAUVEGARDE;?></p></div>');
});
return false;
});
});
The id #form_informations is only used once.
For now, the second overlay is not created in php/formulaires.php because the file is empty as I have not started parsing the data.
Why is this happening? I don't see where this second overlay is coming from.
This is the HTML form:
HTML Form
<form id="form_informations" method="post" enctype="multipart/form-data">
<!-- form here -->
<input type="submit" name="submit_general" value="Save" />
</form>
May be you can add some code like this in the submit function
if(!$("#conf_informations").size()) {
$.get... //your get request here
}
Final solution
if(!$("#conf_informations").length()) {
$.get... //your get request here
}
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 ...
How do I redirect using either JQuery, DOJO or plain JavaScript, load another page but sent some POST parameters in request?
This should work, but i haven't tested it:
function postData(url, data)
{
var form = $('<form></form>');
$(form).hide().attr('method','post').attr('action',url);
for (i in data)
{
var input = $('<input type="hidden" />').attr('name',i).val(data[i]);
$(form).append(input);
}
$(form).appendTo('body').submit();
}
Basically you can create a form on the fly and submit it. Unfortunately you can not POST stuff directly from script.
You can't redirect with postdata using JavaScript, and I'm sure it's the same for jQuery as well. However, what you can do is...have a hidden form with post data, manipulate it as you need in javascript and submit that form.
<form id="myform" method="post" action="mypage.php">
<input id="myinput" type="hidden" value="mydata" />
</form>
<script type="text/javascript">
// in some function...
document.getElementById("myform").submit();
</script>
You can do first the POST request to the page, and then redirect:
var urlToPost='http://www.example.com/';
$.post(urlToPost, {'PARAMETER':'VALUE', 'PARAMETER2': 'VALUE2' /*Etc.*/}, function(response){
/*Callback*/
alert(response);
document.location=urlToPost;
})
More info for this: jQuery Documentation
Voici ma proposition :
String.prototype.poster=function()
{
var requeteur=new XMLHttpRequest;
requeteur.open('post',this,true);
requeteur.setRequestHeader('Content-type','application/x-www-form-urlencoded');
var equations=[];
for(i in arguments) equations.push(arguments[i]);
requeteur.send(equations.join(esper));
}
Au chargement, on récupère requeteur.responseText.
A vos commentaires !
Sacapuss
use this code
$().redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});