AJAX/PHP send values to server - php

I'm trying to use AJAX to send values to PHP file, which then updates mysql database on the server. But for some reason the values are not transferred to PHP file.
This is the JS I use:
function send_message()
{
var number = localStorage.getItem("number");
var message = prompt("Message:", "");
jQuery.ajax({ type: "POST",
url: serviceURL + "message.php",
data: 'number='+number+'&message='+message,
cache: false,
success: function(response)
{
alert("message sent");
}
});
}
And this is the message.php
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$number = $_GET['number'];
$message = $_GET['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>
Everything else is inserted to mysql except the number and message are NULL. What could be the reason for this?

You're posting data with AJAX using POST. In order to listen for those values in PHP you need to...
Replace:
$number = $_GET['number'];
$message = $_GET['message'];
With:
$number = $_POST['number'];
$message = $_POST['message'];

To make things simpler just use a convenience method like $.post or $.get for ajax calls in jQuery:
function send_message()
{
var number = localStorage.getItem("number");
var message = prompt("Message:", "");
$.post(serviceURL + "message.php", {'number' : number, 'message' : message},
function(response){
alert("message sent");
}
);
}
Then in your php:
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
//if you used $.get you will also have to use $_GET here
$number = $_POST['number'];
$message = $_POST['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>
I can see that you're using prepared statements in PDO. But you may also want to add:
Filter Vars and Filter Input for additional security.

Use $_POST instead of $_GET.
Also, you can try to use $_REQUEST global array to forget about it. It has all the data you have sent to script.

You may change your php file to;
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$number = $_POST['number'];
$message = $_POST['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>

Related

JQUERY AJAX GET and POST accessing different files?

I am doing email verification on my website. When user submits the form, it starts ajax post request, which posts the email to PHP which compares it with a datebase.
Than still in the form verification process, I have ajax GET request, which should return from the same PHP file whether the email has already been used.
But. Everything works fine when I proceed to the PHP, but GET request is always blank. URL of POST request is EmailDuplication.php but URL of GET is EmailDuplication?_=somerandomnumbers. Might that be the problem?
I am not experienced in this, will be glad for any help.
Here are the codes
JavaScript
function EmailSendForDupe()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'post',
async: false,
cache: false,
timeout: 30000,
data: {email: email.toString},
success: function (){
window.alert("email sent");
}
});
}
function EmailDuplication()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
async: false,
cache: false,
timeout: 30000,
success: function (callback){
console.log(callback.length);
console.log(callback);
if (callback.length !== 0){
window.alert("Email is already in use");
return false;
}
else {
window.alert("Email valid");
return true;
}
}
});
}
PHP
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}
else {
echo "User Email is already in use.";
}
}
?>
First, I would advise cleaning up your PHP and making sure it is not vulnerable to SQL Injection.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
$returnData = new array();
$conn = mysqli_connect($servername, $username,$password,$dbname);
if (mysqli_connect_errno()) {
$returnData['SQL Error'] = "Connect failed: %s\n", mysqli_connect_error();
header('Content-Type: application/json');
echo json_encode($returnData);
exit();
}
if(isset($_POST['email'])){
// POST
$email = mysqli_real_escape_string($conn, $_POST['email']);
$resultData["AHOJ"] = true;
$Emailquery = "SELECT * FROM Members WHERE email='$email' LIMIT 1;";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
$resultData['inUse'] = false;
$resultData['email'] = $_POST['email'];
} else {
$resultData['inUse'] = true;
}
} else {
// GET
$resultData["AHOJ"] = false;
$resultData['inUse'] = true;
}
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($returnData);
die();
?>
This will return JSON details back to your jQuery script and can be more helpful than plain text.
I also use mysqli_real_escape_string() to help escape any potential injection attempts. I would advise switching to Prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php
In your JavaScript, you will want to make a few changes too.
function EmailSendForDupe(email){
$.ajax({
url: '/files/EmailDuplication.php',
type: 'post',
cache: false,
timeout: 30000,
data: {
email: email.toString()
},
dataType: "json",
success: function (json){
console.log(json);
if(json.inUse == false){
alert("Email Sent to " + json.email);
} else {
alert("There may have been an error: " + json.error);
}
}
});
}
function EmailDuplication(email){
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
data: {
email: email.toString()
},
dataType: "json",
cache: false,
timeout: 30000,
success: function (json){
console.log(json);
if (json.inUse){
window.alert("Email is already in use");
} else {
window.alert("Email valid");
}
}
});
}
Hope this helps.
Generally you want to use async: true.
Also, you do not want to allow the form submit to actually Happen, as that blows away your whole page (reloads the entire thing, if not navigates to somewhere else entirely). So in fact the blank get you could be seeing could be the form submit blowing away your page.
If you are sending ajax requests, the trigger for those simply needs to be a button with a click handler, not an actual submit (unless in that submit input you do something like "onclick='doMyAjax();return false;'" so that the submit action does not actually occur).
If you are actually uploading a file, which for the purpose you appear to be showing here dear goodness please don't let the client drive that functionality via files on their system, the upload post needs a target to post To, so it does not hit your page. For that, the classic embedding of an iframe is still the way to go. Ugh.
posting to an iframe
I have no idea why Two requests need to be sent to do the job. It should probably be just one POST (assuming the ultimate outcome here is you want to send an email if it is a valid email), and the server checks the email and then does the send if it is valid.
And do not use GET versus POST to distinguish what the server should do (such as verifying an email versus sending one) - the Request itself or the Url, for example include "action=verifyEmail" in your form data being passed up, to tell the server what to do rather than it assuming just because it's a POST.
Hopefully some of this is helpful.
you are missing to handle GET Request Data.if some try to using get URL then your code don't have any condition to handle it. check modified code.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}else {
echo "User Email is already in use.";
}
}else{
echo " Get Method Data";
}
?>
Please try it and give your feedback.

PHP Login Script with Ajax loading Header on same page

I have a PHP login script that I want to execute with ajax. The PHP script takes the user to a page if successful but according to the ajax request I am using, the header location also loads in the $('.logresult') div how do I do it such that it goes to the header location when successful and shows the error in the $('logresult') if not. Below are my codes:
Ajax Request
$('#submit_log').click(function(e) {
e.preventDefault();
var data = $('#loginForm').serialize(),
form = $('#loginForm');
$.post($(form).attr("action"), data, function(data) {
$('.logresult').html(data);
})
});
PHP Login Script
session_start();
require_once ("db.php");
$db = new MyDB();
if(isset($_POST['log_name']) && isset($_POST['log_password'])) {
$username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['log_name']);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['log_password']);
$sql = $db->prepare("SELECT * FROM users WHERE uname = ?");
$sql->bindParam(1, $username, SQLITE3_TEXT);
$ret = $sql->execute();
$count = $db->prepare("SELECT COUNT(*) as COUNT FROM users WHERE uname = ?");
$count->bindParam(1, $password, SQLITE3_TEXT);
$count_ret = $count->execute();
if (count($count_ret) == 1)
{
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$id = $row['userid'];
$regas = $row['regas'];
$uemail = $row['uemail'];
$pword = $row['pword'];
if (password_verify($password, $pword))
{
$_SESSION['log_id'] = $id;
$_SESSION['log_name'] = $username;
$_SESSION['regas'] = $regas;
$_SESSION['uemail'] = $uemail;
header("Location: index.php?log_id=$id");
exit();
}
else
{
echo "Information incorrect";
exit();
}
}
}
}
I am guessing the issue is $('.logresult').html(data); but don't really know how to fix this (am new to ajax generally). Thanks
simply don't use ajax if you want to change the location. ajax usage is mostly when you don't want a page reload. in most cases ajax response is a json and handle the response with javascript.
If you want to change the location of the page after success, it is doable via your ajax, I do it all the time. It is also not unusual to have a site use ajax and redirect on success, I have seen it a lot. In your php, instead of doing:
header("Location: index.php?log_id=$id");
exit();
To keep it simple to work with your existing script, you can send back javascript:
die("<script>window.location='http://www.example.com/index.php?log_id={$id}';</script>");
If I were to redo what you have, I would receive json instead in the form of actions/instructions from the PHP and have the javascript in the success interpret the instructions, but that is more complex.

Json data not saved to DB in PHP

I am trying to make a functionality where I am sending Name and Age using ajax. The same is gathered by PHP and then stored to DB. I think I am doing it correctly but data not saved in database. Can someone help me out?
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
$.ajax({
url: 'addData.php',
type: 'POST',
dataType: "json",
data: {
name: $('#name').val(),
age: $('#age').val(),
}
})
});
});
</script>
</head>
<body>
<input id="name" type="text" />
<input id="age" type="text" />
<button>Click</button>
</body>
</html>
PHP
<?php
//Parameters for connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";
//Reading json
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$name = $data_back->{"name"};
$age = $data_back->{"age"};
// Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Creating Query
$sql = "INSERT INTO table1 (name, age) VALUES ($name, $age)";
//Running Query
$conn->query($sql);
//Closing Connection
$conn->close();
?>
ERROR
Even though you're sending data with jquery as json, php is still recieving it as a $_POST object. So, this should work:
$name = $_POST['name'];
$age = $_POST['age'];
I think your object $data_back is empty because of errors in parsing of data by function json_decode. You should try to use var_dump($data_back); exit; after json_decode or more advanced methods such as debugging.
I believe this is the proper way to access data post json_decode
$name = $data_back->name;
I also recommend looking into prepared statements for the database query execution...Ok, I HIGHLY recommend you look into it.
Edit: Maybe try this as well: Replace file_get_contents() with $_POST;

sent an object to my server with ajax, cant seem to get the data with php

I have sent two pieces of data to my PHP with this bit of AJAX:
function ajax_post(){
// Create our XMLHttpRequest object
var request = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "php/addUser.php";
var username = document.getElementById("newUserName").value;
var password = document.getElementById("newUserPass").value;
var newUsername = "user_name="+username;
var newPassword="password="+password;
request.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
document.getElementById("output").innerHTML = return_data;
}
};
// Send the data to PHP now... and wait for response to update the status div
request.send({newUsername,newPassword}); // Actually execute the request
This is the PHP code that is supposed to take these two pieces of data and plug it into my mysql database.
//Connect to the database
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
$userName=$_POST['newUsername'];
$userPassword=$_POST['newPassword'];
$query="INSERT INTO users(user_name,password)
VALUES('$userName','$userPassword')";
if ($connection->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $connection->error;
}
$connection->close();
When the AJAX is run, it runs with no errors and sends the data to my PHP code on my server. The PHP code then runs and completes with no errors but then when I check my database the new user is inserted into the database but it is empty. I'm pretty sure it's something in my PHP code, but I haven't figured it out yet.
The argument to request.send() should be a URL-encoded string, not an object.
request.send(newUsername + '&' + newPassword);
Note that you should also use encodeURIComponent when setting the variables, in case they contain special URL characters.
var newUsername = "user_name=" + encodeURIComponent(username);
var newPassword = "password=" + encodeURIComponent(password);
Also, your object syntax was incorrect. The syntax for objects is
{ prop1: value1, prop2: value2, ... }
{ var1, var2 } should have given you a syntax error.
You're also using the wrong $_POST keys. The keys should match the parameter names before =, not the IDs of the form fields.
$userName = $_POST['user_name'];
$userPassword = $_POST['password'];
You should also use a prepared statement in the PHP instead of variable substitution, to prevent SQL injection problems.
$query = "INSERT INTO users (user_name, password) VALUES (?, ?)";
$stmt = $connection->prepare("ss", $userName, $userPassword);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $stmt->error;
}
$connection->close();
You post user_name and password with ajax. But in your PHP code you used $_POST['newUsername'] and $_POST['newPassword']. You can change either the ajax or PHP.
Example:
$userName = $_POST['user_name'];
$userPassword=$_POST['password'];
And your request from ajax should be
request.send(newUsername+"&"+newPassword);

Access with ajax delivered data on a server side php-script

Okay my problem is the following:
I am trying to access a variable I defined with javascript in my executing php-script.
// CLIENT SIDE CODE
function deleteEntry() {
var action = '_includes/deleteEntry.php';
var method = 'post';
var data = '2';
$.ajax({
url: action,
type: method,
data: data
}).done(function(data){
$('.main').empty();
$('.main').append(data);
});
};
Now I want to make use of my data in a php-script (deleteEntry.php)
// SERVER SIDE CODE
<?php
// VERBINDUNG //
$connection = mysqli_connect('localhost', 'root', '', 'aufgabenplaner');
// if (!$connection){
// die('Verbindung nicht möglich : ' . mysql_error());
// }
// SQL-ABFRAGE //
$query = "DELETE FROM aufgaben WHERE job_nr =" ."DATA GOES HERE!!!";
$result = mysqli_query( $connection, $query );
include 'main-content.php';
?>
Where it says "DATA GOES HERE!!!" I want to make use of the data value, but I don't know how.
Normally you pass a JSON object as your POST
$.ajax({
url: action,
type: 'post', //put your declaration here for readability
data: {'var' : 2}
})
Then you would use $_POST['var'] in your PHP to get the value
You have to prepare data object so it has key - value pairs. This way you'll be able to access data in your PHP script. JavaScript:
function deleteEntry() {
var action = '_includes/deleteEntry.php';
var method = 'post';
var data = { number: '2'};
$.ajax({
url: action,
type: method,
data: data
}).done(function(data){
$('.main').empty();
$('.main').append(data);
});
};
PHP:
// SERVER SIDE CODE
<?php
// VERBINDUNG //
$connection = mysqli_connect('localhost', 'root', '', 'aufgabenplaner');
// if (!$connection){
// die('Verbindung nicht möglich : ' . mysql_error());
// }
// SQL-ABFRAGE //
$number = (int)$_POST['number']; // make sure it's no malicious input from user
$query = "DELETE FROM `aufgaben` WHERE `job_nr` = '" . $number . "'";
$result = mysqli_query( $connection, $query );
include 'main-content.php';
?>

Categories