String with special chars from Ajax POST to DB insert - javascript

i have a form with some text inputs, then i have an ajax event to send this value via POST to my database php script, the issue is that i dont know how to send special chars from my ajax event, if the string has ' " \ or similar chars, it wont insert data to my database, but if the string only contains Numbers/Letters and no special chars...i can insert the data without a problem.
Ajax event
$$("#message").click(function(e) {
var nick_ = window.localStorage.getItem("username");
var message_ = $.trim(($("#msgtext").val()).replace(/(\r\n|\n|\r)/gm,""));
if (message_ .length>0 && message_ .length<=500)
$.ajax({type: "POST",
url: "insert.php",
data: ({nick: nick_, mensaje: message_ }),
cache: false,
dataType: "json",
success: function(data) {
if(data.status == 'success'){
$('input[type=text], textarea').val('');
}
}});
else myApp.alert('Min:1 Max:500','Chars:');
});
And this is my database script
<?php
//jSON
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
//Connect to DB
include('con.php');
//POST vars
$nick=htmlspecialchars(trim($_POST['nick']));
$message=htmlspecialchars(trim($_POST['mensaje']));
$date=date("Y-m-d H:i:s");
//DB insert
$mysqli->real_query("INSERT INTO messages VALUES ('0','$nick','$message','$date')");
if ($mysqli) $response_array['status'] = 'success';
else
$response_array['status'] = 'error';
echo json_encode($response_array);
?>

before sending your data ({nick: nick_, mensaje: message_ }) in ajax, you can verify it using:
function isValid(data){
for (i in data){
if(!data[i].match(/^[a-zA-Z0-9]*$/))
return false;
}
return true;
}
use it like:
isValid({nick: nick_, mensaje: message_ })
this will return true if the data is either letter or character, and false otherwise.
Moreover, you should not be relying on any client side script for this kind of validation.

The problem is in your php script. Try this
$v = trim($_POST['mensaje']);
$message = htmlspecialchars($conn->escape_string($v));
All i did is to escape the post value.
And also the way you are checking if your query was sucessfull should be changed. you are checking the conn object instead of catching a return boolean value from the $conn->real_query () which should give you the real outcome of your query processing (True of false).
$result = $conn->real_query("........);
if ($result){
//do something
}else{
echo $conn->error;
}

If you have a form you can try data:$(this).serializeArray() which escapes those characters
OR
You can use an editor which I would recommend something like tinyMCE.

Related

Handling ajax response exceptions

I am currently handling a form with php and calling it via an ajax request, i want to handle exceptions showing a small div instead of the basic popup
so i did multiple if conditions based on the responsetext, however one of the exceptions doesnt get handled
This exception is the empty fields exception it always shows the wrong username or pw instead
here is the ajax call
function sendLogin(){
username = $('#loginEmail').val();
password = $('#loginPassword').val();
a = $.ajax({
type: 'post',
data: 'username='+username+'&password='+password,
url: '/account/login.php',
async: false,
});
if(a.responseText == "LoggedIn"){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeOut("fast");
$("#LoggedIn").fadeIn("fast");
setTimeout(location.reload(),2200);
}
else if(a.responseText == "Empty_Fields") {
//alert(a.responseText);
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeIn("fast");
}
else if(a.responseText == "Wrong_Credentials") {
//alert(a.responseText);
$("#Empty_Error").fadeOut("fast");
$("#WrongPW_Error").fadeIn("fast");
}
}
and here is the php file
<?php
if(!isset($_POST['username']) || !isset($_POST['password'])){
echo "Empty_Fields";
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$hashed_pass = hash("sha512", $password);
$stmt = $dbh->prepare("SELECT Count(email)as total, username from Users where email = :username and password= :password");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $hashed_pass, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total = $row['total'];
if($total == 1){
session_start();
$_SESSION['user'] = $username;
$_SESSION['user_name'] = $row['username'];
echo "LoggedIn";
die();
}
else{
echo "Wrong_Credentials";
die();
}
?>
You are not performing the correct check in PHP to see if the POST variables are empty.
Read: What's the difference between 'isset()' and '!empty()' in PHP?
isset($_POST['username'])
will return true if the POST parameter exists, even if its content is an empty string. You need both tests: isset AND empty.
if(!isset($_POST['username']) || !isset($_POST['password'])){
echo "Missing_Param";
die();
}
if(empty($_POST['username']) || empty($_POST['password'])){
echo "Empty_Fields";
die();
}
Edit: I did not notice that you're using async: false; leaving this answer for reference. In general it's a good idea to use non-blocking calls in JS so other UI elements aren't affected.
$.ajax does not return anything; it's an asynchronous call that will call a function when it completes. You'll need to do something like this:
$.ajax({
// other arguments here
success: function(data) {
// handle success
},
error: function() {
// handle error
}
});
More examples available here and here.
Instead of calling die() on your PHP code, send an error response. Call http_response_code(401) (not authorized response). Second issue is that $.ajax doesn't return a response and async = false has been deprecated and should not be used. Instead, define two functions for success and failure and just set those as the success and error parameters of your AJAX request.
$.ajax({
type: 'post',
data: 'username='+username+'&password='+password,
url: '/account/login.php',
async: false,
success: successFunction,
error: errorFunction
});
function successFunction(response){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeOut("fast");
$("#LoggedIn").fadeIn("fast");
setTimeout(location.reload(),2200);
}
function errorFunction(response){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeIn("fast");
}

AJAX to PHP --> PHP not picking up the pass

I am still a noobie and still learning, but I can't understand why the data from an AJAX call is not being passed successfully into the PHP.
Where have I gone wrong here? I have literally spent hours on hours and I can't understand why the AJAX call hasn't posted this into the PHP. I believe there must be something wrong with either the data attribute from " data: name+email" in the ajax call OR there is something wrong in the PHP side retrieving the data post from AJAX....
I am totally confused...
Thanks for your help (and go easy on me!)
Thanks
<?php
include_once 'db.php';
$fullname = $_POST['name'];
$email = $_POST['email'];
//this is the new stuff we are putting in
mysqli_select_db('table1');
if(isset($_POST['email']))
{
$checkdata = "SELECT signup_email_of_user FROM table1 WHERE signup_email_of_user = '$email'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0)
{
echo "err";
exit();
}
else {
$sql = "INSERT INTO table1 (signup_name_of_user, signup_email_of_user) VALUES ('$fullname', '$email')";
mysqli_query($conn, $sql);
echo 'ok';
die;
}
}
?>
function submitform1(){
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#signup_name_of_user').val();
var email = $('#signup_email_of_user').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#signup_name_of_user').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#signup_email_of_user').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#signup_email_of_user').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'test_signup.php',
data: name+email,
beforeSend: function () {
$('.btn-light').attr("disabled","disabled");
$('.sign-up').css('opacity', '.5');
},
success: function(msg){
if(msg == 'ok'){
$('#signup_name_of_user').val('');
$('#signup_email_of_user').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
}
});
}
}
This is indeed wrong:
data: name+email
Values are sent as key/value pairs. All you're sending is a value without a key. How would the server-side code know how to retrieve that value without a key? Instead, consider something like this:
data: { 'name': name, 'email': email }
Then server-side you can retrieve the values by their keys:
$_POST['name']
or:
$_POST['email']
Note: The keys don't need to be the same name as the variables which hold the values. They just seem to be reasonably applicable names in this case. You could just as easily do this:
data: { 'first': name, 'another': email }
and retrieve the values with the updated keys:
$_POST['first']
As your form grows in complexity, there are a variety of ways to create an object in JavaScript to define the keys and values. You could serialize an entire <form> in a single line of code, for example. Or perhaps define more complex objects in JSON, serialized, and then de-serialize them server-side. But starting with some simple key/value pairs would work just fine here.
Your data seems to be malformed, try this:
var data = {};
data.name = $('#signup_name_of_user').val();
data.email = $('#signup_email_of_user').val();
and in the ajax: data: data,
According to jQuery documentation data attribute accepts following formats:
Type: PlainObject or String or Array
where the PlainObject is the one we need here:
var data = {'objectmember': 'objectvalue'};

Comparing strings in JQuery not working

Alright so here's the situation. I have the following code block in my php file, and for some reason, whenever it comes to check data, it doesn't accept. I've printed out the value of data, and it is indeed "accepted" (without quotes obviously). Am I comparing these wrong somehow? Running basically the exact same code in another section of my website and it works fine.
$(document).ready(function () {
$("#sign").click(function () {
jQuery.ajax({
url: "loginConfirm.php",
data: { // Correct
username: $("#username").val(),
password: $("#password").val()
},
type: "POST",
success: function (data) {
if ($("#username").val() === "") {
//Do nothin
} else if (data === "accepted") {
alert("Here");
redirectSignIn();
} else {
alert("There");
$("#signInTitle").html(data);
}
},
error: function () {}
});
});
});
EDIT: php code I'm calling in the url below
<?php
// The global $_POST variable allows you to access the data sent with the POST method
// To access the data sent with the GET method, you can use $_GET
$username = htmlspecialchars($_POST['username']);
$userpassword = htmlspecialchars($_POST['password']);
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("SELECT count(*) FROM loginInfo WHERE userName='" . $username . "' AND password='" . $userpassword . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0)
echo "accepted";
else
echo "denied";
?>
You cant validate if ($("#username").val() === "") { in success function. For that you are suppose to validate it before making Ajax call.
I would like to give some advice here that first you have to validate the inputs of the user if validate then you can call ajax.
and then you not required to check the value of the username in AJAX process.
Like....
if($("#username").val() === "" && $("#passoword").val() === "")
{
//AJAX call
}
else
{
//alert to enter the valid inputs
}
hope you get it my concept...

Ajax POST to PHP - How do I do a reply?

I have sent an email address via an ajax post from javascript to php. I have then searched the database in php to find out if this email exists in the database. How can i then send a message back to the javascript/html to say that the value was present?
This is what I used to send the request:
function postEmail(){
var checkEmail = "someone#gmail.com";
var dataString = 'checkEmail1='+ checkEmail;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "myfile.php",
data: dataString,
cache: false,
success: function(result){
alert("Sent successfully");
}
});
}
and then in the PHP:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
if ($row == 0 ) {
echo "email doesnt exist";
}
}
Not sure if I should do a get request? Or if you return values or something. Thanks.
(p.s, Im developing a hybrid app so need to use JSON to send/retrieve from PHP)
I think you need to remove second condition! output json or any other format you want. I use json_encode for arrays
try:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
echo "email doesnt exist";
}
JAVASCRIPT
from your success function, print the result to the console to see the output
console.log(result);
What you echo from the PHP script is sent back to the success function in the javascript, as the result parameter. So the result parameter will contain "email already exists" or "email doesnt exist"

jQuery AJAX Call to PHP Script with JSON Return

I've been smashing my head against a brick wall with this one, i've tried loads of the solutions on stackoverflow but can't find one that works!
Basically when I POST my AJAX the PHP returns JSON but the AJAX shows Undefined instead of the value:
JS:
/* attach a submit handler to the form */
$("#group").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/*clear result div*/
$("#result").html('');
/* get some values from elements on the page: */
var val = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "inc/group.ajax.php",
type: "post",
data: val,
datatype: 'json',
success: function(data){
$('#result').html(data.status +':' + data.message);
$("#result").addClass('msg_notice');
$("#result").fadeIn(1500);
},
error:function(){
$("#result").html('There was an error updating the settings');
$("#result").addClass('msg_error');
$("#result").fadeIn(1500);
}
});
});
PHP:
$db = new DbConnector();
$db->connect();
$sql='SELECT grp.group_id, group_name, group_enabled, COUNT('.USER_TBL.'.id) AS users, grp.created, grp.updated '
.'FROM '.GROUP_TBL.' grp '
.'LEFT JOIN members USING(group_id) '
.'WHERE grp.group_id ='.$group_id.' GROUP BY grp.group_id';
$result = $db->query($sql);
$row = mysql_fetch_array($result);
$users = $row['users'];
if(!$users == '0'){
$return["json"] = json_encode($return);
echo json_encode(array('status' => 'error','message'=> 'There are users in this group'));
}else{
$sql2= 'DELETE FROM '.GROUP_TBL.' WHERE group_id='.$group_id.'';
$result = $db->query($sql2);
if(!$result){
echo json_encode(array('status' => 'error','message'=> 'The group has not been removed'));
}else{
echo json_encode(array('status' => 'success','message'=> 'The group has been removed'));
}
}
JSON Result from firebug:
{"status":"success","message":"success message"}
AJAX Displays the JSON result as Undefined and I dont have a clue why. I have tried displaying adding dataType='json' and datatype='json'. I have also tried changing it to data.status and data['status']: still no joy though.
Any help would be really appreciated.
Make it dataType instead of datatype.
And add below code in php as your ajax request is expecting json and will not accept anything, but json.
header('Content-Type: application/json');
Correct Content type for JSON and JSONP
The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.
I recommend you use:
var returnedData = JSON.parse(data);
to convert the JSON string (if it is just text) to a JavaScript object.
Use parseJSON jquery method to covert string into object
var objData = jQuery.parseJSON(data);
Now you can write code
$('#result').html(objData .status +':' + objData .message);
try to send content type header from server use this just before echoing
header('Content-Type: application/json');
Your datatype is wrong, change datatype for dataType.

Categories