due to some circunstances of my code, i'm using the following button of a form to call a jquery function:
<form id="formElem" name="formElem" enctype="multipart/form-data" action="" method="post">
....
<button name='enviar_candidatura' id='enviar_candidatura' value='enviar_candidatura' onclick='return false;' type='submit'>Enviar Candidatura</button>
...
The jquery function that is called:
$('#enviar_candidatura').bind('click',function(){
var form = $('#formElem');
var conta_Duplicates;
conta_Duplicates=dadosImportantes();
//alert("Deu");
var preenchimentoForm=true;
//alert("Contasssss"+conta1);
//var eventos=$countEventos;
var eventos=conta_Duplicates[2];
//alert("Wiggins"+eventos);
//var empregos=$countEmpregos;
var empregos=conta_Duplicates[1];
//var cursos=$countCursos;
var cursos=conta_Duplicates[0];
//alert($countEmpregos);
/*if($('#formElem').data('errors')){
preenchimentoForm=false;
dadosFormularios(form, preenchimentoForm, cursos, empregos, eventos);
return false;
}
else{*/
dadosFormularios(form, preenchimentoForm, cursos, empregos, eventos);
//}
});
Now what i need is to receive in this function the formElem so that i can define here the action="" of the form and call it using form.action="index.php....".
As you can see in the code above, i tried using
var form = $('#formElem');
however, that doesn't work, i tried:
form.action = 'index.php?pagina=candidaturasB&'+ qstringA;
form.submit();
but without success :/
try this
form.attr("action", 'index.php?pagina=candidaturasB&'+ qstringA)
form.submit();
i think there are no method .action , so you need to set action as attribute
form is jQuery object, it dosn't have action property. You should use attr method:
form.attr('action', 'index.php?pagina=candidaturasB&'+ qstringA);
Since form is a jQuery object it doesn't have the property action. Try this:
form.attr('action', 'url');
Related
I am currently using a very similar AJAX post request across many parts of my page:
$(document).ready(function() {
$("#name").change(function(e){
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
The above code works perfectly.
I am having a problem getting any functionality with dynamically loaded content. So for example a form grabbed by an AJAX call and put into my page this above does not work.
If we can pretend that I was running the same AJAX call as above but on dynamically loaded content from a PHP script using AJAX. what would my call look like. #table is a static element that is always present on the page.
I have tried this but it is not working:
$(document).ready(function() {
$("#table").on("click", "#btn1", function(e){
e.preventDefault();
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
Currently I am getting nothing show up on console and it just does not work.
Is what I am doing here correct?
The html would look like this: echoed from php:
<table id='table'>//this is the static element form is echoed
<form method='post'>
<input id='name' name = 'name'>
<button id='btn1' type='submit'>Add me</button>
</form>
</table>
I have changed my code slightly click on button rather than on change.
Try updating the code with following
$(document).ready(function() {
$("#table #btn1").on("click", function(e){
e.preventDefault();
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
It is not possible to set a function on a dynamically added element, when the element is not there in document
And instead of <table> use <div> if possible
I think your problem is that you miss
$( document ).ajaxComplete(function() { "script here will run and be available after ajax load" });
I'm trying to submit a little contact form.
Here is my jquery to POST:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
});
</script>
Here is my html that handles the form:
<form method="post" >
<textarea id="contact_me_text" name="contact_text">Ask me anything!</textarea>
<div>
<input type="text" name="contact_email" value="Email"/><br/><br/>
<a id="contact_submit" href="javascript:submit_contact()">Submit</a>
</div>
</form>
Everything seems to look ok but the form is not submitting. I've run the .php file through a regular submit and it works fine.
Any thoughts?
You need to declare your function outside of $(document).ready() and then call it using anything.
Why can't I ?
As Local Variables cannot be accessed from outside, similarly local functions cannot also be accessed.
Try this:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
$('#contact_submit').on('click', function(){
submit_contact();
return false;
});
});
</script>
and then remove the JS inside HREF attribute.
You need to declare the function outside ready function of jQuery. Moreover you can use serializeArray to determine data to send. By using this you will not need to mention every control name. On server side you can receive the input with same names you have mentioned in your form.
function submit_contact()
{
var params = $("#formId").serializeArray();
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", params, function(data){
console.log( data );
});
}
I want to passivate form action because i submit the form with js. But if there is form action js doesn't work and page redirects action url. I remove form tags and put div tags with #combination id but it didn't work neither
js:
$("#combination").submit(function(){
var url = "www.myurl.com/?view=listen&";
var i = 0;
$("input:checked").each(function(){
url += "tag[" + i + "]" + $(this).val() + "&";
i++;
});
alert(url);
location.href = url;
});
html:
<form id="combination" action="" method="get" name="combination" target="_self">
<?php foreach($top_tags as $top_tag):?>
<input type="checkbox" name="tag[]" value="<?php echo $top_tag['tag_name'];?>" /><?php echo $top_tag['tag_name'];?><br />
<?php endforeach;?>
<input name="" type="submit">
</form>
you have to prevent the default behavior of the form with "preventDefault" and than start your ajax-call or what ever ;).
$("#combination").submit(function(event){
event.preventDefault();
var url = "www.myurl.com/?view=listen&";
var i = 0;
$("input:checked").each(function(){
url += "tag[" + i + "]" + $(this).val() + "&";
i++;
});
alert(url);
location.href = url;
});
The problem you really could not call the handler this way:
http://api.jquery.com/submit/
handler(eventObject)A function to execute each time the event is triggered.
basically what happend, instead of submitting form you did redirection.
Think about chain:
you call submit method for form, using jquery.
while the event triggered for form, but before the form actually submitted you change the location.
this cancels submitting and instead redirect you to whatever
If you really want things doing this way you may do it into the two ways:
redirection on the server side after the form is submitted
as it was said use ajax http://api.jquery.com/jQuery.ajax/ submitting into the handler and make disable default action either way
$("#combination").submit(function(event){
event.preventDefault();
// code here
});
OR
$("#combination").submit(function(event){
// code here
return false;
});
Is there anyway to send post data to a php script other than having a form? (Not using GET of course).
I want javascript to reload the page after X seconds and post some data to the page at the same time. I could do it with GET but I would rather use POST, as it looks cleaner.
Thanks a lot.
EDIT: Would it be possible to do with PHP header? I'm sure it is better to use JQuery but for my current situation I could implement that a lot easier/faster : )
Cheers
I ended up doing it like so:
<script>
function mySubmit() {
var form = document.forms.myForm;
form.submit();
}
</script>
...
<body onLoad="mySubmit()";>
<form action="script.php?GET_Value=<?php echo $GET_var ?>" name="myForm" method="post">
<input type="hidden" name="POST_Value" value="<?php echo $POST_Var ?>">
</form>
</body>
Seems to work fine for me, but please say if there is anything wrong with it!
Thanks everyone.
As requested above, here is how you could dynamically add a hidden form and submit it when you want to refresh the page.
Somewhere in your HTML:
<div id="hidden_form_container" style="display:none;"></div>
And some Javascript:
function postRefreshPage () {
var theForm, newInput1, newInput2;
// Start by creating a <form>
theForm = document.createElement('form');
theForm.action = 'somepage.php';
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'hidden';
newInput1.name = 'input_1';
newInput1.value = 'value 1';
newInput2 = document.createElement('input');
newInput2.type = 'hidden';
newInput2.name = 'input_2';
newInput2.value = 'value 2';
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
// ...and it to the DOM...
document.getElementById('hidden_form_container').appendChild(theForm);
// ...and submit it
theForm.submit();
}
This is equivalent to submitting this HTML form:
<form action="somepage.php" method="post">
<input type="hidden" name="input_1" value="value 1" />
<input type="hidden" name="input_2" value="value 2" />
</form>
You can use JQuery to post to a php page:
http://api.jquery.com/jQuery.post/
By jQuery:
$.ajax({
url: "yourphpscript.php",
type: "post",
data: json/array/whatever,
success: function(){ // trigger when request was successfull
window.location.href = 'somewhere'
},
error: anyFunction // when error happened
complete: otherFunction // when request is completed -no matter if the error or not
// callbacks are of course not mandatory
})
or simplest:
$.post( "yourphpscript.php", data, success_callback_as_above );
more on http://api.jquery.com/jQuery.ajax
Use the FormData API.
From the example there:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
Form your own header, as such:
POST /submit.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
userId=admin&password=letmein
How about this:
function redirectWithPostData(strLocation, objData, strTarget)
{
var objForm = document.createElement('FORM');
objForm.method = 'post';
objForm.action = strLocation;
if (strTarget)
objForm.target = strTarget;
var strKey;
for (strKey in objData)
{
var objInput = document.createElement('INPUT');
objInput.type = 'hidden';
objInput.name = strKey;
objInput.value = objData[strKey];
objForm.appendChild(objInput);
}
document.body.appendChild(objForm);
objForm.submit();
if (strTarget)
document.body.removeChild(objForm);
}
use like this:
redirectWithPostData('page.aspx', {UserIDs: getMultiUserSelectedItems()},'_top');
You can send an xhr request with the data you want to post before reloading the page.
And reload the page only if the xhr request is finished.
So basically you would want to do a synchronous request.
i have this form:
<form id="myform" name="myform" action="test.php" method="post">
<input type="text" name="shout-in" id="proShoutIn" maxlength="80" />
<img src="post.gif"/>
</form>
how can i do a ajax post so that i can use if (isset($_POST['shout-in'])){..do something..}?
i need to get the value that gets entered in the <input> and do a post with it.
any ideas?
thanks
$('#add_shout').click(function () {
var $form=$('#myform');
$.post($form.attr('action'), $form.serialize());
});
$.post() - $.ajax() shorthand for the POST method
.serialize() - creates a text string in standard URL-encoded notation
With the 3rd (optional) parameter of $.post() you can specify a callback function which will receive anything that was sent back as its only parameter. It will run when the AJAX query successfully finished (so you can do DOM modifications that depend on the AJAX call, etc.).
You also might want to prevent default form submission (in a lot of browsers pressing Enter in the input field would trigger it) and run the AJAX submission:
$('#myform').submit(function (e) {
$('#add_shout').click();
e.preventDefault();
});
$.post("test.php", $("#myform").serialize(),
function(data) {
// do something with the response
}
);
$("#myform").submit(function (e) {
$.post(this.action, $(this).serialize(), function (data) {
//handle response
});
//prevent form from submitting. In jQuery, do not use return false
e.preventDefault();
}
Nettuts plus:
Submit A Form Without Page Refresh using jQuery