Jquery ajax form not submitting. going straight to error function - php

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();
....

Related

Submit Form Without Reloading Page and Get Output [PHP, jQuery]

Hellow,
I've been trying to submit a form without reloading and getting PHP output on the same page. The main objective is to submit the form values to a PHP file and get the output sent by the PHP file.
To understand it better, let's take a look on following code snippet:
HTML & jQuery Code:
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input id="name" name="name"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP Code:
<?php
if (isset($_POST['submit'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
}
else{
echo "I Dont Know You";
}
}
?>
What I Want:
When user enter value in the Input box and submit it, the page should display output value e.g ECHO value without reloading the webpage.
To be more specific on my first comment, you have to put an exit statement after you echo the response so the rest of the code doesn't execute, also to check whether the form was sent or not you can add a hidden input in your form with the value "1" (<input name="formSent" type="hidden" value="1">) that gets checked in your PHP :
<?php
if (isset($_POST['formSent'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
exit;
}
else{
echo "I Dont Know You";
exit;
}
}
?>
and then get the response from the ajax request in the success's callback parameter, also specify the method: 'POST' because jQuery's $.ajax function uses the method GET by default:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
method: 'POST',
data: $('form').serialize(),
success: function (message) {
alert(message);
}
});
});
});
</script>

value is not coming $POST array in php

I am building a simple sign up form using ajax when I creating a data object and pass to PHP file.It shows variables and doesn't show values of that PHP variable.
The code of HTML of form is
<form id="myForm" name="myForm" action="" method="POST" class="register">
<p>
<label>Name *</label>
<input name="name" type="text" class="long"/>
</p>
<p>
<label>Institute Name *</label>
<input name="iname" type="text" maxlength="10"/>
</p>
<div>
<button id="button" class="button" name="register">Register »</button>
</div>
</form>
The code of js is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
The code of PHP is
(mainlogic.php)
if(isset($_POST)) {
print_r($_POST);//////varaibles having null values if it is set
$name=trim($_POST['name']);
echo $name;
}
You are serializing your form on document load. At this stage, the form isn't filled yet. You should serialize your form inside your button click event handler instead.
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
In this code you serialize blank form, just after document is ready:
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Valid click function should begins like:
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({...
It means - serialize form right after button clicked.
var form = $("#myForm").serialize();
That is the line that collects the data from the form.
You have it immediately after $(document).ready(function() { so you will collect the data as soon as the DOM is ready. This won't work because it is before the user has had a chance to fill in the form.
You need to collect the data from the form when the button is clicked. Move that line inside the click event handler function.
The problem is that you calculate the form values at the beginning when loading the page when they have no value yet. You have to move the variable form calculation inside the button binding.
<script>
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Alpadev got the right answer, but here are a few leads that can help you in the future:
ajax
You should add the below error coding in your Ajax call, to display information if the request got a problem:
$.ajax({
[…]
error: function(jqXHR, textStatus, errorThrown){
// Error handling
console.log(form); // where “form” is your variable
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
$_POST
$_POST refers to all the variables that are passed by the page to the server.
You need to use a variable name to access it in your php.
See there for details about $_POST:
http://php.net/manual/en/reserved.variables.post.php
print_r($_POST); should output the array of all the posted variables on your page.
Make sure that:
⋅ The Ajax request ended correctly,
⋅ The print_r instruction is not conditioned by something else that evaluates to false,
⋅ The array is displayed in the page, not hidden by other elements. (You could take a look at the html source code instead of the output page to be sure about it.)

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 doesn't show server response

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');
}

How to display the content without going to another page

I have a message box with a submit button, when I click the submit button the content in the box should be insert in the MYSQL database, but without going to another page. The message which i just entered in the message box should be displayed in the same page after the submission. What should I do?
Use something called AJAX..
suppose this is your code :
<form id="myform" action="something" <!--Add this part-->onsubmit='return sendData()'<!--End of added part-->>
Enter Message <textarea name="msg" id="msg"></textarea>
<input type="submit" value="submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function sendData(){
var msgVal = $("#msg").val();
$.ajax({
data:"msg="+escape(msg),
url: $("#myform").attr("action"),
type: $("#myform").attr("method"),
success:function(){
alert( $("#msg").val() );
}
});
return false;
}
</script>
<script type="text/javascript">
function postData() {
var order = 'name='+$('#textBoxId').val();
$.post("Another_PHP_Page_Path.php", order, function(response,status, xhr){
if (status == "success") {
alert(response);
$('#divId').text(response);
}
else if (status == "error") {
alert('Something went wrong, we are working to fix it');
}
});
}
</script>
Note: name will be posted to PHP Page and after insterting into Database you can echo anything on php page or echo name, and on response this will showing back at same page. Use postData() on button onclick and button type should be button not submit.

Categories