I am sending ajax request to a php page on a button click. Here is my request being sent
$("#enteruser").on('click',function(){
console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();
var data={name: name, email:email, role:role};
var url='addemployee.php';
$.ajax({
url : url,
data: data,
type: 'POST',
success: function(response)
{
if(response=="success")
{
$("#rmsg").text("Hello World");
}
else
{
}
}
});
});
My this line is not working and URL after returning back contains the values I sent. So If I resend request the request is not sent again due to url. If I put the following line
window.location="anotherpage.html"; in the success block the page is redirected to the that page. Then why the rmsg paragraph is not being written?
I am adding the form dynamically using the following code
$("#create").on('click',function(){
var htmc='<div class="testbox">\n\
<h1>Create Employee</h1>\n\
<form>\n\
<hr>\n\
<label id="icon" for="eemail"><i class="icon-envelope "></i></label>\n\
<input type="text" name="eemail" id="eemail" placeholder="Email" required/>\n\
<label id="icon" for="ename"><i class="icon-user"></i></label>\n\
<input type="text" name="ename" id="ename" placeholder="Name" required/>\n\
<label id="icon" for="erole"><i class="icon-road"></i></label>\n\
<input type="text" name="erole" id="erole" placeholder="Role" required/>\n\
<button id="enteruser" class="button">Enter</button>\n\
</form>\n\
</div>';
$("#view").html(htmc);
});
$(document).on("#enteruser",'click',function(e){
e.preventDefault();
console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();
var data={name: name, email:email, role:role};
var url='addemployee.php';
$.ajax({
url : url,
data: data,
type: 'POST',
success: function(response)
{
if(response=="success")
{
alert(response);
$("#rmsg").text("Hello World");
}
else
{
}
}
});
});
One thing i like to do when troubleshooting HTTP calls is to view the actual network event in a debugging tool.
In Google Chrome, use CTRL + SHIFT + I to open up the debugging tools. Then click on the Network tab. In here, you may view the POST and Response and verify that your response is correct.
In MS IE, you can hit F12 to view the developer tools there
Try this
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id="ename" />
<input type="text" id="eemail" />
<input type="text" id="erole" />
<span id="rmsg"></span>
<button id="enteruser">Button</button>
<script type="text/javascript">
$("#enteruser").on('click',function(){
console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();
var data={name: name, email:email, role:role};
var url='addemployee.php';
$.ajax({
url : url,
data: data,
type: 'POST',
success: function(response)
{
if(response=="success")
{
$("#rmsg").text("Hello World");
}
else
{
}
}
});
});
</script>
</body>
</html>
PHP:
<?php session_start(); echo 'success'; ?>
You are not preventing default behaviour for a form. YOu should say to your app: "do nothing with the form and make it handled by js".
Also you are using a delegated function in the wrong way.
To do so change this:
$("#enteruser").on('click',function(){
console.log("entered here");
to this:
$("#enteruser").click(function(e){
e.preventDefault();
console.log("entered here");
all the other part of your code can remain as now if the form is in the dom from the beginning.
$(document).on('click',"#enteruser",function(e){
e.preventDefault();
console.log("entered here");
if the form is added to the page after it is loaded. YOu can also replace document with any element already in the page that is before the form in the dom structure
Related
First of all I'm sorry if my English isn't totally correct.
I'm learning to use json and I want to try with this simple code, where I insert name and surname and with Ajax I send them to a json struct for then show them in a table.
ajax.php
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<input type="submit" id="invia" value="ISCRIVITI" />
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
<script type="text/javascript">
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
</script>
json.php
<?php
header("Content-Type: application/json", true);
$dati = array( 'nome'=>$_POST['nome'], 'cognome'=>$_POST['cognome'] );
echo json_encode($dati);
?>
Where are the mistakes? Because the outputs are shown for just a second and then they will disappear.
Thank you to everybody.
When you submit the form it will reload all page again, so assigned html visible for short time only.
Use preventDefault() function to overcome this situation.
<script type="text/javascript">
$("#iscrizione").submit(function(event){
event.preventDefault()
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
On submitting form, it will reload page by default. We can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. Read more about .submit() event.
1.On using returning false after ajax call.
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
return false; // add return false here
});
2.By using event.preventDefault()
$("#iscrizione").submit(function(event){
event.preventDefault();// use preventDefault() on event
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
});
Either return false or preventDefault() will work, as the other two answers have described. However, it's important to understand that you don't have to submit the form at all, and indeed it isn't best practice to do so. After all, it doesn't make much sense to use HTML to submit the form and then disable the submit behavior in your code. Especially when you don't have to.
AJAX was invented to overcome the problems (such as yours) that result when you reload the page. The point about AJAX is that it gives you the ability to update your page with new data without reloading it.
So, the cleaner way to do what you want is to make your button simply a button, and call your code from the button's click event. Have a look at this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Test
</title>
<!--jQuery file-->
<script src="includes/jquery/jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function showMyPHP() {
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("#td_nome").html(msg.nome);
$("#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
}
$('#invia').on('click', function(e, ui){
showMyPHP();
});
});
</script>
</head>
<body>
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<button type="button" id="invia">"ISCRIVITI"</button>
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
</body>
</html>
You can see that we're not submitting the form at all here. Rather, we're calling the AJAX through the button's click event. You'll see that you get the results you're looking for, without resorting to using HTML to submit the form and then disabling the default submit behavior in code.
Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});
I have a form and ajax call.data are filled in form and goes to remote at the same time user is created in my database using ajax call.but the problem is with validation,which validation should apply here
for example i apply any jquery validation i need to test if the form is valid and then i can call ajax if the form is valid other wise the database will be filled with blank data
i tried with bvalidator but i don't know how to detect the form is valid or invalid using any jquery validator library
<form id="inform" action="http://site.com">
<input type="text" id="name" />
<input type="text" id="email" />
<input type="button" name="subaction" id="infuse" />
</form>
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
$na(document).ready(function(){
$na('#infuse').click(function(){
var name= $na('#name').val();
var email = $na('#email').val();
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email,
cache: false,
success: function(result){
jQuery('.err_msg').html(result);
jQuery("#inform").submit();
}
});
});
});
</script>
You could do something like this
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
var name;
var email;
var options10 = {
// shows or hides error all messages container after validation completes
onAfterAllValidations: function(elements, formIsValid){
// if validation failed
if(!formIsValid)
callAjax();
else{
//do something
}
}
};
function callAjax(){
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email,
cache: false,
success: function(result){
jQuery('.err_msg').html(result);
jQuery("#inform").submit();
}
});
}
$na(document).ready(function(){
$('#inform').bValidator(options10);
$na('#infuse').click(function(){
name= $na('#name').val();
email = $na('#email').val();
});
});
</script>
I haven't checked this, but hopefully , this works. The important point is, you could use the callbacks : onAfterAllValidations.
issues are still there...pls help
I am unable to load external file while using AJAX jquery. I want to use Jquery ajax to pop up form then validate, enter data in mysql. but starting from a simple ajax function. kindly let me know where i am going wrong
<link rel="stylesheet" type="text/css" media="all" href="test_style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
});
});
</script>
</head>
<body>
<div id="contact_form">
<form id="ajax-contact-form" name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<INPUT class="button" type="submit" name="submit" value="Send Message">
</fieldset>
</form>
</div>
</body>
</html>
and contact.php file is
<?php
echo "Hello";
?>
You need to return false; to prevent the form from submitting and refreshing the page and check if your $("#div1") is missing.
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
return false;
});
});
Simple. Since you are posting your form through ajax, you must prevent the default form submit by returning a false inside the submit method. Below is the correct version:
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url:"contact.php",
data: str,
success:function(result) {
$("#div1").html(result);
}
});
return false;
});
});
</script>
You can use a more simple form of post request as follows:
$.post("url",{var1: value1, var2: value2},function(data,status){
if(status=='success')
alert(data);
});
the second argument you can pass as many using this post request. The first argument url, if ofcourse relative to the document in which this js is loaded or you can give the exact url on the server.
According to your php file, data=='Hello'.
Similar is the procedure for any GET request also.
Make sure you are missing the div1
please use
<div id="div1"><div>
The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/