I'm trying to change my form action to another link during submit using jquery. Please view the following code:
javascript
$(document).ready(function(){
$("form[name='search']").submit(function(e){
var submit=$(this);
submit.attr('action','?search='+submit.find("input[name='tsearch']").val());
});
});
HTML/PHP
<form name="search" method="post">
<input class="inputbox" type="text" name="tsearch" value="<?php echo $text_search; ?>" />
Though i can't seem to get it working. Any help here will be appreciated.
Here's a working example: http://jsfiddle.net/RmKDT/4/
You can see by the alerts that the action is changing. You just need to resubmit the form as well.
Edit: Fixed potential infinite loop
$(function(){
var submitted = false;
$('form').submit(function(e){
if (submitted == true) {
return;
}
e.preventDefault();
var action = $(this).attr('action');
alert(action);
$(this).attr('action', 'two.php');
action = $(this).attr('action');
alert(action);
submitted = true;
// resubmit the form
$(this).submit();
});
});
Your code seems to be fine. There are a few things you can try to get this working.
Be sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file else in the html head section
Be sure that you've included the datatale script after you've included jQuery, as it is most certainly dependant upon that.
Check whether jQuery is included properly and once only.
Watch out for jQuery conflicts. There is some other library which is overridding $, so your code is not working because $ is not an alias for jQuery anymore. You can use jQuery.noConflict() to avoid conflicts with other libraries on the page which use the same variable $.
alert('?search='+submit.find("input[name='tsearch']").val()) see whether you are getting the value you want.
Related
I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});
I have a file upload form, the following javascript fires as soon as the form is submitted:
$("#uploader").submit(function() {
$("#indicator").show();
alert("Submitted");
var refresh = setInterval(function() {
$.get("progress.php?getprogress&randval=" + Math.random(), function(data) {
alert("Got " + data);
$("#indicator .bar div").width(data + "%");
if (data == 100) {
clearTimeout(refresh);
$("#indicator").addClass("done");
}
});
}, 250);
});
I added some alerts to debug, I get the alert("Submitted"), but not the one alerting the data. The php is fine, opening it in a separate window gives the correct values, but the javascript does not get it. Another weird thing is that if I stop the page load, the alert() with the value fires and code is processed.
You are not cancelling the form submission, that means your page will refresh. To cancel the submission you can call event.preventDefault()
$("#uploader").submit(function(e) {
e.preventDefault();
Just moving comments into the answer since your question actually has more to it than what you wrote above.
It is impossible to do two actions on the submit and expect them both to happen. Especially when one is trying to run code as the age is submitting. There are JavaScript libraries that do file uploads, you might want to look into them. BUT the basic idea is submitting the form to a hidden iframe on the page.
<form action="YourSubmitPage.php" method="POST" target="hiddenIframe">
...fileds here...
</form>
<iframe id="hiddenIframe" name="hiddenIframe" style="display:none" />
Ok solved this by using an <iframe>:
<form action="save.php" method="post" target="theiframe">...</form>
<iframe name="theiframe" src="about:blank"></iframe>
Still using javascript, but no e.preventDefault();
I hope your function is inside a $(document).ready() statement
I am trying to run this tutorial
i did not implement the validation part yet, but my problem shouldn't be based on this. Here is my code:
<script type="text/javascript">
$("#submitbutton").click(function () {
var content = $.("#contentarea").val();
$.ajax({
type: "POST",
url: "addArticle.php",
data: content,
success: $.("#addArticle").append("<p>ok</p>")
});
return false;
})
</script>
As seen in the demo, it should not refresh the page because of the return false statement and also should do a post instead of get. But neither it does. It will continue to reload the page and also append the given content to the url as an argument. How do i prevent this / where is my failure?
Here is the whole thing
The tutorial you have followed is incorrect. There are more ways to submit a form than just clicking on its submit button (for example, you can press return while in a text field). You need to bind your code to the form's submit() event instead of the button's click() event.
Once you have done this, use your in-browser debugger to check whether the code is actually being run when you submit the form.
Also, the success parameter needs to be a function:
submit: function() { $("#addArticle").append("<p>ok</p>") }
EDIT : also, you have written $.( instead of $( several times. This will cause a runtime error, which may cause the code that blocks the submission to fail.
Well well well...
A few less nerves later, it works.
I decided to use the jquery form plugin
But, and i bet you'll love that, i have no idea why it is working:
<script>
$(document).ready(function() {
$('#addForm').ajaxForm(function() {
alert("ok");
});
});
</script>
<div id="addArticle">
<form id="addForm" method="post" action="addArticle.php">
<textarea id="contentarea" required="required" name="content"> </textarea>
<br />
<input type="submit" id="submitbutton">
</form>
</div>
I guess the author has done pretty good work, just wanted to tell my solution to that future guy who is searching on google for that problem.
I'm having this little problem with internet explorer and ajax.
So first I used just php, and everything, worked, but because I don't want to reload the page, I use ajax.
So I have a form with a checkbox. When someone clicks on the checkbox, my ajaex is called and the input is changed in the db. In firefox there is no problem, but It doesn't work in internet explorer.
Here's a part of my code:
<script language="javascript" type="text/javascript">
function changefield($doss, $display){
$.get("update.php",{dossier: $doss, CSQ_DISPLAY:$display});
alert("test");
}
</script>
echo '<form id="'.$r ['BC_DOSSIER'].'" method="get" action="">
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)">
</form>';
It seems that in explorer, I only get the alert when the checkbox was checked. (Problem because it first reads the db if it must be checked or not, so you can change it later).
Does someone know where I went wrong?
Thank you very much in advance for the answers.
I would prefer to define it like this, I hate using onclick in my HTML:
edit FIXED (registered to change instead of click)
edit Wrapped in $(document).ready()
edit Added a click event as well
<?php
echo '<input class="ajax_check" id="check_'.htmlspecialchars($r['BC_DOSSIER']).'" type="checkbox" name="CSQ_DISPLAY" '.$checked .' />';
?>
<script type="text/javascript">
$(document).ready(function() {
$('input.ajax_check').click(function() {
this.blur();
});
$('input.ajax_check').change(function() {
var dossierId = this.id.slice(6);
var isChecked = (this.checked) ? 1 : 0; // better to explicitly convert bool to int for HTTP requests
$.get('update.php',{
dossier: dossierId,
CSQ_DISPLAY: isChecked
});
alert('test');
});
});
</script>
This will register that handler to all inputs with the className 'ajax_check', without leaving a function cluttering up the window object, and without messing up your HTML. Try it out and see if it fixes the problem - it may not as it does basically the same thing, but it's a better way of doing it IMHO. If you still have a problem, come back to me and we'll debug it.
Note that using this approach, it is important that the <script> is executed after the DOM is ready, so it should either be defined in the body after the checkbox or (better) wrapped inside $(window).load() or (best) $(document).ready().
In your code fallback function value wont passed for IE.
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)">
i.e) in above code onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)" this.checked will not work for IE, so you can pass as this and get the value in four function, this will work for all the browsers. e.g) like this
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this)">
and get the checked attribute inside the function.
I hope this will work.
i am using the following jquery to post comments to user_submit.php
var submit = document.getElementById("submit_js");
var comment = document.getElementById("comment");
$("#submit").bind('click', function(){
$.post("user_submit.php", {
comment: $("#comment").text()
});
});
the user_submit.php listens like:
$comment = htmlspecialchars($_POST["comment"]);
i can see in the Firebug console that there is no POST happening. only a single GET that i use for a different function (can this be the culprit?)
Assuming:
<input type="text" id="comment">
<input type="button" id="submit_js">
you want:
$(function() {
$("#submit_js").click(function() {
$.post("user_submit.php", {
comment: $("#comment").val()
});
});
});
PHP:
<?php
$comment = $_POST['comment'];
//...
echo htmlspecialchars($comment); // nothing catches this currently
?>
You also seem to be confusing "submit" and "submit_js" in your code. I'd advise against mixing Javascript and jQuery code unnecessarily too (the "getElementById()" business). You should familiarize yourself with jQuery selectors. For example:
$("#submit_js")
will create a jQuery object with all the elements (which should only be zero or one elements) with the ID of submit_js.
Remember that you're posting via AJAX, so even if you're echoing back the field value, it won't show on your screen unless you're listening for it in the $.post callback.
To check what the problem may be, submit the form normally without jQuery. If your PHP script is echoing back the field value, then the PHP script is working - check your JavaScript. If the you're getting blank, or empty array when using print_r(), then make sure the field name in your form is the same as what you're using in the PHP script.
Don't want you to have to rewrite your code, but here's what I recommend to do.
<form class="comments" method="post" action="user_submit.php">
<input type="text" name="comment" />
<input type="submit" value="Submit" />
</form>
JavaScript:
$('.comments').submit(function() {
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data, status) {
console.log(data);
}
);
return false;
}
This will submit your form to the PHP script. In the callback function, "data" is the returned data from the PHP script. So if you echo the field value back, the Firebug console will display the value.
In the event the user's browser has JavaScript disabled, the form will still submit properly. Of course your PHP script would have to check if the form was submitted via AJAX so that it can process properly depending on the request method. An easy way to test is to check for the X-Requested-With header. If it was sent via AJAX, the value would be XMLHttpRequest.