print ajax response with php - php

I cannot get the alert to work after sending the data in ajax? Could anyone tell me what I'm doing wrong?
My form:
<body>
<form action="" id="form1" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" id="submit1" value="Submit">
</form>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
// AJAX SEND POST DATA
$('form').on('submit', function() {
var self = this;
$.ajax({
type: 'post',
url: 'submit2.php',
dataType: 'json',
data: $(self).serialize(),
success: function() {
alert("blabla");
}
});
});
</script>
This is my submit2.php file.
<?php echo "bla"; ?>

There is no problem with your HTML or JQuery code. The problem is with submit2.php file. Your AJAX function is looking for a JSON response. Return a JSON response from submit2.php
submit2.php
echo json_encode(array("message"=>"Here is the message"));

Your code should be like this:
HTML
<form action="" id="form1" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" id="submit1" value="Submit">
</form>
jQuery
$("#form1").submit(function(e){
e.preventDefault();
var self = this;
$.ajax({
type: 'post',
url: 'submit2.php',
// dataType: 'json', unless you're expecting json object as server response, remove this
data: $(self).serialize(),
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
submit2.php
<?php
if(isset($_POST['firstname']) && isset($_POST['lastname'])){
echo $_POST['firstname'] . " " . $_POST['lastname'];
}
?>

Related

Server response is printed on the browser but not returned to success function in ajax

I am not able to get the response to ajax success call back function. The response form the server is being directly printed on the browser
<body>
<script>
$(document).ready(function() {
$.ajax({
url: $("#form").attr("action"),
type: "POST",
data: $("#form").serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
<form action="a.php" method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
</body>
my php code
<?php
echo 'hii';
?>
Can you Replace AJAX script below mentioned.
<form method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
$("#form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: 'a.php',
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});

Unable to pass a variable through an ajax request

I'am trying to pass a parameter using ajax to another php page and view the passed parameter in there. But its only redirecting page.parameter is not passed
This is my form.Used to get name through input field
<form id="regform" method="post" action="">
<div>
First Name:
<input type="text" name="fname" id="fname" />
<input type="submit" class="color" name="loginBtn" id="loginBtn" value="register" />
</div>
</form>
This is the ajax code I'am using pass my parameter to ajax.php page.
$("#regform").submit(function(e) {
e.preventDefault();
var form = $(this);
//var url = form.attr('action');
var senddata = {"fname": $('#fname').val()};
console.log(senddata);
$.ajax({
type: "post",
contentType: "application/json",
url: "ajax.php",
dataType: 'json',
data: JSON.stringify(senddata),
success: function(data) {
console.log(data);
}
});
Check this.it is working.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<form id="regform" method="post" action="">
<div>
First Name:
<input type="text" name="fname" id="fname" />
<input type="submit" class="color" name="loginBtn" id="loginBtn" value="register" />
</div>
</form>
<script>
$("#regform").submit(function(e) {
e.preventDefault();
var senddata = $('#fname').val();
console.log(senddata);
$.ajax({
type: "post",
url: "ajax.php",
dataType: 'json',
data: {fname:senddata},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP
<?php
echo ($_POST['fname']);
?>

file is not uploading in ajax php mysql

I am trying to upload a file using ajax which is giving me an error and the rest of data upload successfully i have try without ajax the file is uploading but when i try to upload file via ajax it give me error i am totally confuse why ajax is giving me the problem.here is my code.
<html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
var form_data = $('#reg_form').serialize();
$.ajax({
type:"POST",
url:"process.php",
data:form_data,
success: function(data)
{
$("#info").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="reg_form" enctype="multipart/form-data" method="post" action="">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
<input type="button" value="Send Comment" id="button">
<div id="info" />
</form>
</body>
</html>
The process.php file coding is here.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
First of all serialize() function don't work for file you should have to make an object of form through which you can post the data and will work perfectly I had the same problem and I have just resolved your issue and is working 100% because I have tested this. Please check out.
The form.
<form name="multiform" id="multiform" action="process.php" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
</form>
<input type="button" id="multi-post" value="Run Code"></input>
<div id="multi-msg"></div>
The script.
<script type="text/javascript">
$(document).ready(function(){
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
if(window.FormData !== undefined)
{
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
}
});
$("#multi-post").click(function()
{
//sending form from here
$("#multiform").submit();
});
});
</script>
And your php file is the same I have tested and is working.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>

To display result on the same webpage

I am using php, mysql and ajax to display a contact form , but the problem is that the output "1 record inserted" gets showed on the next page . I want to be displayed on the same page on submit .
Following is the code
validation.html
<html>
<head>
<title>Contact Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" language="javascript">
// <script type="text/javascript">
$(document).ready(function(){
$("#myButton").click(function() {
alert("Hii");
$.ajax({
cache: false,
type: 'POST',
url: 'validation.php',
data: $("#contact").serialize(),
success: function(d) {
$("#record").html(d);
}
});
});
});
</script>
</head>
<body>
<form method="post" id="contact" action="validation.php">
Name: <input type="text" name="name"> <br>
E-mail: <input type="text" name="email"> <br>
Password: <input type="text" name="pass"> <br>
Mobile: <input type="number" name="mobile"> <br>
<br>
<input type="submit" value="SUBMIT" id="mybutton"/>
</form>
<div id="record">Record has been inserted</div>
</body>
</html>
Can anyone please point out how i can go on doing so or what all changes are needed ?
It's because when you click #myButton, you're submitting the form and it redirects you.
Simply prevent the default action.
$("#myButton").click(function(event) {
event.preventDefault();
alert("Hii"); //what is this for???
$.ajax({
cache: false,
type: 'POST',
url: 'validation.php',
data: $("#contact").serialize(),
success: function(d) {
$("#record").html(d);
}
});
});
U are submitting the button, Just change
<input type="button" id="myButton">Submit</input>
OR
<button id="myButton">Submit</button>
It will invoke your ajax request.
Currently the form is submitted by your button, because it is a Submit-Button. If you don't want the submission of the form there are several methods, but these two are the best:
// Use prevent default
$("#myButton").click(function(e) { // This 'e' is important
e.preventDefault()
# rest of the function here
});
or you could just replace your Submit button with a link tag (just with a placeholder href) like here:
<html>
<head>
<title>Contact Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" language="javascript">
<script type="text/javascript">
// Actual Javascript code here
</script>
</head>
<body>
<form method="post" id="contact" action="validation.php">
Name: <input type="text" name="name"> <br>
E-mail: <input type="text" name="email"> <br>
Password: <input type="text" name="pass"> <br>
Mobile: <input type="number" name="mobile"> <br>
<br>
SUBMIT
</form>
<div id="record">Record has been inserted</div>
</body>
</html>
Best case would be combining both.
try to call function onclick event of input element
<input type="submit" value="SUBMIT" id="mybutton" onclick="return myFunction()"/>
then call this function
function myFunction()
{
$.ajax({
cache: false,
type: 'POST',
url: 'validation.php',
data: $("#contact").serialize(),
success: function(d) {
$("#record").html(d);
}
});
return false;
}
also replace this
<form method="post" id="contact" action="validation.php">
with
<form method="post" id="contact" action="validation.php" onsubmit="return false;">
It should help you!
Thanks.
its open another page because your form will do submit procces when you click #myButton.
there are some way to solve this.
1. add attribute into your form tag:
<form method="post" id="contact" action="validation.php" onsubmit="return false;">
or
2. make your button to prevent submit procces by returning false:
$(document).ready(function(){
$("#myButton").click(function() {
alert("Hii");
$.ajax({
cache: false,
type: 'POST',
url: 'validation.php',
data: $("#contact").serialize(),
success: function(d) {
$("#record").html(d);
}
});
return false;
});
});
try this
<input type="button" id="myButton">Submit</input>
OR
Submit

How to submit and validate a form via ajax

Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});

Categories