I use niceEdit as a html editor and a mysql for back end. The process I will send the data into a php using AJAX.
Heres my html code:
<div class='atabcontent'>
<form id='apostform' method='POST'>
<input name='request' type='hidden' value='atabaddnew' />
<textarea id='aposttextarea' name='area1' style='width:780px; height: 400px; margin: 10px auto 0 auto;'cols='40'></textarea>
<div style='height: 5px;'></div>
<button id='apostsubmit'>Save</button>
</form>
</div>
and heres the ajax code.
$("#apostform").submit( function () {
//add a loading bar first
$('div.atabcontent').append("<img class='loading' src='media/loading.gif' />");
//send data to processor.php
$.post(
'processor.php',
$(this).serialize(),
//here, where we're going to manage the respond from the processor.php
function(data){
//remove the loading bar
$('.atabcontent img.loading').remove();
//output the respond
$('div.atabcontent').html(data).show();
});
return false;
});
and heres the php file (processor.php).
<? //this a processor e.g. post, delete, edit etc..
//check if a post "request" is present..
if (isset($_POST['request']))
{
//check if what type of request, if request type is equal to atabmenu then..
if ($_POST['request'] === "atabmenu")
{
echo $_POST['data'];
}
elseif ($_POST['request'] === "atabaddnew")
{
echo htmlspecialchars($_POST['area1']);
}
//end
//else if no request then go to fail.php along with the error code of "unable to process the data"
}
else
{
header("location: fail.php?error=unable to process the data");
}
?>
as you can see on the above code, it should work fine, but the respond from the php file that has been fetch by the ajax respond handler is empty and seems like there is no data that has been sent or neither has been received also i tried this
$("#apostform").submit( function () {
var data = $('#apostform textarea').val();
alert (data);
return false;
});
but there the alertbox content is empty and as you can see in the code, it should alert a box with the value of the "#apostform". I tried a normal form, i mean no ajax and its work fine because i can see the data has been receive because it display the data receive from the form.
hope someone could help me on pointing out on what seems the problem on this. anyway i use niceEdit textbox http://nicedit.com/
PS: im open in any suggestion, recommendation and idea. Thanks in advance.
Your submit function seems to have a few syntax errors in it
$("#apostform").submit( function () {
var data = $('#apostform textarea').val(); // missing equals sign and closing apostrophe
alert (data);
return false;
});
Related
I've had a look around and unfortunately the solutions I've found on the site don't appear to address my issue below.
Basically I'm doing a project where I need to effectively set up a diary - the user writes in a textarea element and this is passed via PHP to a database and stored for the user. In the lecturer's video, it appears he's doing without using a submit button (even if he's not, I think it'd be an interesting thing to learn how to do).
I'm having some issues though. Here's my PHP:
<?php
session_start();
if(array_key_exists("id", $_COOKIE)) {
$_SESSION['id'] = $_COOKIE['id'];
}
if(array_key_exists("id",$_SESSION)) {
echo "Logged in: <p><a href='secretDiaryFinal2.php?logout=1'>
Log out</a></p>";
} else {
header("Location: secretDiaryFinal2.php");
}
/* I'm putting in the database update later, for now I just wanted to check if I could
actually create the POST variable below*/
$msg = "";
if(array_key_exists('diaryEntry',$_POST)) {
$msg = $_POST['diaryEntry'];
} else {
$msg = "Some kind of PHP error";
}
?>
The relevant HTML:
<body>
<div id="testDiv">
<? echo $msg ?>
</div>
<div class="container" id="diaryArea">
<form method="post">
<textarea id="diary" value=""></textarea>
</form>
</div>
The relevant JQuery (I'm very weak on Ajax and I suspect there's a lot of issues here - also note the url I'm using is actually in the same script as the JQuery, I'm not certain if that works?) is below.
The basic idea is that every time the user types, the database should be updated (I realise this is a lot of calls to the server, I'll probably replace it with a timed command):
<script type="text/javascript">
$("#diary").keyup(function () {
var dataString = $("#diary").val();
$.ajax({
type: "POST",
url: "loggedInPageFinal.php",
data: ({diaryEntry:dataString}),
success: function(data) {
console.log(data);
}
});
return false;
});
</script>
Many thanks in advance and apologies for my poor code!
var DataString = $("#diary").val();
$.post( "loggedInPageFinal.php",{dataString:DataString }, function( data ) {
console.log(data);
});
Your ajax script actually does work.
But your php code isn't returning anything. put exit($msg); at the end of the code and see what happens.
In this basic jQuery, AJAX, PHP form I want to display errors next to inputs instead of the bottom of the form. I use if(empty(something)) { jQuery here }. Why won't this work? Whats the best practice to do this? Thank you.
HTML:
Name:<input type="text" id="name" /> <span id="name_error"></span>
<input type="button" value="Update!" id="update" /> <span id="name_error"></span>
<span id="update_status"></span>
PHP
<?php
include('init.inc.php');
if(isset($_POST['name'])) {
$name = mysql_real_escape_string(htmlentities($_POST['name']));
if(empty($name)) {
?>
// Why wont this work here? It just outputs the the whole thing as text. in the update_status div (You can see that in the ajax part at the bottom of the code).
<script>
$('#name_error').text('Name required');
</script>
<?php
if(!empty($name)) {
$query = mysql_query("UPDATE users SET
name = '$name'
WHERE user_id = ".$_SESSION['user_id']."
");
if($query === true) {
echo 'Your settings have been saved';
} else if($query === false) {
echo 'Unable to save your settings';
}
}
}
// This is the jQuery / AJAX part -- no issues here. Just have it to include both parts.
$('#update').click(function() {
var name = $('#name').val();
$('#update_status').text('Loading...');
$.ajax({
type: 'POST',
url: 'page.php',
data: 'name='+name,
success: function(data) {
$('#update_status').text(data);
}
});
});
CODE UPDATED
Why aren't you checking for empty before the form submit?
You can stop the form submission and check for empty values with javascript, if all is clear then you can submit the form.
You can do this, but you are specifiying .text()
What you need to do is jQuery("#update_status").html(data);
jQuery("#update").click( function(){
if(jQuery.trim(jQuery("#name").val()) == ''){ alert("empty"); return false; }
jQuery.post("page.php", {name:jQuery("#name").val()}, function(html){
jQuery("#update_status").html(html);
});
});
Note that you PHP page is going to return more than just your intended code as it is now. It is going to try and return the form again also.
You need to wrap your processing and from in separate if/else statement. Better to put them in two separate files and keep ajax stuff separate.
That's a really bad way to do it. The reason it doesn't work is because that JavaScript needs to be parsed and run by the browser first, that's a whole different story and would involve using eval(). The better way to do it would be to send back a JSON object, then use it in your JavaScript to display the message to the user.
I want to check the value enter in the form by user. i have applied validation and its working. The problem is that if user enter any form value incorrectly and then clicks submit, the whole page is refreshed and all input data is lost.
I want that validations is checked before passing it to server. One of my friends told me its possible with AJAX. Can anyone guide a beginner on how to do this?
You can use javascript instead and save the server from transferring some extra KBs and calculations by using Ajax (which technically is javascript but you send the request back to the server)
Jquery has a plugin called validation that will make your life easier though:
http://docs.jquery.com/Plugins/validation
There is a live demo in the link above
For example if you wanted to validate the username you could do this
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
</script>
<form id="commentForm">
<input id="uname" name="name" class="required" />
</form>
yes you can use ajax or otherwise with your current approach you can use sessions to store user data and prevent it from being lost. with ajax you can show response from the server to show to the user.
$.ajax({
url: 'ajax_login.php',
type:'post'.
data:(/*data from form, like,*/ id: $('#username').val())
success: function( data ) {
if(data == 1) {
$('.feedback').html('data has been saved successfully');
//redirect to another page
}
else {
$('.feedback').html('data could not be saved');
$('.errors').html(data);
}
}
});
ajax_login.php would be something like
<?php
if(isset($_POST)) {
//do form validation if it is valid
if(form is valid) {
saveData();
echo 1;
}
else {
echo $errors;
}
}
?>
Do not need ajax.
Just set the onsubmit attribute of your form to "return checkfun();" and define checkfun some way like this:
function checkfun()
{
if ( all things were checked and no problem to submit)
return true;
else
{
alert('ERROR!');
return false;
}
}
I have a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:
delete.php
<?php
if (isset($_POST['id'])) {
if (unlink($_POST['id'])) {
echo "success";
}
else {
echo "failure";
}
}
?>
(There's already user authentication in place just to get them to the page that calls delete.php.)
Here's the html of one displayed image - there can be up to 5 of these chunks one after another:
<div class="box">
<img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" />
<h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5>
<a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
<div class="clear"></div>
</div>
My jQuery so far looks like this:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(data){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?
Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case
success: function(data){
/*The code you need*/
});
The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.
Hope this helps a bit.
Edit Note:
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.
This is the php that executes:
if ( !$db->isGlobal($id_css)){
$data['id_poll'] = $id_poll;
$data['id_css'] = $id_css;
$data['css'] = $css;
$db->applyCssChanges($data);
}
else{
echo 'invalid';
}
You've two obvious options I can think of:
Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:
Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.
From delete.php return whether the delete succeeded or not. In the success even check for that data and handle it appropriately.
HTH.
I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the
$(document).ready(function(){
But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js
$(document).ready(function(){
$('#AddCaller').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var Firstname = $('#Firstname').val();
...OTHER FORM FIELDS HERE
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut. */
if(Firstname.length == 0){
var error = true;
$('#Firstname_error').fadeIn(500);
}else{
$('#Firstname_error').fadeOut(500);
}
if(Lastname.length == 0){
var error = true;
$('#Lastname_error').fadeIn(500);
}else{
$('#Lastname_error').fadeOut(500);
}
...MORE CONDITIONAL STATEMENTS HERE
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'added'){
//$('#cf_submit_p').remove();
//and show the success div with fadeIn
$('#Add_success').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
document.getElementById('Firstname').value = "";
document.getElementById('Lastname').value = "";
document.getElementById('PhoneNumber').value = "";
document.getElementById('DefaultETA').value = "";
document.getElementById('Apparatus').value = "";
document.getElementById('DefaultLocation').value = "";
setTimeout(" $('#Add_success').fadeOut(500);",5000);
}else if(result == 'alreadythere'){
//checks database to see if the user is already there
$('#Alreadythere').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
}
else{
//show the failed div
$('#Add_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.
Thanks for the help!
EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.
EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.
<form action='addcallers.php' method='post' id='AddCaller_form'>
<h2>Add Callers</h2>
<p>
First Name:
<div id='Firstname_error' class='error'> Please Enter a First Name</div>
<div><input type='text' name='Firstname' id='Firstname'></div>
</p>
<p>
Last Name:
<div id='Lastname_error' class='error'> Please Enter a Last Name</div>
<div><input type='text' name='Lastname' id='Lastname'></div>
</p>
...MORE FORM FIELDS HERE
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly >
</div>
</p>
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
<p id='cf_submit_p'>
<input type='submit' id='AddCaller' value='Send The Message'>
</p>
</form>
</div>
EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.
EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it
EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?
most likely, it's the #DefaultLocation field, since it's a read only and you are resetting it after the first post:
document.getElementById('DefaultLocation').value = "";
And never changing it's value back to something (or are you?)
so you have to do one of the following:
don't reset it
set it's value with something after posing the form
don't validate it at all since it's a read only and you are using it as a hidden input (which is wrong by the way)!
also, it can be the other "ajax" code you are talking about so please post that too here, also maybe you have other fields (elements) somewhere else on the page with same IDs like the ones in the form..
anyway, here are sometips for you:
1- close the input tags correctly (add / to the end of it):
<input type='text' name='Firstname' id='Firstname' />
2- make sure all DIVs and Ps are closed...as it seems that you have an open P here:
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
</p> <---- missing this one
<p id='cf_submit_p'>
3- you are redeclaring the error variable all the time, you don't need to do that:
if(Firstname.length == 0){
var error = true;
....
just use error = true; without var this applies on all places you are changing its value only use var on initialization:
var error = false;
4- instead of this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
use:
$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });
5- if you are using DefaultLocation as a hidden field then instead of this:
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly />
</div>
use:
<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />
Try to change from using the click event handler to the form's submit event handler
Change this : $('#AddCaller').click
To this : $('#AddCaller_form').submit
Do not remove the attribute of disabled, set it to false.
This line
$('#AddCaller').removeAttr('disabled').attr(...
should be
$('#AddCaller').attr('disabled', false).attr(...
I assume that by removing and adding attributes, the element is removed and replaced by the new one, but the handler is not re-attached. Try using $('#AddCaller').live('click', function(){ //code }) instead of .click()
This function send queries to php and can return results from the php file using ajax.
I have left comments for guide. the first part with try & catch statements does not need modifications. go to #1 and #2
function ajaxFunction(){
var ajaxRequest;
//Browser compatible. keep it as it is
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//Browser compatible end
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//#2 opional: create functions to return data from your php file
$('#resultArea').html(ajaxRequest.responseText);
}
}
//#1 Set the form method, filename & query here here
ajaxRequest.open("GET", "serverTime.php?query=something", true);
ajaxRequest.send(null);
}
example:
<input type='submit' value='ajax-submit' onclick='ajaxFunction()' />
quick jquery plugin for that since you might use this in almost every ajax form on your site:
it will disable all fields that could trigger a submit event and also add a class on the form tag so that you can apply some styling, or showing a load message when the form is submitted:
jQuery.extend(jQuery.fn, {
formToggle: function (enable){
return this.each(function(){
jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
.find(':input').attr('disabled', !enable);
},
enable: function(){ return this.formToggle(true); },
disable: function(){ return this.formToggle(false); }
}
then on your jq ajax code:
[...]
var $form = $(your_form).submit(function(){
$.ajax({
type: 'post',
url: "/whatever/",
data: $form.serialize(),
success: function (){ alert ('yay');},
complete: function(){ $form.enable();},
error: function(){ alert('insert coin')}
}
$form.disable();
return false;
});
It should be enough to properly block the submits while the forms is sending/receiving data.
If you are really paranoid you can add a check so that it cannot be sent twice between the moment the user triggers the submit and the fields get disabled with : if ($form.is('.disabled')) return false; as first line of the submit handler, but it shouldn t be necessary really
Set some breakpoints in Firebug and watch if it goes somewhere.
Button can lose its click handler after submit and applying effects. You probably need to assign click handler again after submit and stuff.
Not 100% on this but try setting the code as a separate function then rebinding the click event at the end.
Example:
function addCaller(e) {
// your unchanged code
$('#AddCaller').click(addCaller(e));
}
$(document).ready(function(){
// added an unbind just in case
$('#AddCaller').unbind('click').click(addCaller(e));
});
Try to change this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
into that:
$('#AddCaller').attr({'value' : 'Adding...' });
This should make it work.