Nested if statement not firing - php

I am posting data to my db, however, before I do I have set in my php to echo out any issues. When the 'data != 'signup success' it should run the if within it, this does not work. Any ideas ?
PHP:
if($u == ""){
echo "Please create a username";
exit();
}
Js:
var submitBtn = $('#signUpBtn');
submitBtn.on('click', function() {
var fn = $('#fname'),
ln = $('#lname'),
u = $('#uname'),
e = $('#email'),
p = $('#pword1'),
p2 = $('#pword2'),
fnVal = fn.val(),
lnVal = ln.val(),
uVal = u.val(),
eVal = e.val(),
pVal = p.val(),
p2Val = p2.val();
$.post('phpsrc/parsers/signUp.php',
{fn: fnVal, ln: lnVal, u: uVal, e: eVal, p: pVal},
function(data) {
if (data != 'signup success') {
if (data === 'Please create a username') {
alert('uname');
}
} else {
}
}
);
});

You'd be better off json encoding the data:
if($u == ""){
$data = array("response" => "Please create a username");
exit(json_encode($data));
}
Allowing you to check the response in your ajax request like this:
function(data) {
if (data.response !== 'signup success') {
if (data.response == 'Please create a username') {
alert('uname');
}
} else {
alert('something');
}
}

Related

php web service cannot read my angular js key value

I am using angularjs 1.6.4 version, I send my keys and values to php web service but my key and value does not read, I get result for in database stored at '0', this is my angular js code,
$scope.fav = {
"userid":101,
"favid":120
}
$http({
method:"POST",
url:apiurl+"addFavorites.php",
data:JSON.stringify($scope.fav)
}).then(function(data)
{
$scope.favorites = data.data;
alert(data.data.message);
});
this is my php rest api
include("../includes/db.php");
//creating response array
$response = array();
$request_method = $_SERVER['REQUEST_METHOD'];
if ($request_method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
$request_method = 'DELETE';
} else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
$request_method = 'PUT';
} else {
throw new Exception("Unexpected Header");
}
}
if($request_method == "POST"){
//getting values
$userid = isset($_POST['userid']) && $_POST['userid'] != '' ? trim($_POST['userid']) : "";
$favid = isset($_POST['favid']) && $_POST['favid'] != '' ? trim($_POST['favid']) : "";
if ($favid == 0) {
$strupdate = mysql_query("insert into nr_favourites(UserProfileId,FavouriteUserProfileId,CreatedDate)Values('$userid','$favid',now())");
}
if ($favid != 0) {
$sql = mysql_query("select * from nr_favourites where id=$favid");
$rc = mysql_num_rows($sql);
if ($rc != 0) {
$strupdate = mysql_query("insert into nr_favourites(UserProfileId,FavouriteUserProfileId,CreatedDate)Values('$userid','$favid',now())");
}
}
if ($strupdate)
{
$response['error']=false;
$response['message']='add favourites successfully!';
}
else
{
$response['error']=true;
$response['message']='add favourites not successfully.';
}
} else {
$response['error']=true;
$response['message']='You are not authorized';
}
header('Content-Type: application/json');
echo json_encode($response);
those are my code, please help me to solve this error
It looks like you may be saving strings to numerical fields. When JSON.stringify($scope.fav) is called the numbers are converted to strings.
Here
$userid = isset($_POST['userid']) && $_POST['userid'] != '' ? trim($_POST['userid']) : "";
$favid = isset($_POST['favid']) && $_POST['favid'] != '' ? trim($_POST['favid']) : "";
since user_id and favid are strings they are set to empty strings every time. My guess would be both
nr_favourites.UserProfileId
nr_favourites.FavouriteUserProfileId
are numerical fields which are receiving strings hence the 0 values. Remove JSON.stringify() and save nulls rather than empty strings, this should take care of the issue.

Passing Special Characters to PHP via AJAX

I'm collecting form data, sending that to PHP validation script through AJAX call. The issue is on special characters the php validation script is not working as expected.
HTML:
<input type="text" name="firstName" class="firstName"
placeholder="[first name]" required autofocus maxlength="25" size="25" />
JS:
$(".button").click(function () {
var firstName = encodeURIComponent($("input.firstName").val());
var datastring = "firstName=" + firstName;
$.ajax({
type: "POST",
url: "/scripts/validateSignup.php",
data: datastring,
cache: false,
success: function (errorMessage) {
//print to screen
}
});
});
PHP Validation
$postData = $_POST;
if (Filter::validateString($postData['firstName']) == false) {
echo "Oops! Some characters used in your first name are not valid.";
}
PHP Filter
//Returns true if string is good, false otherwise
public static function validateString($string) {
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.\,\-\_\'\"\#\?\!\:\;\$\#\%\&\+\= a-zA-Z0-9()]/", $string) == true) {
return false;
} else {
return true;
}
}
}
On an empty string it prints error to screen just fine. But if I do something like "~!##$%^&*()", then it accepts the string as good and doesnt throw and error, even though the result of preg_match == false.
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/", $string) == true) {
return false;
} else {
return true;
}
}
That is more valid regex, but not the result you want: you're checking for pretty much all input, so it'll match "abcd" and return false as well. There are 11 characters with special meanings to regular expressions, only those and the " need to be escaped: ^$[]()|.*+-
Try this:-
<?php
$string = "tes$%tname"; // invalid string
//$string = "testname"; // valid string
if(test($string) == false)
{
echo "String is invalid";
}
function test($string){
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/",$string) == true) {
return false;
} else {
return true;
}
}
}
?>
PHPFiddle is here:- http://phpfiddle.org/main/code/cdu-xg2

retrieving Message from a json array

I want to check the username availability while users register. I am working on the front end. The backend code was given to me.
These are the php code in signup.php
if (isset($_GET['chkusername']))
JSON_username_avail($_GET['chkusername']);
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username, $ret));
die();
}
function validate_username($username, & $retval_arr) {
if ($username == NULL)
$retval_arr['E_UserName'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['E_UserName'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['E_UserName'] = "USERNAME_EXISTS";
return $retval_arr;
}
function username_validation($user) {
$username = str_split($user);
foreach($username as $i) {
$i = ord($i);
if ($i >= 48 and $i <= 57)
continue;
if ($i >= 65 and $i <= 90)
continue;
if ($i >= 97 and $i <= 122)
continue;
return FALSE;
}
return TRUE;
}
function data_not_exists($table, $field, $data, $CSense = FALSE) {
$conn = connect_db();
$data = filter_var($data, FILTER_SANITIZE_STRING);
if ($CSense == TRUE)
$sql = "SELECT * FROM ".$table.
" WHERE ".$field.
"='".$data.
"'";
else
$sql = "SELECT * FROM ".$table.
" WHERE upper(".$field.
")='".$data.
"'";
$result = mysqli_query($conn, $sql);
switch ($result - > num_rows) {
case 0:
return TRUE;
break;
case 1:
return FALSE;
break;
default:
die("500 Internal Server Error: 122");
} //switch
}
Now I dont know that much of php. I created a javascript function to send the username to the signup.php page for validation.
Here is my function
function submit_form() {
var u = document.getElementById("username").value;
$.post("signup.php", {
"chkusername": u
},
function (data) {
var x = data; //here i dont know how to get the return string. Whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS.
}, "json");
}
here i am getting the value of x as [object Object].
But i need to store the return message in variable x. I want to know whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS. Kindly help me with that.
The username is POSTed but in the PHP you try to access it with $_GET, change to:
if (isset($_POST['chkusername']))
JSON_username_avail($_POST['chkusername']);
Also your validation logic doesn't look right, what if the username is valid and available? I would add an else clause and set a success variable:
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username));
die();
}
function validate_username($username) {
$retval_arr = array('success' => false, 'message' => '');
if ($username == NULL)
$retval_arr['message'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['message'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['msessage'] = "USERNAME_EXISTS";
else
$retval_arr['success'] = true;
return $retval_arr;
}
and the ajax:
if(!data.success){
console.log(data.message);
} else {
// valid and available
}
Try,
function(data){
var x = data.E_UserName;
}, "json");
also change your request to GET as per MrCode's answer
function submit_form() {
var u = document.getElementById("username").value;
$.get("signup.php", {
"chkusername": u
},
function (data) {
var x = data.E_UserName
}, "json");
}

PHP Ajax Form Integration return arrays

Using PHP and jQuery Ajax to build a basic log in system.
What I want to do is submit sections of a form via ajax and return an array. I'm not quite sure if I've got this one right.
Here is the PHP
if($access_function == 'access_login_1'){
$email = $_POST['access_email'];
$pwd = $_POST['access_pwd'];
if(!$email || !$pwd){
$error = 'Empty';
}
else {
$user = get_user($email);
if($user && $user['pwd'] == $pwd){
if($user['status'] == 1){
$action = 1;
}
else {
$order = 'Unauthorised';
}
}
else {
$error = 'invalid';
}
}
return array('action'=>$action,'error'=>$error,'order'=>$order);
}
The get_user function is like this::
function get_user($email){
global $cnx;
$q = $cnx->prepare("SELECT email FROM `users` WHERE email = :email");
$q->execute(array(':email' => $email));
return $q->fetch();
}
Now the jQuery is the real struggle. What I want is to submit the serialised values to this php. If the script returns an action of 1, I want to perform another script, I want $error to go into a div called error and order into a div called $order
This hasn't worked:
function sendvars(container,linkrul,perform){
var vars = 'access=1';
$(container).find('input').each(function(){
vars += '&' + $(this).attr('name') + '=' + $(this).val();
});
$.ajax({type:'POST',url:linkrul,data:vars,success:function(results){
if(results == 1){ }
else { $(container).find('.orders').html(results).slideDown(300); }
}
});
}
-- Hashing is off for not just while we test everything.
I would do it returning json encoded arrays:
if($access_function == 'access_login_1'){
$email = $_POST['access_email'];
$pwd = $_POST['access_pwd'];
if(!$email || !$pwd){
$resp = array(
'action' => $someValue,
'order' => $someValue,
'error' => 'No Email or password provided'
);
}
else {
$user = get_user($email);
if($user && $user['pwd'] == $pwd){
if($user['status'] == 1){
$resp = array(
'action' => 1,
'order' => $someValue,
'error' => 'No Error'
);
}
else{
$resp = array(
'action' => $someValue,
'order' => 'Unauthorised',
'error' => 'Order Error'
);
}
}
else {
$resp = array(
'action' => $someValue,
'order' => 'Unauthorised',
'error' => 'Invalid'
);
}
}
echo json_encode($resp);
}
And in js:
function sendvars(container,linkrul,perform){
var vars = 'access=1';
$(container).find('input').each(function(){
vars += '&' + $(this).attr('name') + '=' + $(this).val();
});
$.ajax({type:'POST',url:linkrul,data:vars,dataType:'JSON',success:function(results){
if(results.action == 1){
//do something
}else if(results.action == someOtherValue){
$(container).find('.orders').html(results.order).slideDown(300);
}else{
alert(results.error); //Or put the error in some div
}
//any other code or if/else statement
});
}
You need to think more carefully about what data is being sent from the PHP to the AJAX callback:
Remember that a PHP script cannot "return" anything, it simply "displays" it. So return array('action'=>$action,'error'=>$error,'order'=>$order); will not produce any output that the Javascript can read unless you then serialize it (turn it into a string and output it) in some way, such as XML or JSON (using json_encode()). You can test that the script is outputting something useful by looking at it directly in your browser, or using debug tools such as Firebug.
jQuery needs to know what encoding you've output your data in (see documentation on the dataType parameter). If it's XML, it will pass the whole XML document to your callback function, so you would need to use functions like .find and .each to inspect it. Probably the easiest is for your PHP to use header('Content-type: application/json'); (which tells jQuery you're using JSON) and echo some data using json_encode, so that your Javascript callback gets a simple Javascript object to work with.
Your current Javascript assumes that the result of the AJAX call is either an integer (result == 1) or a blob of HTML .html(results). A better approach would be to pass back the whole result structure shown in your PHP code (i.e. echo json_encode(array('action'=>$action,'error'=>$error,'order'=>$order));). Then you can check and act on each part of the structure separately (e.g. response.action == 1, .html(response.order)), and your code becomes more readable and more flexible for future situations.
Finally, jQuery has some built-in functions which can do some more of your work for you here: check out $.post as a short-hand for the AJAX call, and .serialize() (or its cousin .serializeArray()) for reading out the current values of form elements in a form you can send to the AJAX callback.
(Incidentally, I'm sure you'd have spotted this, but I presume linkrul should be linkurl)
This is also one option.
HTML
<input type='text' class='email' />
<input type='password' class='pass' />
PHP - checkLogin.php
<?php
$action = 0;
$order = 0;
$error = 0;
if(isset($_POST['email'], $_POST['pass'])) {
if(!empty($_POST['email']) && !empty($_POST['pass'])) {
$user = get_user($email);
if($user && $user['pwd'] == $_POST['pass']){
if($user['status'] == 1){
$action = 1;
} else {
$order = 'Unauthorised';
}
} else {
$error = 'invalid';
}
} else {
$error = "Empty";
}
$array = array('action'=>$action,'error'=>$error,'order'=>$order);
echo json_encode($array);
}
Javascript
function checkLogin(){
var email = $('.email').val();
var pass = $('.pass').val();
$.post('checkLogin.php', {email:email,pass:pass}, function(response) {
var result = $.parseJSON(response);
if(response['action'] == 1) {
//authorized
} else if(response['order'] == 'Unauthorised') {
//unauthorized
} else {
//error
}
});
}

Multiple row select with shift key using jqGridRender

I'd like to implement a multiselect function using jqGridRender (the php only version of jqGrid that uses javascript). Anyways i'm having troubles implementing it. I've found solution for javascript (and you can use javascript in predefinded function), which is here: http://www.trirand.com/blog/?page_id=393/help/multiselect-with-shift-to-emulate-the-same-behaviour-as-in-the-file-explorer/#p9963 I'm declaring this function as heredoc string ($myevent variable), and then call it under $gird->setGridEvent('onSelectRow', $myevent); but it doesn't work, here are the errors (but i'm not suer if they are the real cause):
Notice: Undefined variable: gird in C:\xampp\htdocs\kmedia\grid.php on line 72
Fatal error: Call to a member function setGridEvent() on a non-object in C:\xampp\htdocs\kmedia\grid.php on line 72
I'd also like to ask, how do i make cellEdit function, save the changes into variable, since when i'm setting grid options to cellEdit it works, but doesn't save etc.
You can use Oleg great suggestion from other answer (I modified it a bit):
$.extend($.fn.jqGrid, {
bindKeys: function (settings) {
var o = $.extend({
onEnter: null,
onSpace: null,
onLeftKey: null,
onRightKey: null,
scrollingRows: true
}, settings || {});
return this.each(function () {
var $t = this;
if (!$('body').is('[role]')) { $('body').attr('role', 'application'); }
$t.p.scrollrows = o.scrollingRows;
$($t).keydown(function (event) {
if (isInlineEdit()) {
return; // am if removed space etc does not work in inline edit
}
var target = $($t).find('tr[tabindex=0]')[0], id, r, mind,
expanded = $t.p.treeReader.expanded_field;
if (!target && $t.p.selrow !== null) {
r = $("#" + $t.p.selrow);
if (r.length > 0) {
target = r[0];
}
}
//check for arrow keys
if (target) {
mind = $t.p._index[target.id];
if (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
// up key
if (event.keyCode === 38) {
r = target.previousSibling;
id = "";
if (r) {
if ($(r).is(":hidden")) {
while (r) {
r = r.previousSibling;
if (!$(r).is(":hidden") && $(r).hasClass('jqgrow')) { id = r.id; break; }
}
} else {
id = r.id;
}
}
if ($.inArray(id, $t.p.selarrrow) === -1) {
if (!event.shiftKey) {// AM. added for shift+up arrow
$($t).jqGrid('resetSelection');
idsOfSelectedRows = []; // AM. Added
}
// todo: how to unselect row if shift is hold?
// this only selectcts row
$($t).jqGrid('setSelection', id);
saveWindowState();
} else {
$t.p.selrow = id;
}
}
//if key is down arrow
if (event.keyCode === 40) {
r = target.nextSibling;
id = "";
if (r) {
if ($(r).is(":hidden")) {
while (r) {
r = r.nextSibling;
if (!$(r).is(":hidden") && $(r).hasClass('jqgrow')) { id = r.id; break; }
}
} else {
id = r.id;
}
}
if ($.inArray(id, $t.p.selarrrow) === -1) {
if (!event.shiftKey) {// AM. added for shift+up down arrow
$($t).jqGrid('resetSelection'); // AM. added
idsOfSelectedRows = [];
}
// todo: how to unselect row if shift is hold?
// this only selectcts row
$($t).jqGrid('setSelection', id);
saveWindowState();
} else {
$t.p.selrow = id;
}
}
// left
if (event.keyCode === 37) {
if ($t.p.treeGrid && $t.p.data[mind][expanded]) {
$(target).find("div.treeclick").trigger('click');
}
if ($.isFunction(o.onLeftKey)) {
o.onLeftKey.call($t, $t.p.selrow);
}
}
// right
if (event.keyCode === 39) {
if ($t.p.treeGrid && !$t.p.data[mind][expanded]) {
$(target).find("div.treeclick").trigger('click');
}
if ($.isFunction(o.onRightKey)) {
o.onRightKey.call($t, $t.p.selrow);
}
}
return false;
}
//check if enter was pressed on a grid or treegrid node
else if (event.keyCode === 13) {
if ($.isFunction(o.onEnter)) {
o.onEnter.call($t, $t.p.selrow);
}
return false;
} else if (event.keyCode === 32) {
if ($.isFunction(o.onSpace)) {
o.onSpace.call($t, $t.p.selrow);
}
return false;
}
}
});
});
}
});

Categories