Ajax POST call doesn't send or submit any data - javascript

I am trying to make my submit button send data to my PHP file without reloading, however, when I use this call it doesn't send any data and neither is saved in my database.
$('#formSubmitData').on('submit', function(event) {
event.preventDefault();
var msg = $('#textareaSubmitData').val();
$.ajax({
url: 'searchData.php', //this is ALSO how the text is being send to the database to be retrieved later on.
type: 'POST',
data: {message:msg},
success: function(data) {
console.log(data);
data = msg;
alert(data);
}
});
});
The alert shows the correct value, but in my database, the rows remain empty.
How the PHP code looks like:.
if (isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === "POST") {
include_once 'dbConn.php';
$name = $_SESSION['userName'];
$msg = $_POST['textareaSubmitData'];
$stmt = $conn->prepare("INSERT INTO messages (name, message) VALUES (?, ?)");
$stmt->bind_param('ss', $name, $msg);
$name = $_SESSION['userName'];
$msg = $_POST['textareaSubmitData'];
$stmt->execute();
$conn->close();
$stmt->close();
} else {
header('Location: index.php?send=failure');
exit();
}
}

Think there are 2 issues, the first is that you need to make sure the data to send is an object and not just a value...
data: { textareaSubmitData: msg },
The second is that when you try and process the data, your first line is...
if (isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === "POST") {
So this is looking for some POST data in 'submit' - which you don't send. So as you (now) just send 'textareaSubmitData' - check if that is set...
if (isset($_POST['textareaSubmitData']) && $_SERVER['REQUEST_METHOD'] === "POST") {

You are sending the value of submit button in data. You need to send the form data to your server.
$('#formSubmitData').on('submit', function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: 'searchData.php', //this is ALSO how the text is being send to the database to be retrieved later on.
type: 'POST',
data: data,
success: function(data) {
data = msg;
alert(data);
}
});
});

Also – definitively, "look at(!)" what is being sent, using the debugging features of your browser. When the AJAX call goes off, you can see an HTML POST being done – so, you can see exactly what the URL is, and exactly what data is (or, isn't) being supplied.
On the host side, you can also do things like print_r($_POST) so that you can once again see what PHP has received.
My experience is that, once you can see what's happening, debugging is very quick and easy. Whereas, guessing leads nowhere.

Related

Not sending data with AJAX to database

I have a problem with catching AJAX data with PHP and send it to the database. Site is on the WordPress platform.
I have checked for the errors with mysqli_error but there nothing happened. Console not showing any error, just show there is `console.log data from the ajax, so the ajax work.
Here is what I have tried so far.
AJAX:
$.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: {
'creditCardValue':creditCardValue,
'creditCardValueCvc':creditCardValueCvc,
'phoneNumberForm':phoneNumberForm
}
});
Here is a PHP code:
<?php
if (isset($_POST['button'])) { // button name from html
$creditCardValue = $_POST['creditCardValue'];
$creditCardValueCvc = $_POST['creditCardValueCvc'];
$phoneNumberForm = $_POST['phoneNumberForm'];
$query = "INSERT INTO validations(credit_card_number, credit_card_cvc, phone_number) ";
$query .= "VALUES ({$creditCardValue}, '{$creditCardValueCvc}', '{$phoneNumberForm}' ) ";
$create_post_query = mysqli_query($connection, $query);
}
?>
I need to send all these data to the database so I can later call them and displayed them.
Thanks in advance.
Remove the check for $_POST['button'] as this is not sent with the AJAX data. If you want to check if it's an AJAX call then just check that one of the values has been POSTed:
if (isset($_POST['creditCardValue'])) { ...

Secure AJAX POST/GET jquery

So basically my question is simple.
Imagine situation when you a making a login or register form. With jquery.post i make ajax call
$.post( "pages/form_handle.php", name: $.(".username").val(), pass: $.(".pass").val() , function( data ) {
$( ".result" ).html( data );
});
it's simple call(i belive so)...
How to make it secure?
So if user look in my source code he or she know where i send my data in example pages/form_handle.php also he or she know what data i send to this page.
One of idea what i have simple send all ajax calls to one page ajax.php adding extra variables who will call right php function for ajax call...
But does it is the right way? Or maybe there is some better way to make it secure?
Stick to basics, and keep salting your passwords.
AJAX is not server side language, its a javascript plugin that does the same thing as forms, actions, etc... just in background as a new request.
Your ajax is not in danger, but your php files are, you can use jquery-validate.js to check on users input, but also you should make validation check in your ajax.php.
Here is a simple ajax login request:
function loginUser() {
var process = "loginUser";
var data = $("form").serializeArray();
data[1].value = data[1].value; // data to ajax.php page
data = JSON.stringify(data);
$("#loginButton").html('Login');
$.ajax({
type: "POST",
url: "ajax.php",
data: {"process": process, "data": data},
success: function(data) {
if (data.response.state == "success") {
// if ajax.php returns success, redirect to homepage or whatever
} else {
// if ajax.php returns failure, display error
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
// error handling
},
dataType: "json"
});
}
And the simple ajax.php login:
<?php // ajax.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])){
$un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username='$un_temp'";
$result = mysql_query($query);
if (!$result) die("Database access failed: " . mysql_error());
elseif (mysql_num_rows($result)){
$row = mysql_fetch_row($result);
$salt1 = "qm&h*";
$salt2 = "pg!#";
$token = md5("$salt1$pw_temp$salt2");
if ($token == $row[3]) echo "$row[0] $row[1] :
Hi $row[0], you are now logged in as '$row[2]'";
else die("Invalid username/password combination");
} else die("Invalid username/password combination");
}else{
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function mysql_entities_fix_string($string){
return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string){
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
?>

How can I attach the POST variable values to a new SESSION variable in AJAX and call it from other script?

I checked the accepted answer of this question it but didn't help
I'm trying to make an AJAX Post Request to sumbit my signup form, the ajax.php file will check the entered information, example passwords match or not, and then attach the $_POST variable to a $_SESSION variable so that I can call the submitted data from any other page later.
Ajax.php
...
if ($everythingValid) {
// add this user to db
$_SESSION["signup_details"] = $_POST;
echo "SUCCESS#".$core->signupPaymentUrl($package); // tried without this line but didn't work
exit(); // tried without this line but didn't work
} else {
foreach ($errors as $e) print "<br>".$e;
exit();
}
...
The jquery code that I'm using to call the file is the below:
var form = $('#signup');
$("#submit").click(function() {
$.ajax( {
type: "POST",
dataType: 'html',
crossDomain: true,
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
if ("SUCCESS" === $.trim(response.split('#')[0])) {
// user created, redirect to payment page
var paymentUrl = $.trim(response.split('#')[1]);
window.location.href = paymentUrl;
} else {
$("b#signupErr").hide();
$("b#signupErr").html(response);
$("b#signupErr").fadeIn();
}
}
} );
});
After submitting the form, I successfully get redirected to the payment Url, however, after accessing the page where I want to use my session, I cannot figure out how to retrieve my session although I'm pretty sure that I have included session_start in both of ajax.php and completeOrder.php and no blank spaces before the opening php tag.
here is the line that I included in both files :
if(!session_id()) session_start();
I tried to var_dump the $_SESSION variable on ajax.php and It looks okay. However when I var_dump the session variable on completeOrder.php it shows me NULL
Finally here is the completeOrder.php content
if(!session_id()) session_start();
require_once("core.php");
$core = new coreOptions();
$email = $_SESSION["signup_details"]["email"];
$password = $_SESSION["signup_details"]["password"];
$package = $_SESSION["signup_details"]["pkg"];
$options = $core->attachOptions($package);
if ($core->registerUser($email,$password,$options,$package))
$core->redirect("registrationCompleted.php");
in the completeOrder.php file remove if(!session_id()) session_start();
and then only add session_start(); and it will do the trick!
session_id() will return an empty string in ajax.php if there was no call to session_start() before. So the in ajax.php session_start() will never be called and the content of $_SESSION won't be stored anywhere.
So just use:
session_start();
in both files.

Problems posting data to a server using jQuery

I'm a student who is doing an app with jQueryMobile and gonna be compiled with Phonegap. I want to posting data to a server using jQuery but I have problems loading my .php file in the server.
I have the last version of jQuery.
Here I put my script for post the data from a form:
$(document).ready(function() {
var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
$.ajax({
type: 'post',
data: postData,
url: 'http://www.smartweb.cat/app/Habana/user_register.php',
success: function(data) {
alert('Usuari registrat correctament.');
},
error: function() {
alert('Hi ha algun problema amb el registre.');
}
});
return false;
});
});
Thanks a lot and sorry for my english wrinting.
Your post data are empty. You retrieve them directly when the DOM is loaded and not when the form is submit. You should move your var postData.
$(document).ready(function() {
//var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
var postData = $('#registerForm').serialize(); // here
$.ajax({
//...
});
});
});
First of all I want to say that you should use prepared statements.
Althought you sanitize user input(GOOD) its still recommended using prepared statements.
Not only does it help with readability its also more secure.
Make sure your form sends following postdata:
{name:"YourName", surname:"Yoursurname",date:"<dateobject>",email:"sample#mail.com",user:"username",password:"password}
== THIS LOOKS OK ==
$name = mysql_real_escape_string($_POST["name"]);
$surname = mysql_real_escape_string($_POST["surname"]);
$date = $_POST["date"];
$email = mysql_real_escape_string($_POST["email"]);
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
enter code here
If the conditions above are the same the server should receive all your data. I do see a problem in your query that may be the problem.
What you are doing is inserting everything as string in the database. You have to make sure when you try to execute a query given values for a table that the given values correspond with the database.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
('$name', '$surname', '$date', '$email', '$user', '$pass')"); //insert
Make sure everything is correct for example your date column in the database is it a string or a mysql date TYPE. Try to lose the '.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
($name, $surname, $date, $email, $user, $pass)");

Ajax getting a value from php?

I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}

Categories

Resources