$.post not sending data to php script - javascript

Okay I am at a loss for what is going wrong. I am trying to pass the form data to my php script from a simple jQuery script but for some reason when I try to access $_POST data php says that $_POST is empty?
Here we go, so I have the following jQuery and php scripts
jQuery
var post = $('#cform').serialize();
console.log("POST DATA: " + post);
$.post(action, post, function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#cform').slideUp('slow');
});
PHP
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
The console log of var post looks like this
POST DATA: fname=Daniel&lname=Jarvis&email=test%40gmail.com&phone=4444444444&comments=hello
And the var_dump of $_POST says this
array(0) { }
I have no clue why this is giving me so many problems so any help would be greatly appreciated.
P.S
I have also tried simply doing this for the post data but it still was not working.
var post = {fname: $('#fname').val(), lname: $('lname').val(), ...} //you get the idea
The console.log looked like this
{fname: "Dan", lname: "Jarvis", ...}
But when I var_dumped the $_POST variable it still said
array(0) { }

*There are several issues in your code,
1.Add event which will trigger ajax.
2.Your php script does not echo any data.
3.No return false or prevent defaul to stop form submission manually.(I think this is the main issue)
check the solution:*
HTML:
<form id="form">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="text" name="phone">
<input type="text" name="comments">
<input type="submit" name="submit" value="submit">
</form>
<span id="message"></span>
Javascript:
$("#form").submit(function(){
var post = $('#form').serialize();
console.log("POST DATA: " + post);
$.post('target.php', post, function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#cform').slideUp('slow');
});
return false;
})
PHP(I assume that your php script is target.php):
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
echo $fname.$lname.$email.$phone.$comments;

Related

how to display the result in same page?

it is my code.
html
<html>
<head></head>
</body>
<form id="myform" action="formdata.php" method="post">
username:<input type="text" name="username" id="name"><br>
password:<input type="password" name="password" id="pass"><br>
firstname:<input type="text" name="firstname" id="fname"><br>
lastname:<input type="text" name="lastname" id="lname"><br>
<input type="submit" id="submit" value="register">
</form>
<div id="status_text"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#submit").click(function(){
var username = $('#name').val();
var password = $('#pass').val();
var firstname = $('#fname').val();
var lastnamee = $('#lname').val();
var postData = '&username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname;
var status_text = $('#status_text');
//alert(postData);
//var mydata = {'username':name,'password':pass,'firstname':fname,'lastname':lname};
/*$.post($('#myform').attr('action'),
$('#myform:input').serializeArray(),
function(info){
$('status_text').html(info)
});*/
$.ajax({
url:"action",
type:"post",
success:function(info)
{
status_text.html(info);
}
});
});
</script>
</body>
</html>
and it is my php code for database
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
$name = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO karthik.person(name,password,firstname,lastname)VALUES('$name','$password','$firstname','$lastname')";
if($conn->query($sql) === TRUE){
echo("record added success");
}else{
echo("failed".$conn->error);
}
$conn->close();
?>
when ever i run this code it goes to next page and display the result like "record added successfully" instead of that i want the code to display the result in the same page. i almost tried all ways but i can't get my expected result.
You have some problems here:
You are not preventing the default submit event and that causes the form to submit "normally" as well.
You are not sending any data with your ajax request so you will never have any $_POST variables on the server-side.
You have an sql injection problem. You should use a prepared statement and bind the values.
You are not sending your ajax request to the correct url.
You are using a plain-text password. You should always salt and hash passwords.
You need to tell the browser not to submit the form:
$("#submit").click(function(e) {
e.preventDefault(); // Prevents the default behaviour for the submit-action
//... the rest of your code
When you get this working, you should start fixing stuff from #jeroen's list.

how to make a contact from html form and php page by ajax

I make this form to send data to a php page in another domain but always it results error. can someone explain my problem
I search in Internet many times but exactly I didnt find my answer
here is my code
html:
<form action="#" id="smail" method="post" class="form">
<input type="text" name="name" value="Your Name *">
<input type="text" name="mailadd" value="Your E-mail *">
<textarea name="message" cols="0" rows="0">Your Message *</textarea>
<input type="submit" value="send message">
</form>
js:
$('#smail').submit(function(event) {
event.preventDefault();
var mail = $("#smail input[name=name]").val();
var message = $("#smail input[name=mailadd]").val()+' '+$("#smail textarea[name=message]").val();
$.ajax({
type: "POST",
url:"http://cofeebeen.dx.am/email.php",
crossDomain: true,
data:{
"mail": mail,
"message": message,
},
dataType: "text",
error: function(){
alert("error")
}
}).success(function(result){
alert(result)
});
});
php:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
Your PHP code is not correct, we can get data at your PHP page like below.
Correct code:
$subject = $_POST["mail"];
$msg = $_POST["message"]
Incorrect code:
$subject = $_POST["name"];
$msg = $_POST["mailadd"]
I hope it will work now.
Per #mpf82's comment, if this is a cross domain request, that changes things. However, the AJAX request is currently passing 2 PHP post variables:
...
data:{
"mail": mail,
"message": message,
},
...
And you reference 3:
$_POST['name'];
$_POST['mailadd'];
$_POST['message'];
As #Reghbendra pointed out, you are referencing the incorrect variable names. Plus, since you did the concatenation of mailadd and message in Javascript, you can skip that part in PHP.
Therefore, your code would need to reference the two post variables that were passed by their proper indexes.
Result code:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
You also should consider the headers for the PHP mail function to ensure that it sends properly and is handled correctly. See the documentation for the function here.

Ajax request not sending data to php page but logging in console fine

I cannot figure out why the data is not getting inserted to my mysql database when it is being logged to the console properly.
My form as follows:
<form id="insertForm" type="post">
name: <input type="text" id="name" name="name">
activity: <input type="text" id="activity" name="activity">
level: <input type="number" id="level" name="level">
<input type="button" name="add" id="add" value="add">
</form>
My ajax call:
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(e){
var Data = $("#insertForm").serializeArray();
console.log(Data);
$.ajax({
url : "insert.php",
type: "POST",
data : Data,
success:function(data, textStatus, jqXHR)
{
$('#msg').html(data);
}
});
$("#msg").slideDown("slow");
e.preventDefault();
});
});
</script>
My PHP insert:
<?php
if (!empty($_POST))
{
$dbhost = 'localhost';
$dbuser = 'lot_root';
$dbpass = '';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$name = mysql_real_escape_string($_POST['name']);
$activity = mysql_real_escape_string($_POST['activity']);
$level = $_POST['level'];
$sql = "INSERT INTO lottt ".
"(name, activity, level) ".
"VALUES('$name','$activity', '$level')";
mysql_select_db('lot');
mysql_close($con);
}
?>
When i insert the data via the input fields it gets logged to the js console fine like so [Object, Object, Object]0: Objectname: "character_name"value: "aSD"__proto__: Object1: Object2: Objectlength: 3__proto__: Array[0]
but nothing is inserted into the mysql database after a quick check.
You need to run the query to save it. I'll answer it to the mysql_* library, even though it is deprecated.
This is how the flow is supposed to go:
$con = mysql_connect(....) or die();
mysql_select_db('database');
$name = mysql_real_escape_string($_POST['name']);
$activity = mysql_real_escape_string($_POST['activity']);
$level = $_POST['level'];
$sql = "INSERT INTO lottt ".
"(name, activity, level) ".
"VALUES('$name','$activity', '$level')";
if(!mysql_query($sql)) {
die('Error: ' . mysql_error());
} else {
echo 'saved';
}
You should stop using mysql_* functions. The library is deprecated.
You should look into using PDO or MySQLi as they are more modern libraries and while you might have to overcome a hurdle to learn it, being competent in those libraries will do you the world of good!
Resources:
PDO
MySQLi

PHP remembers POST value after refresh

I've got a problem with a html form. Php seems to remember my POST value after refreshing my page. It has to do with a login form that I uses.
I'm using cookies to let php communicate with javascript, telling javascript if the user is logged in or not.
Php code:
<?php
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = MD5($_POST['password']);
echo '<script>console.log("' . $username . '", "username"); </script>';
echo '<script>console.log("' . $password . '" , "password"); </script>';
/* against sql injections */
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$query = "SELECT user_id FROM User WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row[user_id]){
$cookie_name = "login";
$cookie_value = "1";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
} else{
echo '<script> alert("Incorrect username and password combination");</script>';
}
}
?>
The form:
<form method="POST" id="loginForm">
<b>Login</b>
<table style="margin-top: 10px">
<tr><td>Username: </td><td><input type="text" name="username" placeholder="username" required="required"></td></tr>
<tr><td>Password: </td><td><input type="text" name="password" placeholder="password" required="required"></td></tr>
<tr><td><input type="submit" name="login" value="Login" style="margin-top: 5px"></td></tr>
</table>
</form>
Because I love javascript, I'm using a ajax call to communicate with php and the server database.
Javascript code:
function openPage(page) {
var content;
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
document.getElementById('contentMiddle').innerHTML = data;
}
});
}
}
The problem is whenever I try to refresh the page, my php code will always run and $_POST['username'] and $_POST['password'] will always have the POST value from before refreshing the page.
I always make sure I remove the cookie before refreshing the page.
Any idea?
You've most likely already submitted the page and by hitting refresh the browser is attempting to send the POST data along with the refresh.
Since you're using Ajax to process your form you can/should remove type="submit" from the login button since there's no need for it. Instead you can have Login.
Then update your Ajax to run when the button is clicked. You can also use jQuery to get your elements by ID, for example:
$("#btn_login").on("click", function() {
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
//document.getElementById('contentMiddle').innerHTML = data;
$("#contentMiddle").html(data);
}
});
});
To address the comment by #charlietfl, handling an Enter press to submit the form you'd use something like this.
document.onkeydown = function(){
if(window.event.keyCode=='13'){
$("#loginForm").submit();
}
}

Data submit with ajax get result but not contact form

I have a online quiz by jQuery, I want once the user submit it, to send the results with the contact information's of the users to the moderator.
I make it work, sending the results information correctly, the problem is it doesn't send the user information.
I've been playing around with different solution's, I can manage or to have the user information or the results of the quiz, but not both at the same time !
Here is the "contact form":
<form action="submit.php" method="POST" id="form">
<label>Name</label>
<input name="name" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<input id="button" type="submit" value="Send" class="btnShowResult">
Here is the jQuery part about the ajax to send the data result of the quiz, the div #resultKeeper being the result I want to receive
$(function() {
$('#form').on('submit',function(e) { e.preventDefault();
$.ajax({
url:'submit.php',
type:'POST',
data:{'results':$('#resultKeeper').html(),'subject':'Subject of your e-mail'},
success:function() {
$('#responseMessage').html()
}
});
return false;
});
});
here is my PHP
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$results = $_POST['results'];
$formcontent="From: $name \n Message: $message \n Results: \n $results";
$recipient = "myemail#gmail.com";
$subject = "my subject";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Your email has been send, thank you";
?>
If in the Jquery I change the
$(function() {
$('#form').on('submit',function(e)
by #button instead of #form, I receive the informations from the contact form, but not anymore from the results.
Also by keepin the #form, I receive the result of the quiz, and few value as the form content, but not the informations from the placeholder !, here is what I receive by email:
"
From:
Message:
Results:
<div> Question 1 is true</div><div> Question 2 is false\</div><div> Question 3 is true\</div>\<div> Question 4 is false\</div>\<div> Question 5 is false\</div>\<div class=\"totalScore\">\<br>Your total score is 2 / 5\</div>\<div class=\"totalScore\">\<br>CONGRATULATION, YOUR LEVEL IS A1.1\</div
"
As we can see I have the From: and Message: appearing, but not the proper name and message that the user are writing .. .
Any help will be adorable !!
Here is the allcode of JSFiddle:
http://jsfiddle.net/ccwJJ/
You do not receive your form values in your php file when you make an ajax request, you have to explictly send them in the ajax request.
Consider below form
<form action="submit.php">
<input type="email" name="email" id="email"/>
<input type="submit" value="send"/>
</form>
Case 1 Normal way
When you submit the form normally, say hitting enter or on click you would receive the form values implicitly in your php file as $_POST['email] variable
<?php $email = $_POST['email'] ; // valid ?>
Case 2 Ajax way
When you submit the form using ajax, You do not receive the form values implicitly in your php file since your ajax request does not know about your form elements, You have to send the values explicitly in the ajax request.
$.post('submit.php',function(result){
$('#responseMessage').html(result);
});
<?php $email = $_POST['email'] // error ?>
why? because you have not set the post variable email
Then how to do it?
var uemail = $("#email").val(); // get the email
// Set email and send it through ajax
$.post('submit.php',email:uemail,function(result){
$('#responseMessage').html(result);
});
<?php $email = $_POST['email'] // works perfect ?>
So now change your form to this
<form action="submit.php" method="POST" id="quesForm">
<label>Name</label>
<input name="username" type="text" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<input id="button" type="submit" value="Send" class="btnShowResult">
</form>
Notice I have changed name='name' to name='username'and I suggest you to change id=form to some other name say id=quesForm. I have seen some browsers does not seem to work as expected when you use tags as id names and attributes as attribute values like you have done name=name and id=form
I suggest you to use $.post instead of $.ajax, It simplifies the things for you when you really require $.post
jQuery
$(function() {
$('#quesForm').on('submit',function(e) {
e.preventDefault();
// I am fetching the form values you could get them by other selectors too
var uname = $("input[name=username]").val();
var uemail = $("input[name=email]").val();
var msg = $("textarea").val()
$.post('submit.php',{username:uname,email:uemail,message:msg,results:$('#resultKeeper').html(),subject:'Subject of your e-mail'},function(result){
// result variable contains your response text
// I guess you trying to update your response
// notice I have used html(result) as you have just used html()
$('#responseMessage').html(result);
});
// you dont require `return false`
// you have already did it using e.preventDefault();
});
});
php
<?php $name = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
$results = $_POST['results'];
$results = strip_tags($results); // add this to remove html tags and all
$formcontent="From: $name \n Message: $message \n Results: \n $results";
$recipient = "thibault.rolando#gmail.com";
$subject = "my subject";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Your email has been send, thank you";
?>
To remove html tags in php you have function named strip_tags();
You need to send the form data, plus your results string.
Try the following:
$(function() {
$('#form').on('submit',function(e) { e.preventDefault();
//grab the form data into array
var formData = $('#form').serializeArray();
//add your result and subject
formData.push({ results:$('#resultKeeper').html(), subject:'Subject of your e-mail'});
$.ajax({
url:'submit.php',
type:'POST',
data:formData,
success:function() {
$('#responseMessage').html()
}
});
return false;
});
It is better to use following way for getting form input values:
var data = $('#yourformid').serielize();
You will get the data in serielize format and put it on ajax data param.

Categories