cant get concat values and php not working - javascript

So my problem is that why jquery concat is not working and also it is not posting and can't inserted into the database
I tried changing the code and read references still cant get enough
This is my jquery
var uid = $('#lname').val() + $('fname').val() + $('#datecreated').val(moment().format('YYYY'));
var datecreated = $('#datecreated').val(moment().format('YYYY'));
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var password = $('#pass').val();
var passcheck = false;
This is my ajax
if (uid && fname && lname && email && password && datecreated)
{
var form = $(this);
var formData = new FormData(this);
$(".formcontent").hide();
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success:function(response)
{
this is my full code php, I dunno if the problem is with xampp or not. Im tackling this problem for 3 day straight now and I dunno where the problem is
valid['success'] = array('success' => true, 'messages' => array());
$uid = $_POST ['uid'];
$pass = $_POST['pass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$datecreated = $_POST['datecreated'];
if ($_POST)
{
if(true)
{
$sqlmail = "SELECT * FROM acc WHERE (email = '$email') AND acc_stat < 3";
$resmail = $connect->query($sqlmail);
if($resmail->num_rows > 0)
{
while($row = $resmail->fetch_array())
{
if($email === $row['email'])
{
$valid['messages'] = "Email address is already taken";
}
}
$valid['success'] = false;
$connect->close();
echo json_encode($valid);
}
else
{
$sql = "INSERT INTO 'acc' ('uid', 'password', 'lname', 'fname', 'email', 'acc_type', 'acc_stat','date_create') VALUES ('$uid', '$pass', '$fname', '$lname', '$email', '3', '1','$datecreated')";
if($connect->query($sql) === TRUE)
{
$valid['success'] = true;
$valid['messages'] = "Account registration successful.";
$connect->close();
echo json_encode($valid);
}
else
{
$valid['success'] = false;
$valid['messages'] = "Network connection not stable. Please try again later.";
$connect->close();
echo json_encode($valid);
}
}
}
else
{
$valid['success'] = false;
$valid['messages'] = "No internet connection.";
$connect->close();
echo json_encode($valid);
}
}

There is a small mistake in your code, please fix it and it should work fine. the error is at line
var uid = $('#lname').val() + $('fname').val() + $('#datecreated').val(moment().format('YYYY'));
chage it to var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));.
silly mistake of missing just #. one more thing, you will not receive the uid paramter in php side, just because you are not sending it with form. append it to FormData as give,
var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));.
var formData = new FormData(this);
formData.append('uid' , uid);
Now you will be able to recieve that uid parameter.

Try to use this:
var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));
var datecreated = $('#datecreated').val(moment().format('YYYY'));
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var password = $('#pass').val();
var passcheck = false;

Related

I can't redirect user after login

I have login page which take username and password from user after user will be login. I am getting response for successfully login. but I can not redirect to index.php.
I am getting console message that User successfully login, But then page is not redirect on other page.
My JS file is like this.
$(document).ready(function() {
//alert('ss');
$("#login-form").submit(function(e){
e.preventDefault();
var username = $("#email").val();
var password = $("#password").val();
var isValid = true;
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!re.test($("#email").val())){
isValid = false;
$("#message").html("Please enter valid email.");
}
if($('#remember').is(':checked')){
$.cookie('adminCookie', $("#loginUser").val(), { expires: 7 });
}
else{
if($.cookie('adminCookie') == null) {
$.removeCookie("adminCookie");
}
}
if(password == ""){
isValid = false;
$("#message").html("Please enter password.");
}
if(isValid){
$.ajax({
type : "POST",
url : "process/login.php?rand="+Math.random(),
data : {
username : $("#email").val(),
password : $("#password").val(),
}
}).
done(function(response){
//alert(response);
var JSONArray = $.parseJSON(rawJSON);
console.log(response);
if(jsonObj.success=="1"){
window.location("index.php");
}else{
$("#userDiv").addClass("form-group has-error");
$("#passDiv").addClass("form-group has-error");
$("#passWarning").css("display","");
$("#passWarning").html("Invalid User Name or Password");
$.when($('#passWarning').fadeOut(5000)).done(function() {
$("#userDiv").attr('class', 'form-group');
$("#passDiv").attr('class', 'form-group');
});
}
}).fail(function(){
}).always(function() {
});
}
});
});
my PHP file is looks like this.
<?php
include "../connection.php";
extract($_POST);
$data = array();
$resArr = array();
if (isset($_POST['username']) && isset($_POST['password'])) {
$check_user = mysqli_query($conn, "select * from cut_users where email like '$username' and password like '$password' and user_role like 'A'");
if ($check_user) {
if (mysqli_num_rows($check_user) > 0) {
$message = "Login successfully.";
$success = 1;
while ($row = mysqli_fetch_array($check_user)) {
if ($row['is_active'] == "0") {
$message = "Your account is blocked. Please contact admin.";
$success = 0;
}
$data["id"] = $row['cut_users_id'];
$data["name"] = $row['name'];
$data["emailID"] = $row['email'];
$data["device"] = $row['device_type'];
$data["is_reset"] = $row['is_reset'];
$_SESSION['userID'] = $row['cut_users_id'];
$_SESSION['name'] = $row['name'];
$_SESSION['emailID'] = $row['email'];
}
$resArr = array("success" => $success, "data" => $data, "message" => $message);
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Email or password invalid.");
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Something went wrong!!!" . mysqli_error($conn));
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Parameter Missing");
}
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>
1) Why you are using variable jsonObj instead of response ?
2) Modify your if statement like this
if(response.success==1){
window.location.href="index.php";
}
window.location is not a function it is an object. Please change href property in window.location object to redirect to new url.
window.location.href = "./index.php";
Simple redirect to specific file
if(jsonObj.success==1)
{
window.location.href = "http://www.example.com/index.php";
}

Getting an empty AJAX response from PHP

I have the following code but its getting an empty response when I check in firebug.
Here is the code:
function sendemail() {
var phone = escape($("#phone").val());
var reason = escape($("#reason").val());
var fname = "<?= $_SESSION['fname'];?>";
var lname = "<?= $_SESSION['lname'];?>";
var email = "<?= $_SESSION['email'];;?>";
getAjax("ajax.php?action=sendemail3",
"Please Wait...",
"phone" + phone +" & reason "+reason+" & fname "+fname+" & lname "+lname+" & email "+email");
}
And here is my PHP code:
case "sendemail3":
$name = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$to = 'xxx#xxx.edu';
$phone = $_REQUEST['phone'];
$reason = $_REQUEST['reason'];
$subject = 'Verification';
$cont="<html><body style=''>
<div style='width:100%;' >
<div style='width:50%;margin-left:20%'; >
<div style='text-align:center;font-size:16px;padding:5px;'>
<p>Hi $name $lname,</p>
<p>Thank you <p/>
</div></div></div>
</body></html>";
mail ($to, $subject, $cont);
echo "successfully sent";
break;
edit getAjax function
function getAjax(e, t, n) {
var a = null;
return $.ajax({
url: e,
beforeSend: function() {
$("#notify-container").show(), $("#msg").empty().html(t)
},
success: function(e) {
"gotosearch" == e && (window.location.href = "search.php"), "gotoprofile" == e && (window.location.href = "profile.php"), "hostpage" == e && (window.location.href = "search.php"), "tourpage" == e && (window.location.href = "search.php"), "gotohomenot" == e && ($("#email1").val(""), $("#pass1").val(""), $("#invalid").fadeIn("fast"), document.getElementById("invalid1").style.display = "none", document.getElementById("invalid2").style.display = "none"), "gohome" == e && ($("#email1").val(""), $("#pass1").val(""), $("#invalid2").fadeIn("fast"), document.getElementById("invalid1").style.display = "none", document.getElementById("invalid").style.display = "none"), "gonot" == e && ($("#email1").val(""), $("#pass1").val(""), document.getElementById("invalid").style.display = "none", document.getElementById("invalid2").style.display = "none", $("#invalid1").fadeIn("fast"))
},
type: "POST",
data: n,
async: !1
}), a
}
When I check in firebug the values does get send to the in a post but when I look at the response its empty. Anything I could do to fix it?
Thank you.

commands in chatroom & defining words after command

Okay basically I'm trying to have a action happen of alert('hi $message'); when a user enters the command /command lewis into the chatroom; In the alert I have stated the variable $message and this is the word followed by the command; for example /command $message. I have posted my script below; so basically what I'm trying to achieve is recognise when a user types /command followed by a $message into the textarea then perform an action.
Chatroom Javascript
name ='<? echo $chat_room_username; ?>';
$("#name-area").html("You are: <span>" + name + "</span>");
var chat = new Chat();
$(function() {
chat.getState();
// watch textarea for key presses
$("#sendie").keydown(function(event) {
var key = event.which;
//all keys including return.
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
// don't allow new content if length is maxed out
if (length >= maxLength) {
event.preventDefault();
}
}
});
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
var newdata = data.text[i].replace(/:brand/g,"<img src=\"/_img/logo1.png\"></img>");
newdata = newdata.replace(/:tipsound/g,"<audio autoplay><source src=\"/tip.wav\" type=\"audio/mpeg\"></audio>");
<?
$select_gifs = mysql_query("SELECT * FROM `submited_chatroom_gifs` WHERE `staff` = '1'");
while($gif = mysql_fetch_array($select_gifs)){
?>
newdata = newdata.replace(/:<? echo $gif['name']; ?>/g,"<img data-toggle=\"tooltip\" height=\"<? echo $gif['height']; ?>\" width=\"<? echo $gif['width']; ?>\"title=\":<? echo $gif['name']; ?>\" src=\"/_img/gifs/<? echo $gif['img']; ?>\"></img>");
<? } ?>
$('#chat-area').append($("<p>"+ newdata +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
process.php
<?php
$function = $_POST['function'];
$room = $_GET['room'];
$log = array();
switch($function) {
case('getState'):
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = $_POST['nickname'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
fwrite(fopen($room . '.txt', 'a'), "<p><font size=\"2px\">". $nickname . ": " . $message = str_replace("\n", " ", $message) . "</font></p>\n");
}
break;
}
echo json_encode($log);
}
?>
the alert is only for the person who wrote the command in
Thankyou for any help, and I apologise for the lengthy question.
[edit] Sorry just re-read my question and I will just try and explain what I'm trying to achieve in abit more detail. So basically when a user inputs /command lewis the script would then perform an alert('Hi Lewis');. But then if a user was to enter /command john the alert would be alert('Hi John');.
The alert would be instead of posting the message to the chatroom.

what can I do to prevent xss code?

I have escaped my fields, but when I make an xss code like <script>alert(one frame);</script> then the table which is specially for display the date the xss code is sent it to my database. I want when I make my own xss code dont send the JS script to my database.
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
my controller
case 'add_product':
if(isset($_POST['code']) && $_POST['code']!= '' && isset($_POST['product']) && $_POST['product']!= '' && isset($_POST['sale_type']) && $_POST['sale_type']!= '' && isset($_POST['purchase_price']) && $_POST['purchase_price']!= 0 && isset($_POST['sale_price']) && $_POST['sale_price']!= 0 && isset($_POST['min_stock']) && $_POST['min_stock']!= '' && isset($_POST['max_stock']) && $_POST['max_stock']!= '' ){
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
$newProduct = new product();
if($newProduct->add($code,$product,$sale_type,$purchase_price,$sale_price,$min_stock,$stock)){
echo "success";
}else{
echo "it cannot be added";
}
}
else{
echo "something went wrong";
}
break;
my javascript function
function addProduct(){
var code = $('#code').val();
var product = $('#product').val();
var sale_type = $('#sale_type').val();
var purchase_price = $('#purchase_price').val();
var sale_price = $('#sale_price').val();
var min_stock = $('#min_stock').val();
var max_stock = $('#max_stock').val();
var valCheck = verificar();
if(valCheck == true){
$.ajax({
url: '../controller/product_controller.php',
type: 'POST',
data: 'code='+code+'&product='+product+'&sale_type='+sale_type+'&purchase_price='+purchase_price+'&sale_price='+sale_price+'&min_stock='+min_stock+'&max_stock='+max_stock+'&boton=add_product',
}).done(function(ans){
if(ans == 'success'){
$('#code,#product,#purchase_price,#sale_price').val("");
$('#sale_type').val('0');
$('#min_stock,#max_stock').val('0');
$('#success').show().delay(2000).fadeOut();
searchProduct('','1');
}else{
alert(ans);
}
})
}
else {
}
}
XSS code in database
datable
While displaying data from database, use htmlspecialchars() function.

Save to XML via PHP

Okay i could be doing this %100 wrong I'm having trouble With the PHP to XML I'm just trying to save the customer details.......(not trying to be secure yet just learning how to do it)
The Html is a simple form
for firstname, lastname, password, email, and optional phone number (not needed at the moment)
The PHP code is initiated after the javascript calls it by the Javascript..
PHP
<?php
// header('Content-Type: text/xml');
session_register('Customer');
//session_start('customer');
$doc = new DOMDocument();
$doc->load('customer.xml');
$firstname = $_GET["firstName"];
$lastname = $_GET["lastName"];
$email = $_GET["email"];
$password = $_GET["password"];
$MDA = $_SESSION["Customer"]; //assign the session varaible to MDA
if (isset($firstname)) {
$customerArray = array();
$customerArray['firstname'] = $firstname;
$customerArray['lastname'] = $lastname;
$customerArray['email'] = $email;
$customerArray['password'] = $password;
$MDA[$firstname] = $customerArray;
$_SESSION["Customer"] = $MDA;
ECHO (toXml($MDA));
}
function toXml($MDA)
{
$doc = new DomDocument('1.0');
$Customer = $doc->createElement('Customers');
$Customer = $doc->appendChild($Customer);
$root = $doc->appendChild($doc->createElement('Root'));
foreach ($MDA as $a => $b)
{
$nodeA = $doc->createElement('NodeA');
$root->appendChild($nodeA);
$nodeA->appendChild($attr1);
$attr1 = $doc->createAttribute('firstname');
$attr1->appendChild($doc->createTextNode($a['firstname']));
$attr = $doc->createElement('firstname');
$attr = $Customer->appendChild($person);
$lastname = $doc->createElement('lastname');
$lastname = $person->appendChild($lastname);
$value = $doc->createTextNode($a);
$value = $lastname->appendChild($value);
$email = $doc->createElement('email');
$email = $person->appendChild($email);
$value2 = $doc->createTextNode($b['email']);
$value2 = $email->appendChild($value2);
$password = $doc->createElement('password');
$password = $person->appendChild($password);
$value3 = $doc->createTextNode($b['password']);
$value3 = $password->appendChild($value3);
}
$doc->formatOutput = true;
$strXml = $doc->saveXML();
//$doc->save('customer.xml');
return $strXml;
}
?>
and not to sure if its needed but the javascript... it just checks the password atm
var xHRObject = false;
if (window.XMLHttpRequest)
xHRObject = new XMLHttpRequest();
else if (window.ActiveXObject)
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
function test()
{
var firstname = document.getElementById("firstName").value;
var lastname = document.getElementById("lastName").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var password2 = document.getElementById("password2").value;
var number = document.getElementById("pNumber").value;
var type = "";
var input = document.getElementsByTagName("input");
xHRObject.open("GET", "testregristation.php?", true);
xHRObject.onreadystatechange = function() {
if (xHRObject.readyState == 4 && xHRObject.status == 200)
if (password != password2) {
alert("Password is wrong");
}
else
{
alert("test " +firstname + " " + lastname + " " + email + " : " + password);
document.getElementById('information').innerHTML = xHRObject.responseText;
}
xHRObject.send();
};
}
Out of date Browser issue, This works fine in Firefox

Categories

Resources