I dont get it... I reviewed my code hundred times and I dont get the error...
I am actually testing a bit with JQuery and AJAX and made a simple form with a textarea to submit. Without AJAX it works fine, but with, it sends always an empty value of my textarea...
The Javascript Code:
$(document).ready(function(e) {
$("#formPost input").attr("disabled", false);
$("#formPost input:submit").click(function() {
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: $('#formPost').serialize(),
beforeSend: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", true);
$("#formPost .ajaxloader").show();
},
success: function(data) {
var message = $("#flashMessage");
message.text(data.msg);
if(data.error) {
message.addClass("fail");
}
else {
message.addClass("success");
}
message.show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#formPost .ajaxloader').hide();
$('#flashMessage').removeClass().
addClass('fail').text('There was an error.').show();
},
complete: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", false);
$("#formPost .ajaxloader").hide();
}
});
return false;
});
});
The HTML:
<div>
<h1>Add new post</h1>
<div id="flashMessage"></div>
<form id="formPost" method="post" action="post.php">
<textarea id="post" name="post"></textarea>
<input type="submit" value="Save" />
<div class="ajaxloader">
<img src="ajax-loader.gif" />
</div>
<div class="clear"></div>
</form>
</div>
I use Firebug and look under "Network" -> "XHR" -> "Post" and under Source he shows post=
So where is the value gone?
Your problem is related with CKEditor (as you said in the comment), because WYSIWYG editors replace the appearance of textarea and update value on form submit. So you have to use built-in functions of CKEditor for updating textarea's value manually as you are using Ajax. I can't help you specifically with CKEditor but this thread may help: CKEditor, AJAX Save .
You are disabling the form elements in the beforeSend method, but JQuery's serialize will ignore those disabled elements. Try removing that first to test. This SO question has some ways to get around it.
Related
I want to use the jquery-modal plugin to make comments for several form elements. Its working fine, as long there is no keyboard input. Otherwise it remembers the last input and keeps that in the textarea, even if I empty it before.
This is the form that is shown in the modal window.
<a title="" href="#" onclick="getRechKomm('12345'); return false;" class="edit_komm">Kommentar</a>
<form id="RechKommForm" class="none">
<h3></h3>
<p><textarea name="kommentar" id="ptrRechKomm"></textarea></p>
<p><input type="hidden" name="rechid" id="ptrRechKommID" value=""></p>
</form>
<script>
function getRechKomm(rechnr){
$('#ptrRechKomm').html('');
$.ajax({
type: "POST",
url: "ptr_getrechkomm.php",
data: {rechnr: rechnr},
success: function(data){
readSession();
$('#ptrRechKomm').html(data);
$('#ptrRechKommID').val(rechnr);
$('#RechKommForm').modal({
escapeClose:false,
clickClose: false,
fadeDuration:500
});
}
});
}
$('#RechKommForm').on($.modal.BEFORE_CLOSE, function(event, modal) {
$.ajax({
type: 'POST',
url: 'ptr_putrechkomm.php',
cache: false,
data: $("#RechKommForm").serialize(),
success: function (data) {
$('#ptrRechKomm').html('');
$('#ptrRechKommID').val('');
}
});
});
</script>
So if call the comment for the ID 12345 and write a comment "Komm 12345", everything is fine. After that I call the comment for ID 23456, that may be already "Komm 23456". It is loaded from the database and put into the textarea #ptrRechKomm, but the first text is still there. So in the textarea is "Komm 12345Komm 23456".
Where is the old content coming from and how to delete it?
Update: Forget that all! Don't know why, but I thought that a textarea has to be filled by html(). Thats working, but only once. Filling it by val() is the correct way!
So here is the scenario:
I have HTML, JS, and PHP Files. Within the PHP File is an associative array of default values to fill out various form elements on the HTML file. I am attempting to use AJAX to take the files from the PHP Files, and put them in the corresponding form elements. However nothing is working.....
Below is the code for the corresponding files. Any help figuring this out is greatly appreciated :)
HTML
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
PHP
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
}
?>
JAVASCRIPT
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$.post('backend.phps',
{ act: 'default' },
function(data) {
for (var key in data) {
document.getElementById(key).value = data[key] }
},
'json');
// prevents link click default behaviour
return false;
});
});
As a side note, I always have trouble with web development stuff because I have no idea how to properly debug what I am doing. If anyone has any tips on what are some useful tricks/tools to use for debugging web code, I'd be more than happy to get some input on that too.
Thanks for your time.
For ajax code request use:
$("#InsertDefault").click(function(){
$.ajax({
type: "POST",
url: "backend.phps",
data: "act=default&name=test&phone=test", //Something like this
success: funtion(msg){
console.log(msg);
},
beforeSend:function(dd){
console.log(dd)
}
});
});
and in your backend.php file
if ($_REQUEST['act'] == 'default'){
//echo $_REQUEST['name'];
}
And for simple debugging use browsers' console, right click on the page and click Inspect Element. (Simple)
You can also install Firebug extension on Mozilla Firefox and then right click on the page and click on inspect Element with firebug. after this click on the Console tab there.
These are the basic and simple debugging for simple ajax request.
Per the newest Ajax documentation your ajax should include the Success and Failure callbacks where you can handle the response being sent from your PHP.
This should work with you existing PHP file.
Ajax
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#InsertDefault', function (event) {
$.ajax({
url: "/backend.phps",
type: 'POST',
cache: false,
data: {act: 'default'},
dataType: 'json',
success: function (output, text, error)
{
for (var key in output.defaultData) {
document.getElementById(key).value = data[key]
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
preventDefault(event);
});
I have a form that contains an input with type="image" attribute. I am changing the image everytime whether I get a success or fail call.
But It doesn't work always, I don't see why. Is there any possible way to eliminate setTimeout(function()) or alternative way to implement this animation since this may cause the problem?
HTML
<p class="text-center" style="color:brown" id="input_result">Send</p>
<form data-ajax="false" method="post" name="login_form" role="form">
<div class="form-group">
<input type="image" src="images/default.png" class="img-responsive center-block" name="submit" class="submitBtn" id="input_img">
</div>
</form>
Script
<script>
$('form').bind('submit', function() {
$.ajax({
type: 'POST',
url: 'includes/sendmail.php',
data: $(this).serialize(),
cache: false,
dataType: 'text',
success: function(data, status, xhttp) {
$("#input_img").slideUp(2000).slideDown(1000);
setTimeout(function() {
// Success animation
$('#input_img').attr("src", "images/success.png");
jQuery("input[type='image']").prop("disabled", true);
$('selector').click(false);
$("#input_result").text("Sent!");
$("#input_result").css("color", "green");
}, 1999);
this.submit();
},
error: function(jqXHR, textStatus, errorThrown) {
$("#input_img").slideUp(2000).slideDown(1000);
setTimeout(function() {
// Fail animation
$('#input_img').attr("src", "images/fail.png");
jQuery("input[type='image']").prop("disabled", true);
$('selector').click(false);
$("#input_result").text("Failed to send!");
$("#input_result").css("color", "red");
}, 1999);
},
});
return false;
})
</script>
When you submit the form using this.submit(); the page is submitted to the server and reloaded again, so you lose the success animation. Since you are posting the values in the function, you don't need to submit the form.
Instead of $("#input_img").slideUp(2000).slideDown(1000); you can use the callback of slideUp to run your function and then in the end of that function call .slideDown()
Like:
$("#input_img").slideUp(2000, function(){
$('#input_img').attr("src", "images/fail.png");
jQuery("input[type='image']").prop("disabled", true);
$('selector').click(false);
$("#input_result").text("Failed to send!");
$("#input_result").css("color", "red");
$("#input_img").slideDown(1000);
}
what's up guys? look... I have a comment system for my web page... and I've been dealing with this little problem for a entire week. I really need some help here x_x ... the thing is that when a user leave a comment on my page, this comment is showed automatically thanks to ajax, that's ok...
each comment can be voted. and here's my problem... these divs that contain the forms for voting are build dynamically and the thing is that when I do click on the button for sending the form in any comment... the resulting data appears in all the comments! instead of appear in the specific one where the submit button was clicked, so I don't know what to do at this point, I hope you can give me a hand. this is my code
the form:
<label > Vote </label>
<form action="vote.php" method="POST" class="form-vote" id="form-vote">
<button class="icon-thumbs-up" id="icon-thumbs-up"></button>
<input hidden="hidden" type="text" name="num-comment" id="num-comment" value="'.$d['id'].'" >
<input hidden="hidden" type="text" name="point" id="point" value="'.$d['point'].'" >
<p id="actual-points" class="actual-points"> '.$d['point'].'</p>
<div id="result" class="result"> </div>
</form>
the script:
<script type="text/javascript">
$(document).ready function() {
$('.form-vote')on('submit', function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('.actual-points').hide();
$('.result').html(data).fadeIn('slow');
}
})
return false;
});
})
</script>
Have you tried saving the 'this' object of the original event and using it inside the success function like this:
$('.form-vote')on('submit', function(e) {
e.preventDefault();
var $form = $(this); // Save here
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// use here
$form.find('.actual-points').hide();
$form.find('.result').html(data).fadeIn('slow');
}
})
return false;
});
change this:
$('.result').html(data).fadeIn('slow');
to this:
$(this).find('.result').html(data).fadeIn('slow');
So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after doubleĀ“s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.ajax.