Form submit through AJAX not working - javascript

My form will not submit through AJAX to show the return of the PHP page, 'myscript.php'.
This is the HTML I'm using:
<form name="myform" id="myform" method="post" action="#" enctype="multipart/form-data" accept-charset="utf-8" class="taxonomy-drilldown-dropdowns">
<ul>
<li>
<label>Destination:</label>
<select name="city" id="city">
<option class="level-0" value="atlanta">Atlanta</option>
<option class="level-0" value="miami">Miami</option>
</select>
</li>
</ul>
<input class="srch_btn" type="button" value="{{submit-text}}" />
</form>
Here is the javascript earlier in the page:
jQuery(document).ready(function($) {
$('#city').change(function() {
$(this).parents("form").submit();
});
$('#myform').submit(function() {
$.post(
'myscript.php',
$(this).serialize(),
function(data){
$("#mydiv").html(data)
}
);
return false;
});
});
Here is the myscript.php:
<?php
if ($_POST['city'] == "atlanta") {
echo "Div contents 1";
}
if ($_POST['city'] == "miami") {
echo "Div contents 2";
}
?>
The submit button won't respond at this point or make an attempt to access the 'myscript.php' file. Help is appreciated. Thanks in advance!

It is better to use .closest() rather than .parents() in this case.. As parents selector gets all the ancestors that match the selector.
$('#city').change(function() {
$(this).closest("form").submit();
});
And to stop the Default action use e.preventDefault instead of return false
$('#myform').submit(function(e) {
e.preventDefault();
// Your code here
});

In you HTML code, I think you should change input type=button to input type=submit
<input class="srch_btn" type="submit" value="{{submit-text}}" />
Then when you click that button, the form will be submitted to your php page.
Also, about select change event in your jQuery code, I think you can just try following selector, as you have the name/id attribute available in your HTML.
$('#city').change(function() {
$('#myform').submit();
});

One issue with your code is that it does not actually stop the form from being submitted. return false; does not exactly work in jQuery in the way that you think it does. Instead, to stop the default action, you would have to do something like this.
$('#myform').submit(function(event) {
event.preventDefault();
http://api.jquery.com/event.preventDefault/
On top of that, if you don't want the form submit to take place, and you want to replace it with your own AJAX submition, why are you calling form submit at all in this code? Why not just put the AJAX directly into your change code?

dqhendricks was right - why use form submit when you can just access ajax directly? In the below example, I added a div (#responder) below the form to show the output. Try it -- you'll see that it works perfectly.
You really don't need the button, although I left it there, because the data is sent/received the moment the drop-down is changed. You will see your messages appear in the div I included below the form.
REVISED HTML:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form name="myform" id="myform" method="post" action="#" enctype="multipart/form-data" accept-charset="utf-8" class="taxonomy-drilldown-dropdowns">
<ul>
<li>
<label>Destination:</label>
<select name="city" id="city">
<option class="level-0" value="atlanta">Atlanta</option>
<option class="level-0" value="miami">Miami</option>
</select>
</li>
</ul>
<input class="srch_btn" type="button" value="Go" />
</form>
<div id="responder"></div>
REVISED JAVASCRIPT/JQUERY:
$(document).ready(function() {
$('#city').change(function() {
//var cty = $('#city').val();
$.ajax({
type: "POST",
url: "myscript.php",
data: "city=" + $(this).val(),
success:function(data){
$('#responder').html(data);
}
});
});
});

Related

jquery - hide not working

By clicking on "empty cart?", I am unsetting the cart array which is working fine. Now I wanted another form to be hidden if this "empty cart" button is clicked.
html:
<form id="f1" action="checkout.php" method="post">
<input name="cust_login" type="submit" value="Continue" />
</form>
<br>
<button>empty cart?</button>
javascript:
<script>
$(document).ready(function(){
$("button").click(function(){
$("#f1").hide();
});
});
</script>
php code for unsetting array:
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
unset($_SESSION["cart_array"]);
But hide is not working here.
My question is, can we use button and link together as I have written ? If not, then how to implement it?
Try to use this:
$(document).ready(function(){
var cmd = '<?php echo $_GET["cmd"] ;?>' ;
if(cmd == "emptycart")
{
$("#f1").hide();
}
});
You can try
$(document).ready(function(){
$("button").click(function(){
$("#f1").attr('style','display: block !important')
});
});
or to add a class to style file that do the same and then just add this class when clicking on the button.
<form id="f1"
action="checkout.php"
style="<?= (isset($_SESSION['cart_array']) && count($_SESSION['cart_array']))? "display:none;": ""; ?>"
method="post">
<input name="cust_login" type="submit" value="Continue" />
</form>
<br>
<button>empty cart?</button>
On rendering form - check if cart is empty - render it on hidden state
But in this case your js code had no sense. So you can add
<script>
$(document).ready(function(){
$(document).on('click', "a[href='cart.php?cmd=emptycart']", function(ev){
ev.preventDefault();
$.get($(this).attr('href', function() {
$("#f1").hide();
});
});
});
</script>
Istead of your js code - this one prevent page reload ( which happens when you click on link ) and send request via AJAX
You can try this solution
HTML
<form id="f1" action="checkout.php" method="post">
<input name="cust_login" type="submit" value="Continue" />
</form>
<br>
<button>empty cart?</button>
JS
$(document).ready(function(){
$("button").click(function(){
//$("#f1").hide();
window.location.href = "cart.php?cmd=emptycart";
});
});

Submit image via AjaxForm and perform callback

I have the following function
(inside onchange; console.log works well)
$("#prof_picture").ajaxForm(
{
target: '#preview',
success: function(response){
console.log("called");
}
});
The success function is not called and therefore no feedback is received. Feedback is echoed in the following way "{message:"success",action:"something",data:Array}". Can someone help me please? Thank you very much
Here is the form
<form id="profile_picture_upload" enctype="multipart/form-data" action="profile/uploadProfilePicture.php" method="post" name="prof_picture">
<input id="profpic1" style="display:none;" name="profile_picture" type="file">
<a id="change_profile_picture" class="profile_option" onclick="$('#profpic1').click();">Upload</a>
</form>
As Quentin mentioned, the form isn't submitting.
Bind the ajax to the correct form ID instead of the name of the form
$("#profile_picture_upload").ajaxForm(
{
target: '#preview',
success: function(response){
console.log("called");
}
});
And use this html to submit the form
<form id="profile_picture_upload" enctype="multipart/form-data" action="profile/uploadProfilePicture.php" method="post" name="prof_picture">
<input id="profpic1" style="display:none;" name="profile_picture" type="file" onchange="$('#profile_picture_upload').submit();">
<a id="change_profile_picture" class="profile_option" onclick="$('#profpic1').click();">Upload</a>
</form>
though it'll click through to the next page if you do this, so you probably want to add the return false to prevent it from leaving this page.

How do I POST when a dropdown is selected then popup a jquery overlay filed with data from a sql database?

I'm trying to create a jquery overlay displaying results from a sql database. The results come from a select statement with php that was populated from the information received from an html select dropdown. Once the user has confirmed they've read, I want to update the database to reflect this and allow for the user to continue completing the original form.
I can't figure out how to submit the original form, then pop up the overlay, submit the form on the overlay, but keep the original page allowing it to be completed.
So this:
<form action="myformpage.php" method="post" id="myform">
<select id="username" onchange="this.form.submit()">
<option value='01'>User 1</option>
<option value='02'>User 2</option>
</select>
<select id="location">
<option value='north'>North</option>
<option value='south'>South</option>
</select>
<input id="subbut" type="submit" value="SUBMIT" style="display: none;" />
</form>
jquery:
<script type="text/javascript">
$(document).ready(function () {
$("#popup").overlay();
$("#confirm").click(function() {
$("#popup").overlay().close();
var dataString = 'confirmread=Y';
$.ajax({
type: "POST",
url: "read_message.php?",
data: dataString,
success: function() {
$('#location').show();
}
});
});
</script>
Oddly the submit button never works when style is set to none. (Side question: Is this because it was never visible to the browser at load?)
You'll want to do an ajax post and generate the popup (probably via jQuery UI) with a successful post:
html:
<select id="username">
<option value='01'>User 1</option>
<option value='02'>User 2</option>
</select>
jquery:
$("#username").change( function() {
$.post( "myformpage.php", {username: $(this).val()}, function( data ) {
// Create popup here
});
});
your "myformpage.php" can take care of the database stuff and return whatever you want in your popup.
You don't even have to check for it if you want to do it like this.
<?php
//your connection to db goes here
$message = "SELECT `message` FROM......";
$test="true"
?>
<script type="text/javascript">
function checkit()
{
alert("<?php $message; ?>");
}
</script>
<?php
2 options !!!
using a redirect
?>
<script>
window.location.href="your page.php";
</script>
using css to hide & show
$var="display:none;";
if($test=="true")
{
$var="";
}
?>
HTML
<div style="<?php echo $var; ?>" name="original form" >
your original form goes here
</div>
You need ajax for this, is easy with jQuery.
with jQuery you need to do something like this:
<script>
$(function(){
$("#username").change(function(){
$.post("myformpage.php",{ value : $(this).val(), function(data){
alert(data);
});
});
});
</script>
You can't style the default alert, you need to make your own dialog or use a library that can do that, like jQuery ui.
EDIT
Yes IE have problems when you submit a form from javascript without a submit button but i recommend you to dont use that way to submit because this will do a postback that you dont need.
Try something like this:
<script>
$(function(){
$("#username").change(function(){
$.post("retrievedata.php",{ username : $(this).val() },function(data){
$("#popup").html(data);
$("#popup").overlay();
});
});
$("#confirm").click(function() {
$("#popup").overlay().close();
var dataString = 'Y';
$.post("read_message.php",{confirmread:dataString},function(){
$('#location').show();
});
});
});
<script>

javascript jquery carrying html form POST data

SO I have a form that look similar to
<form action="test.php" id="checksub" method="post">
<div>
<select name="mydropdown">
<option value="buy">buy</option>
<option value="sell">sell</option>
</select>
</div>
autocomplete text input that triggers "checksub"
<input type="submit" id="checksub" name="checksub" style="visibility:hidden">
<input type="submit" id="newsbutton" name="newsbutton">
</form>
<script type="text/javascript">
$('#newbutton').click(function() {
var newaction = "cantfinditems.php";
$("#checksub").prop("action", newaction);
$('#checksub').submit();
});
</script>
Now the submit button is hidden because the autocomplete triggers it anyway, but if the user cant find what they are looking for I want a button that says "cant find what your'e looking for?"
I want this button to have a different action to the form action, ie window.location = cantfinditems.php
but I also want to carry the POST data from the form ie "mydropdown".
Thank you
Ok, so you need a second button, which calls a JavaScript function. In this function, you do a number of things:
Set the action attribute of the form to your alternate action (e.g. cantfinditems.php)
var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);
Submit the form
$('#form_id').submit();
So a full example would be:
<script type="text/javascript">
$('#yourbuttonid').click(function() {
var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);
$('#form_id').submit();
});
</script>

Multiple show/hide forms in jquery

Hello I want to have list of files in directory and a form below each of them that allows my users to name them.
That's all clear - I made it in php, but now I want to have this list and hidden forms, and when I'm clicking on one of my file's name, the form shows under the clicked name.
Something like here: http://papermashup.com/demos/jquery-sliding-div/#
Here is the code: http://papermashup.com/simple-jquery-showhide-div/
But it works in a way, that when i click on one of files, all forms shows or all hides. How to fix it to work only for clicked file?
JSFIDDLE EXAMPLE: http://jsfiddle.net/qbNrR/
#UPDATE - SIMILAR PROBLEM
Hey, I've got similar problem with submitting ajax forms - using this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
my forms are in div id=#upform and when i'm trying to submit any of them via $.ajax it submits only the first one, here's the code:
<script>
$(function() {
$(".button").click(function() {
var txt = $(".tekst#test").val();
var dataString = 'tekst=' + tekscior;
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
$('#upform').html("<div id='message'></div>");
$('#message')
.html("<h2>described!</h2>")
.append("<p>thanks!</p>")
.hide()
.fadeIn(1500, function() {
$('#message')
.append("<img id='checkmark' src='http://artivia-dev2/i/check.png' />");
});
}
});
return false;
});
});​
</script>
AND Here are my forms:
// ONLY THIS ONE IS SUBMITTED, EVEN WHEN I'M SUBMITTING THE SECOND ONE!
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
You can use the next() jQuery method. Then your code will look something like:
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(e) {
$(e.target).next(".slidingDiv").slideToggle();
});
});​
Try event.currentTarget to get the form that triggered the click event
on click event use jquery like
$(this).show(); // or hide();
as in example
$('.show_hide').click(function(){
//$(".slidingDiv").slideToggle();
$(this).slideToggle();
});

Categories