Jeed Jeed - 6 months ago 20
jQuery Question

Jquery Ajax form select change div fadeout error

i'm a new user of ajax and i have a little problem on div function.

Here is my code :

$(document).ready(function() {
$('select.age').change(function(){
$.ajax({
type: 'POST',
url: 'change_age.php',
data: {selectage: $('select.age').val(), projectId: $('input[name$="projectId"]').val()},
dataType: 'html',
success: function()
{
$("#msg_age").html('<span style="color: #00BB00;">Changement OK</span>').fadeOut(4000);
}
});
});
});


My form page test.php

<form action="#" method="post">
<label for="age">Votre Age</label>
<select class="age" name="age">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
</select>
<input class="projectId" type="hidden" name="projectId" value="1"/>
<div id="msg_age"></div>
</form>


My change_age.php

<?php
$query=mysql_connect("localhost","user","pass");
mysql_select_db('database',$query);
$selectage=$_POST['selectage'];
$id=$_POST['projectId'];
$sql='UPDATE tests SET name="'.$selectage.'" WHERE id="'.$id.'"';
mysql_query($sql) or die("Error: ".mysql_error());
?>


When i go on my form for 1st time, i change an option the changement is ok, i wait 4 seconds the div fadeout.
When i select another select, nothing appear, i must to refresh the page ..
I wanted to show again the message with the fadeout if another select is selected.

Someone have an idea ?

Thanks a lot :)

Answer

In this case I would create span for notifications in your template, give it own id, and .fadeIn()/.fadeOut() it when it's needed.

Less DOM manipulations and better performance.

So, your code will be like :

...
success: function() {
  $("#msg_age").fadeIn(150).fadeOut(4000);  
}

Next, long-time fading out don't look friendly, I would better use .delay() for that

...
success: function() {
  $("#msg_age").fadeIn().delay(4000).fadeOut();  
}
Comments