I am trying to submit without reloading using AJAX, but when I press the Submit Button and no records are insert, however it prints out that All records are Submitted. Any Idea
<?php echo validation_errors(); ?>
<?php echo form_open('', 'class="form-horizontal" id="myForm"'); ?>
<div class="form-group">
<label for="note_text" class="col-sm-1 control-label">Note</label>
<div class="col-sm-10">
<textarea class="form-control" name="note_text" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-default">Post</button>
</div>
</div>
<div class="buttons"> <span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
</form>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000); //=== Show Success Message==
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
</script>
Also can someone point me to a tutorial about how to do LIVE UPDATE. I mean this function for example is in index() where is also my loop for all the notes and what I am searching for is as soon as I submit it and immediately the new record of notes to be shown below. Something like Facebook posting
I think the issue is in your server side code, it's returning a HTTP 200 response so the $.ajax function thinks it succeeded but actually it didn't. This might happen if you're catching the error and outputting a message, but not throwing say a 500 error.
If you have google chrome press F12 to bring up developer tools > Go to network > Press submit and a new entry should appear in the list > click on that entry. Take note of the "Status Code" in the headers tab, and the output in the response tab.
If that doesn't return what you'd expect (ie. non-200 when the update fails and the correct response) then you should start debugging your server side code.
Related
I would like to do a web site using Aptana IDE and xampp, and it has a few pages. Index page is where all users which does not log in the system and home is where all users which does log in the system must visit. I am very new to develop web site. Because of that I am changing a lot of and vital things during the development. An here my problem is began.
I have created log and sign pages separately using HTML5, CSS, Javascript, JQuery and Php. To achieve more quality service, decided to use also Ajax. These pages works correctly, log page can control validation with jquery
$('#login-form').validate({
//validation rules, messages and submitHandler(ajax code) goes here});
and with using ajax, it can communicate with php file and mysql database so can check whether the user is exist or not.
$.ajax({
type: 'POST',
url: 'log.php',
data: strAjax, //username and password
success: function(data) { //data is echoing from php file either as true or false
if(data) {
window.location.href = "home.php";
}
else {
//some error messages
}
}
});
Sign systems works like it and correctly. But I do not like the design of these pages because of emptiness. So in index file when user click log in button, the log file is showing inside a div with jquery load function.
$(".jumbotron").load("login.html").hide().fadeIn(1500).delay(5000);
Same thing for sign system as well. For good looking, I am satisfied but...
The whole system messed up. (I want to cry) I have to think before start to coding web site, very bad I know but this is my first complete web site. How can achieve a system working properly in this way? I have searched some pages on the internet and they said that the ajax can not work across the pages or something like that. I am also new to stack overflow too, so some important thing will be forgotten. I can edit if you want more information.
Thank You and Regards...
EDIT 1:
<div class="jumbotron">
<div class="container">
<h1>//sometext</h1>
<p>//some text</p>
</div>
</div>
Firstly this is showing on the screen. And when the user press login button, jquery load function running which is above. And loads login.html which works properly by itself.
<form id="login-form" class="text-left">
<div class="form-group">
<label for="lg_username" class="sr-only">Username</label>
<input type="text" class="form-control" id="lg_username" name="username" placeholder="username"
data-container="body" data-toggle="popover" data-placement="left" data-content=""
value="">
</div>
<div class="form-group">
<label for="lg_password" class="sr-only">Password</label>
<input type="password" class="form-control" id="lg_password" name="password" placeholder="password"
data-container="body" data-toggle="popover" data-placement="left" data-content="">
</div>
<div class="form-group login-group-checkbox">
<input type="checkbox" id="lg_remember" name="lg_remember">
<label for="lg_remember">remember</label>
</div>
<button type="submit" class="login-button">Submit</button>
</form>
The jquery validation works right. My rules are valid. If the inputs are ok upon my rules, it send me to home.php. I think ajax code can not work.
submitHandler: function() {
var username = $('#lg_username').val();
var password = $('#lg_password').val();
var checkbox = $('#lg_remember').is(":checked");
var strAjax = "username=" + username + "&password=" + password + "&checkbox=" + checkbox;
$.ajax({
type: 'POST',
url: 'logDeneme.php',
data: strAjax,
cache: false,
success: function(data) {
if(data) {
window.location.href = "home.php";
}
else {
//error message. but when this code run, always send to home page.
}
}
});
return false;
}
This parts all works. It does not works inside index.php. My question is why and how to handle this!
Problem 1
Your form is submitting via a GET request because the JS is not getting called (see #2 below) and the HTML is likely declared like this:
<form action='log.php'>
[...]
</form>
You must specify method='post' to submit POST data.
Problem 2
Unless you're using a jQuery plugin there is no .validate event for forms. You want to use .submit.
Finally, make sure all your javascript is in $(document).ready(function() { ... }); or it won't execute at the right time. Look in the Firefox/Chrome developer console, it's a lifesaver for debugging.
Im very new to Ajax and Jquery and learning through SO and online tutorials so please keep in mind im a rookie should you read and be kind enough to answer my post.
I have managed to create the following which is a form that displays a message on submit. If form was successfully submitted a message is displayed without page refreshing as you can see in image below:
FORM
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
What I want to do
Retrieve the value from text field message and assign it to php variable
My problem
When I try to retrieve the value of message with the following code, nothing happens:
PHP code below form
<?php
if(isset($_POST['contact'])){
$message = $_POST['msg'];
echo $message;
}
?>
Im very new to Ajax so I guess I am doing something wrong here, unfortunately I dont know where I am going wrong so I am hoping someone can put me on the right path here.
Thanks in advance
Hanoncs suggestion will work, but keeping things only browser side (by displaying the message only from form to div), will always give the user the impression that message is send (processed) server-side, while it is not always the case, one would make php return it before displaying it with javascript. So here is another approach I suggest:
First, Make a Separation of concerns: Sending a POST HTTP Request to the same current page contardicts somehow the purpose of AJAX. The HTTP Response will contain all the page ( the HTML rendred by PHP, the embeded HTML used for templating, and maybe the script if it is not joined in a script tag). Instead, I suggest you create a small separate php file that is responsible for rendereing only the needed markup. And so, instead of using $.post(document.location.url.., one would use $.post('pathToSmallPHPFile'..
Second, let jQuery AJAX functions accept callbacks or use promises. I suggest you carefully read the following link.
The issue is that you are using ajax, which does not cause a page refresh, and then trying to echo out the posted variable, since there is no page refresh, php will not process the page again to echo the posted variable.
My solution is to use javascript to display the text entered and then database it using php.
Here is an example,
$(document).ready(function () {
$(".button").click(function () {
$('p').text($('#msg').val());
});
});
http://jsfiddle.net/r4nanmof/ you dont need ajax if all you want to do is display it on the page. If you plan on saving in the database then ajax is required.
Jquery Code for posting the message value to the php file is given below:
$('#contact_btn').click(function(event){
event.preventDefault();
var url = "url/of/the/php/page/where/to/process/data";
var data = $("#msg_box").val();
var wrapper = $('#wrapper');
$.ajax({
type: "POST",
url: url,
data: data,
success: function(response){
wrapper.html("The reponse from the page is " + response);
},
error: function(xhr,status,msg){
//Handle error here
}
});
});
<code>
<div id="wrapper">
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" id="msg_box" value="" /><br />
<input type="submit" id="contact_btn" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
</div>
</code>
Message
Thank You We will Get Back to you
Ooops....Something Went Wrong
Its not necessary in your case but change method"post"> to method="post">
And change your Form
<form name="message-form" action="" id="contact-form" method="""post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none"> </div>
And use the following jQuery code to post your data
$(function () {
$("#contact-form").submit(function (e) {
e.preventDefault();
$form = $(this);
$.post(
document.location.url,
$(this).serialize(),
function (data) {
$(".form-feedback").html("Your msge " + data + " is recieved and we will get back soon");
$(".form-feedback").show();
})
});
});
Im learning Jquery and AJAX on my own through online tutorials and by posting on SO when I gets stuck, so please keep in mind I am a novice should you be so kind to answer my question.
I have a form inside a modalbox. Ajax prevents it from closing/reloading and a message gets displayed after submission as you can see in image below:
My problem
Both the success and failure messages gets displayed. I would like to change this so that 1) Success message gets displayed on successfull submission or 2) failure message gets displayed on failed submission:
My Form
<div id="inline3" style="width:400px;display: none;">
<h3>Contact Us</h3>
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
If anyone can give me a bit of help or advise here it will be greatyly appreciated.
Thanks for reading
First thing I would do is change the backend so that instead of returning html it return json containing only the information you need (like whether the submission was a success or failure and any other messages, etc.).
Then the easiest fix that comes to my mind is to give each of your two feedback message divs unique id's:
<div id="form-feedback-success" class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div id="form-feedback-error" class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
Keep the class names so that you can use css to style the two in a similar manner.
Then in your javascript check for a success or failure flag. Based on the flag display one or the other div based on the id:
$.post(document.location.url, $(this).serialize(), function(data){
if(data.success) {
$('#form-feedback-success').fadeIn(1500);
}
else {
$('#form-feedback-error').fadeIn(1500);
}
});
You may need to make some tweeks(like deserialize the response from json to an object), but that is the gist of it.
Alright, after hours and hours of research and trying things I am completely stuck at the moment. I coded quite a lot for a web page so I'll try to summarize it as good as possible.
So I've got this ASP CLASSIC page where a user can create a ticket using a form.
The coded page consists out of 3 main parts:
Javascript client side error handling.
ASP CLASSIC server side error handling after submission (checking if
database values exists like email).
The form submitting (sending an email + inserting the data into the
database).
After the form is submitted there is some ASP error handling. When a error is encountered a Javascript popup box will be shown with the error and the data submission and email is being cancelled.
The form is auto filled with the inputted values (with asp code) so that after a error the inputted values are kept in the form. This all works.
The form code:
<div align="left"><form name="myForm" method="post" style="display:inline" onsubmit="return(validate());">
<div class="FormTitel">Voor welke afdeling is de ticket bestemd?
</div>
<div class="radio">
<input type="radio" class="radio" name="automatisering" value="Automatisering" checked <% if Request.Form("automatisering") = "Automatisering" then response.write("checked")%>>Automatisering
<input type="radio" class="radio" name="automatisering" value="Software" <% if Request.Form("automatisering") = "Software" then response.write("checked")%>>Software
<div id="Error1" style="display:none" color="white"></div>
</div>
<div class="FormTitel">Soort ticket
</div>
<div class="radio">
<input type="radio" class="radio" name="probleem" value="Probleem" <% if Request.Form("probleem") = "Probleem" then response.write("checked")%>>Probleem
<input type="radio" class="radio" name="probleem" value="Wijziging"<% if Request.Form("probleem") = "Wijziging" then response.write("checked")%>>Wijziging
<div id="Error2" style="display:none" color="white"></div>
</div>
<div class="FormTitel">Uw gegevens
</div>
<div>
<input type="text" name="Name" class="name" placeholder="Vul hier uw voor- en achternaam in" style="color:#888;"
onfocus="inputFocus(this)" onblur="inputBlur(this)" value="<%=Request.Form("Name")%>">
<div id="Error3" style="display:none" color="white"></div>
</div>
<div>
<input type="text" name="EMail" class="name" placeholder="Vul hier uw emailadres in" style="color:#888;"
onfocus="inputFocus(this)" onblur="inputBlur(this)" value="<%=Request.Form("EMail")%>"/>
<div id="Error4" style="display:none" color="white"></div>
</div>
<input type="submit" class="ticketVerstuur" value="Verstuur ticket" />
</form></div>
*The error id's are client side styling boxes that are being showed when a Validation returns false (with javascript).
*Sorry for not translating the title's, names, etc. but that would be quite some work;)
The ASP IF statements in the form make sure that the inputted values are returned and not lost when a error is being showed.
Alright now for the part where it goes wrong.
After submission, which is being activated by If Request.ServerVariables("REQUEST_METHOD") = "POST" Then some stuff is happening. Namely, the input values are being parameterized for sql injection, some input values are being checked on the server side, for example; does the submitted email exists in the database? and if the server side validation is all fine then the data is being inserted in the database and a email is being send.
The error messages on the server side are being shown to the user as javascript popup boxes. This works.
The javascript popup code:
function popup(popup,container) {
var thisPopup = this;
thisPopup.load = function() {
container.animate({
"opacity": "0.3"
},250, function() {
popup.fadeIn("250");
});
container.off("click").on("click", function() {
thisPopup.unload();
});
$('#closePop').off("click").on("click", function() {
thisPopup.unload();
});
}
thisPopup.unload = function() {
popup.fadeOut("250", function(){
container.animate({
"opacity": "1"
},250);
});
}
}
The function is called in the submit code like so: new popup($("#popup_box"),$("#container")).load(); The popup div is put above the form and the container is wrapped around the form. (popup works).
The problem though is that after the server side validation is all good, so the data goes into the database and the email is send, I popup a new javascript box saying that the everything was successful. When it is successful I want to clear my form (to avoid confusion).
First I try'd to do this with a response.redirect ("mypage.asp"). Though, when I use this the javascript popup box wont show.
Then I try'd to use a window.location.replace("http://stackoverflow.com"); on my close / unload function of the popup box, this has no effect though (data is not being cleared). Also try'd it with setting a var to true when the popup is unloaded and then later checking the var if it is set to true (then redirect) but this also doesn't work, even a direct javascript redirect, so without the popup, in the submission code (after all is successful) doesn't seem to work for some reason. In matter of fact only alert seems to work. Here the example of the adjusted popup unload:
thisPopup.unload = function() {
window.location.replace("http://stackoverflow.com");
popup.fadeOut("250", function(){
container.animate({
"opacity": "1"
},250);
});
}
So what causes this problem and how can I fix it? I can imagine it requires a bit more of my code so don't hesitate to ask for it, but the post is big enough as it is.
Last but not least a short summary of how my code is setup:
<html>
<head>
stylesheet
<title></title>
</head>
<body>
<javascript>
Pop up box code + validate form code
</javascript>
<form>
</form>
</body>
</html>
<asp server side code (on submit)>
Some functions (mail - anti injection) + request form values
Validation server side (with javascript poups)
Insert data in database
Sending mail
I think you were on the right track with the redirect. To get a pop-up to show after a redirect, do something like this:
response.redirect "mypage.asp?ShowSuccess=true"
Then in mypage.asp use this:
<%
if request("ShowSuccess") = "true" then
onload = "alert('Success message here!');"
end if
%>
<body onload="<%=onload%>">
I have a simpel form that I would like to submit with Ajax. It seems that regardless how I approach this, the form keeps insisting to refresh the page.
I would like the form to be submitted with a GET request, submitted with javascript, because I need a js response back from the server.
<div id='form_wrapper'>
<div class='gradient'></div>
<form action='' class='my-form' method='get' name='my-form'>
<div class='header'>
<h1>Submit this form</h1>
<span>Please fill out all fields, and then submit the form.</span>
</div>
<div class='content'>
<input class='input full_name' name='full_name' placeholder='Your full name' type='text'>
<div class='full_name-icon input-icon'></div>
<input class='input address' name='address' placeholder='Your full address' type='text'>
<div class='address-icon input-icon'></div>
</div>
<div class='form-footer'>
<input class='button' name='submit' type='submit' value='SUBMIT'>
<input class='help' name='submit' type='submit' value='HELP?'>
</div>
</form>
</div>
Also, I would like my submit button to not look like it is being pushed down - meaning that I would like to avoid having that blue border around the button once it has been pushed. I usually avoid the blue border by letting my buttons have href='javascript:void(0)', but as this is a form button I don't suppose I can apply my own href.
For one, i don't think you should have 2 submit buttons, but have an other mechanism in place, for the two different submit actions, however, that aside, i'll give you a jQuery answer since it's faster:
$(document).on('submit','.my-form',function(e){
e.preventDefault();
$.ajax({
url: "processing_page.php",
type : 'get',
data: { name : $('.full_name').val(), address: $('.address').val },
dataType: 'json'
}).success(function(data){
// do something here
console.log(data); //this is an object in my example
});
});
You'll also need a php processing page (named processing_page.php in my example) to get back some data. For example (didn't go through all the verification steps on either side, but you'll get the gist of it):
<?php
$myData = ['name' => '', 'address' => ''];
$name = $_POST['name'];
$address = $_POST['address'];
$myData['name'] = $name;
$myData['address'] = $address;
echo json_encode($myData);
?>
Reason for the long answer is so that you can verify your code at the basic level.
Hope i didn't make any typos.
Taken from the jQuery documentation:
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
event.preventDefault() stops the submit from triggering a new page.
You could do the following if you're using vanilla JavaScript;
function myFunc(){
alert(1);
}
<form id="formID" onsubmit="myFunc(); return false;">
<input type="submit" value="Submit">
</form>
When you click the submit button, it will activate the myFunc() JavaScript function and using return false in this manner will prevent the page from being changed. Then simply call document.getElementById('formID') to load the form details up. Alternatively you can use an active selector or jQuery $("#formID").
Happy Coding!