Ajax doesn't show server response - php

I'm trying to build a subscribe form. I can't run php on my site and I don't want the user leave the main site to subscribe the newsletter. I'm using this example as server side.
If you try to put in you email you will get redirected and the error message shows up even if the e-mail was added to the mailchimp list.
<div id="email">
<span>Your email..</span>
<form action="http://simondahla.com/jolliassets/notify.php" id="notify" method="POST">
<input type="text" placeholder="your#email.com" name="email" id="address" data-validate="validate(required, email)"/>
<span>We'll never spam or give this address away</span>
<button type="submit">ยป</button>
</form>
<span id="result"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#notify').submit(function() {
var action = $(this).attr('action');
$.ajax({
url: action,
type: 'POST',
data: {
email: $('#address').attr('value')
},
success: function(data){
$('#result').html(data).css('color', 'green');
},
error: function() {
$('#result').html('Sorry, an error occurred.').css('color', 'red');
}
});
});
});
</script>
live example of the problem

You need to return false from your submit handler. This is to prevent the browser from executing the default action, i.e. to submit the form the normal way.
$('#notify').submit(function() {
// .. your ajax call
return false;
});

From your PHP function you're going to return the values you want given the success or failure of the code.
Succeeded:
print json_encode(array("status"=>"success","message"=>'Successfully added'));
Failed:
print json_encode(array("status"=>"error","message"=>'There was an error'));
Then in the HTML you return that message like this:
success: function(data){
$('#result').html(content.message).css('color', 'green');
},
error: function() {
$('#result').html(content.message).css('color', 'red');
}

Related

Form not submitting without redirecting

I want to send sms on click without page reload and redirecting but the form not working without redirecting to action page. Here is my code.
Page containing form
<div class="blog">
<form method="post">
<input type="hidden" name="message" value="whatever">
<input type="text" name="tono" maxlength="10">
<input type="submit" value="SEND SMS" id="sendit">
</form>
<script>
$(document).ready(function(){
$("#sendit").click(function(){
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize();
}).done(function(response) {
alert(response);
});
return false;
});
});
</script>
</div>
example.php
<?php
error_reporting(E_ALL);
ob_implicit_flush(true);
include_once "class.curl.php";
include_once "class.sms.php";
include_once "cprint.php";
$smsapp=new sms();
$smsapp->setGateway('way2sms');
$myno='XXXXXXX';
$p='XXXXXXXX';
$tonum=$_POST['tono'];
$mess=$_POST['message'];
cprint("Logging in ..\n");
$ret=$smsapp->login($myno,$p);
if (!$ret) {
cprint("Error Logging In");
exit(1);
}
print("Logged in Successfully\n");
print("Sending SMS ..\n");
$ret=$smsapp->send($tonum,$mess);
if (!$ret) {
print("Error in sending message");
exit(1);
}
print("Message sent");
?>
This reloads the page but doesn't submit the form and if i add action attribute to form it redirects to example.php and successfully sends sms.
I see you are returning false in the handler, which is basically the same as using event.preventDefault(), but this is not working because you have a syntax error (a semicolon that should not be there):
$(document).ready(function () {
$("#sendit").click(function () {
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize() // You have ";" here, and it's causing the rest of the code to fail.
}).done(function (response) {
alert(response);
});
return false;
});
});

ajax request not working?

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

Callback message for php form

I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>

Ajax call only if the jquery validation is valid

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.

Jquery ajax form not submitting. going straight to error function

I have a form where users can sign up to a newsletter but i can't get it to submit properly.
When i click the submit button, i get an alert saying "Failure" so the ajax request is going straight to the error catchment in the ajax request.
In my php, I get all the $_POST variables and insert them into the database and I know that script is working. I just want to return the message back to the ajax success so that the message can be displayed to the user.
I have looked everywhere for a solution and can't find one.
<?php
echo "done";
?>
and the form with jquery
<html>
<head>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mlbutton').click(function() {
var name = $('#mlName').val();
var email = $('#mlEmail').val();
$.ajax({
type:'POST',
url: 'storeAddress.php',
data:$('#addressform').serialize(),
success: function(response) {
$('#addressform').find('#response').html(response);
alert(response);
},
complete: function() {
$('#addressform').each(function() {
this.reset();
});
},
error: function(){
alert('failure');
}
});
});
});
</script>
</head>
<body>
<form id="addressform">
<div class="textl1"><label id="namLbl" for="mlName">Name</label><input type="text" id="mlName" name="mlName" /></div>
<div class="textl1"><label id="emlLbl" for="mlEmail">Email</label><input type="text" id="mlEmail" name="mlEmail" /></div>
<div class="textr1"><input type="submit" id="mlbutton" name="mlbutton" value="dffhfdh" class="button-signup" /></div>
<p id="response" style="text-align: left"> </p>
</form>
</body>
</html>
Update
Added e.preventDefault(); //call prevent default on event
This now stops the failure message but it appears that the php file is not called. I have tested the php file and because no email address supplied I get a message i was expecting. If i just click the form without entering an email address, I am expecting the same message but nothing. If i do enter an email address, I would expect the email to be in database but nothing happens. It is like the php file is not being called
The could should prevent the default action of the form.
$('#mlbutton').click(function(e) { //added event as argument
e.preventDefault(); //call prevent default on event
var name = $('#mlName').val();
var email = $('#mlEmail').val();
$.ajax({
type:'POST',
url: 'storeAddress.php',
data:$('#addressform').serialize(),
success: function(response) {
$('#addressform').find('#response').html(response);
alert(response);
},
complete: function() {
$('#addressform').each(function() {
this.reset();
});
},
error: function(){
alert('failure');
}
});
});
You need to prevent your button from submitting the page, so that the AJAX can run.
$('#mlbutton').click(function(e) {
e.preventDefault();
....

Categories