This is the code which sends data to the database. It works correctly when I filled form field and click the 'Add Record' button. It inserts the data successfully in the database.
However the main problem is that if the form field is empty and then I click the button, it sends empty data to the database.
function addRecord() {
var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form
$.ajax({
url: "ajax/EditDeleteLecture.php",
type: "post",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(output) {
alertify.set('notifier', 'delay', 3);
alertify.set('notifier', 'position', 'top-right');
alertify.success('Data Inserted Successfully');
readRecords();
$('#form1').trigger("reset");
}
});
}
you have 3 places where you can tackle empty data issue before saving to database
1- Put required attribute in your input elements so that user can not submit empty fields.
2- validate your form data in java-script function addRecord() before making ajax request. if the validation is complete send ajax call else show message to user to fill the data.
3- validate your data that you received in $_POST variable and if fields are empty, send error message back in ajax response and show error to user.
When You get form data value while you should the form field value is empty or not... or use print_r($_POST) data..
/* on submitting my form */
$( '#myform' ).submit(function() {
var errors = [];
/* else if Textarea is empty display message error */
if($('#myform textarea').val()=="") {
errors[errors.length] = 'enter your message';
}
/* if radio button is not being selected display message error */
if (!$(":radio:checked").attr('checked')) {
errors[errors.length] = 'select a radio';
}
if(errors.length > 0){
var errMsg = "Please "
for(e = 0; e < errors.length-1; e++){
errMsg += errors[e]+", ";
}
errMsg = errMsg.substr(0, errMsg.length -2)+" and "+errors[errors.length-1];
$('#errors').empty().text(errMsg);
return false;
}
/* Everthing is good display success message and add SENDING class to submit button */
else {
$('#myform :submit').addClass('sending').html('Sending message...');
$('#errors').empty().text('All Good :D');
}
return false;
});
});
Make sure to set the contentType property to "application/x-www-form-urlencoded" in order to parse this in the backend server.
Related
I have a profile page which updates the username, email, firstname and last name. I want to update and show the updated values in the same form without refreshing.
I use the below jQuery code to update the data but how can I retrieve the updated values after the submit is success
$(document).ready(function() {
$("#send").submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://localhost/form/index.php/mail/send',
type: 'POST',
data: formData,
async: false,
success: function(data) {
if (data == 'true') {
alert("success");
} else {
alert("error!");
}
},
error: function(data){
alert("Something went wrong!");
},
});
return false;
});
Try some thing like this:
from your ajax url page return an array like:
$response['errCode'] = 0;
$response['content'] = // your updated content
echo json_encode($response);
in your js code you will get it in response like:
var data = JSON.parse(response);
if(data['errCode'] == 0)
{
// update content
}
You don't have to retrieve anything from database if you have successfully updated the database. On successful update in your database you just return true or false back to ajax success point. If it returns true then just set username, email, firstname and last name to the text box by using jquery $("#email").val('abc#abc.com'); that's it!!
There is .val() method
GET $("#txtEmail").val()
SET $("#txtEmail").val("something")
Please give
return true;
statement in your jquery code after
success: function(data) {
if (data == 'true') {
//place here return true; and remove this alert statement.
}
and in your html portion,add like this on your html elements
<input name="name" id="name" value="<?php echo set_value('name'); ?>" class=" field_style-2" type="text" maxlength="20" required/>
This is just an example.you can change your html code with your own id,name and value attribute.I think this is helpful.Otherwise please share yoyur html code
After if(data == 'true') { add this below two lines.
$("#div_id").html('');
$("#div_id").html(data);
Now do three things,
1. Add the div tag before start your form. And close that div tag after close of form tag. Give the div id #div_id
2. Copy the full form code and paste below the Update SQL.
3. Change if(data == 'true') to if(data != '').
Logic:-
Using JQuery it will hit the url for update the database. Then It will load the form in the response of the jquery post. If first make the $div_id empty, then load the response data into that div id. And if the data load successfully then with out refresh the page, the updated value will display.
Note: I already use this thing in my project. And it's working fine.
If user not banned, user can comment here. So I have a php function to check banned user. In case of comment form submitting, a ajax call 1st check this user is banned or not. If not: comment will be submit else display a massage.
Here, I cannot submit any comment if banned or not, Page refresh if I try to submit. In cannot also understand how to apply my banneduser() response to check form submitting.
php function: (I dont want change it, because I used it many more case)
//user name banned by user
function Banned($user){
global $db;
if(!get_magic_quotes_gpc()){
$touser = addslashes($user);
}
$byuser = $_SESSION['user'];
$result = mysqli_query($db,"SELECT * FROM blocking WHERE byname = '$byuser' AND toname = '$touser'") or die(mysqli_error($db));
return (mysqli_num_rows($result) > 0);
}
Ajax:
// check banned user
function banneduser(){
var Bauthor = $("#author").attr("value");
$.ajax({
type: "POST",
url: "../common",
data: "action=Banned&user="+ Bauthor,
success: function(data){
// How to play with this data
if(data){
return false;
}
}
});
return false;
}
//comment submit if user not banned
$(".reply").on("click",function(){
if(banneduser()){
// make form submission
} else { // You are banned}
});
The AJAX request is asynchronous which means the rest of the code (i.e. the return false will execute before the response is processed. This means that banneduser() will always return false.
What you should do is pass a callback function to banneduser which is then executed once the AJAX response is received:
function banneduser(callback){
var Bauthor = $("#author").attr("value");
$.ajax({
type: "POST",
url: "../common",
data: "action=Banned&user="+ Bauthor,
success: function(data){
callback(data)
}
});
return false;
}
//comment submit if user not banned
$(".reply").on("click",function()
{
banneduser(function (is_banned)
{
if (is_banned)
{
// You are banned
}
else
{
// Submit form
}
}
)
});
Although, this script is easily hacked. It's trivial for a visitor (who know what he's doing) to change the value of #author until he finds a value that works. You should use a purely server-side solution to the problem (i.e. a session variable which stores the author value).
At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.
I have created a form using ajax and php. The initial load and entering values into the form are all working fine, but where I am getting errors, is after the submit button has been pressed. Here is the markup for the form, and the ajax and php handlers:
relevant parts of form:
<form id="edit_time">
<!-----form fields here----!>
<button class="saveRecurrence" type="button" onclick="editTimeDriver('.$_GET['driver_id'].')">Save</button>
ajax part:
function editTimeDriver(driver_id) {
var time = "";
if (driver_id)
{
time += "&driver_id="+driver_id;
}
var data = $("#edit_time").serialize();
$.ajax({
url: "ajax.php?action=save_driver_event"+time,
dataType: "json",
type: "post",
data: data,
beforeSend: function()
{
$(".error, .success, .notice").remove();
},
success: function(json)
{
if (json["status"]=="success")
{
alert(json["message"]);
$("#edit_time")[0].reset();
}else{
if(json["error"]["date_from"]){
$("input[name=date_from]").after("<div class="error">"+json_time["error"]["date_from"]+"</div>");
}
}
}
});
}
This then passes to the php part which is:
$json = array();
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$date_from = tep_db_prepare_input($_POST['date_from']);
if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date_from)) {
$json['error']['date_from'] = 'Start Date is not valid!';
}
if (isset($json['error']) and !empty($json['error'])){
$json['status'] = 'error';
$json['message'] = 'Please check your error(s)!';
}else{
$json['status'] = 'success';
$json['message'] = 'Time Data has been successfully updated!';
}
}
echo json_encode($json);
Now for some reason, if the date_from field is left blank, and the form submitted, it doesn't come back with error message, instead it returns the success message. Can anyone tell me why it is not reading the errors?
Change your code by this one
onclick="editTimeDriver('<php echo $_GET['driver_id'] ?>'); return false;"
The return false statement prevent the form to be submitted using http (as you want to send an ajax request)
And You where doing something weird with your $_GET['driver_id']
Don't forget that php is running server-side
I wonder whether someone may be able to help me please.
Firstly, my apologies, I'm relatively new to JavaScript and jQuery, so perhaps this is a really stupid question.
Using these tutorials here and here I've put together this page to allow users to add records to a MySQL database but I'm having a little difficulty with the form 'validation' and jQuery 'submission' message.
If use select the above link, then once the page has loaded, select 'Save', you'll see that the correct field validation is activated, but despite being validation errors, the 'Location saved' message appears at the bottom of the page, and the page refreshes saving the record to the database.
Obviously this is not supposed to happen, but I'm having great difficulty in joining the 'validation' and 'submission' message. Independently they work fine, but as you can see, once together they don't.
The code below deals with the 'Save Record' and refresh of the page
UPDATE - Working Solution Below
<script>
jQuery(document).ready(function(){
jQuery("#addlocation").validationEngine();
$("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#saverecordresponse');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
});
</script>
and this is the 'saverecord.php' script which is called upon selecting the 'Save' button.
<?php
//sanitize data
$userid = mysql_real_escape_string($_POST['userid']);
$locationname = mysql_real_escape_string($_POST['locationname']);
$returnedaddress = mysql_real_escape_string($_POST['returnedaddress']);
//validate email address - check if input was empty
if(empty($locationname)){
$status = "error";
$message = "You didn't enter a name for this location!";
}
else if(!preg_match('/^$|^[A-Za-z0-9 _.,]{5,35}$/', $locationname)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid Location Name!";
}
else{
$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");
if($query){ //if insert is successful
$status = "success";
$message = "Location Saved!";
}
else { //if insert fails
$status = "error";
$message = "I'm sorry, there has been a technical error! Please try again. If problems persist please contact Map My Finds support.";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
I just wondered whether someone could possibly take a look at this please and let me know where I'm going wrong.
Many thanks and kind regards
I believe you need:
if($.validationEngine.submitForm(this,settings) == true) {return false;}
somewhere before your $.ajax line
IRHM, check that the form is validate before submit in your event i.e.
$('#addlocation').submit(function(){
if($(this).validate()){
// put your all existing content here.
}
});
To prevent submitting the form after ajax put return false at the end of above script in if block i.e.
if($(this).validate()){
// put your all existing content here.
return false;
}
I guess the problem is occurring due to validation engine, so in that case to prevent form to submit try to use as follows:
$('#addlocation').submit(function(evt){
if($(this).validate()){
evt.preventDefault();
// put your all existing content here.
}
});
If the above code doesn't work then include onValidationComplete event with validationEngine and put you all existing stuff of if($(this).validate()) block in that i.e.
jQuery(document).ready(function(){
// binds form submission and fields to the validation engine
jQuery("#addlocation").validationEngine({ onValidationComplete: function(){
//setup variables
//add status data to form
//show response message - waiting
//send data to server for validation
return false;
}
});
});
Good Luck
After several days of working on this, I now have a working solution by using the example here which I've added to my original post.