Checking Valid Membership - javascript

I just can't get my head around this, I'm probably just missing it but let me know if you can help.
Issue: It's stating that the User is a member, even though they are not.
For example if the user is not in the User Auth table, it should display "Not a Member" where if the user is in the table it should display "Member"
Issue
Table Structure :
user_auth table :
This is the Js that is executed on all pages
function GetUserinfo(token)
{
var info = { Token: token };
$.ajax({
type: "POST",
url: "http://localhost/Api/CurrentUser",
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$(".account .user").html(data.Username);
if(data.Member == 0)
{
$(".account .status").html("<p style=\"color:red;\">Not a member</p>");
} else {
$(".account .status").html("<p style=\"color:green;\">Member</p>");
}
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
console.log(xhr);
}
});
}
Rest API
` elseif($parameter == "CurrentUser") {
$params = $this->dataStream();
$user = new User(null, $params['Token']);
echo '{ "Username":"' . htmlspecialchars($user->fetch("username")) . '", "Member": ' . $user->hasMembership() . ' }';
http_response_code(200);
}
}`
Here is the hasMembership function
public function hasMembership()
{
$uid = $this->fetch("uid");
$this->queryObj->Execute("SELECT * FROM user_auth WHERE uid=:uid ", "prepare", array($uid), 0);
return ($this->queryObj->rows >= 1);
}
Any help will be greatly appreciated, thank you.

Related

pagination automatically sending multiple requests with laravel

hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me

Calling API | JavaScript to php | How to know if Response != 200, Print Error

Good day!
What I want to achieve is when user clicks the link, it will pass the parameter to javascript, which then using ajax to call the php file where my API is. The API will process the parameter and return a json result.
My code works when the parameter values are given correctly. However I'm stuck at the part where the values are incorrect/invalid and I need to catch the error.
The API document says that if the RESPONSE is 200, then it's a success. Else there is error. My issue is I have no idea how to get this "RESPONSE == 200". Any advise is appreciated!
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
if(res!=200)
{
alert("Invalid Wallet Address!");
}
else
{
alert(res);
}
}
});// ajax
} //end callMS_API
merklescienceAPI.php
<?php
$addr=$_POST['WalAddr']; //Wallet Addr
$cur=$_POST['CryCur']; //Cryptocurrency
$cur_code;
$result = "";
switch ($cur) {
case "Bitcoin":
$cur_code = 0;
break;
case "Ethereum":
$cur_code = 1;
break;
case "LiteCoin":
$cur_code = 2;
break;
case "Tether USD":
$cur_code = 10;
break;
}
require_once('../vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nAddress Risk Level : " . $data->risk_level_verbose;
//Whatever you echo will go to javascript success: function(res), and you can do alert(res)
echo $result;
?>
====================================================================
Edit + Solution
I read and tested further on the Guzzle thingy, and came across this thread. I implemented the Try Catch in the API.php and got my result.
Javascript function
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
alert(res);
}
});//ajax
} //end callMS_API
API.php
try{
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
}catch(Exception $e){
$error = true;
}
if($error == false)
{
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nRisk Level : " . $data->risk_level . " - " . $data->risk_level_verbose;
}else
{
$result = "Invalid Wallet Address!";
}
echo $result;
Thank you everyone for your help!
If you mean status code or HTTP status code 200 you could try add this line to your ajax option:
...
$.ajax({
...
statusCode: {
200: function() {
alert( "200 reaced" );
},
error: function(response) {
if(response.status != 200)
alert(" status code is " + response.status);
}
...
in Ajax
$.ajax({type:'POST',
url:'somefile.php',
data:{
a name:"a value"
} ,
success: <<THIS EXECUTES WITH A 200 RESPONSE>>,
error: <<THIS EXECUTES IF IT GOES BAD>>
});
The success: runs ONLY if the response is 200. for everything else you capture it with error:

wordpress ajax rest api ("code":"rest_invalid_json","message":"Invalid JSON body passed.")

I dont understand what i did wrong, can anyone give me a suggestion on what causes the above error below is my code. I can confirm that, i am hitting the route, succesfully because the code inside get it executed. I am also adding the 1 value at the end, to be passed it to json as per wp_send_json_success. At this point i dont know what to next, can anyone explaint to me, on what is going on?
route.php
function update_employee_photo($request){
global $wpdb;
$data_with_photo = array(
'photo' => $request['photo'],
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data_null_photo = array(
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data = ($request['photo'] != "null") ? $data_with_photo : $data_null_photo;
$where = array('wp_user_id' => get_current_user_id());
$result = $wpdb->update("aupair_registered_employee", $data, $where);
if($result){
wp_send_json_success($result, 200, 1);
} else {
wp_send_json_error($wpdb->last_query);
}
die();
}
add_action('rest_api_init', function(){
register_rest_route( 'activeAupair/v1', '/updateEmployeePhoto', [
'methods' => 'POST',
'callback' => 'update_employee_photo'
]);
});
file.js
$.ajax({
type: 'POST',
url: myAjax.restURL + 'activeAupair/v1/updateEmployeePhoto',
contentType: 'application/json',
datatype: 'json',
data: {
photo: photo,
photoPrivacy: getPhotoPrivacy(),
photoDescription: getPhotoDescription()
},
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', myAjax.nonce);
},
success: function(response){
console.log('TYPE OF ', typeof response);
console.log('RESPONSE ', response);
msg.empty();
msg.append($('<p id="required"></p>').text('Updated'));
uploadBtn.attr('value', 'Update');
uploadBtn.attr('disabled', false);
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function(data){
console.log('COMPLETE ', data);
}
});
As per the wordpress wp_send_json_success() function expect third parameter 1(default 0) to encode it into JSON format (see the reference). So you need to pass the status code as second parameter and 1 for the JSON object.
wp_send_json_success($result, 200, 1);

Not able to display the JSON success output in the view or alert

I am using CodeIgniter, I have a three input field called as name, emp_id,crm_id. I am entering the id value and sending to the controller to get all the information related to that id using AJAX an JSON. Now the issue is, I am getting the correct output in the network tab but not able to display in the view page even alert is also not displaying in the JSON.
Sometimes I am getting below error because of JSON is empty
[Show/hide message details.] SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I think there is some issue with JSON.
Ajax
$("form[name='search_addSalaryrecord']").validate({
// errorElement: 'div',
submitHandler: function(form) {
//alert(baseUrl);
var employee_name = $('#employee_name').val();
var crm_id = $('#crm_id').val();
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_name: employee_name,crm_id:crm_id,employee_id:employee_id},
success: function(response) {
//$('.search_record tbody').html(response);
// var data = JSON.parse(response);
//alert(data.status);
if (response.status === 'error')
{
alert(response.msg);
}
if (response.status === 'success') {
//alert('data avaliable');
alert(response.records);
console.log(response.records);
}
}
//error: function(error) { console.log(error); }
});
}
});
Controller
public function search_addSalaryrecord()
{
$employee_name=trim($this->input->post('employee_name'));
$emp_crmid=trim($this->input->post('crm_id'));
$employee_id=trim($this->input->post('employee_id'));
if((!empty($employee_name)) ||(!empty($emp_crmid)) || (!empty($employee_id))){
$arr_result =$this->Employee_model->get_salary_search_emp_id($employee_name,$emp_crmid,$employee_id);
if (!empty($arr_result)){
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
"employee_id" => $row->employee_id,
"month_year" => $row->month.' '.$row->year
);
}
//print_r($result);
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($arr_result);
exit;
}
Hope this will help you :
Use dataType: "json" in your ajax to avoid further parsing of response and return json_encode data with exit from your controller
Your ajax should be like this :
$("form[name='search_record']").validate({
submitHandler: function(form)
{
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_id:employee_id},
success: function(response) {
//alert(data.status);
if (response.status == 'error')
{
alert(response.msg);
$('.personel_info').empty();
}
if (response.status == 'success')
{
alert(response.records);
$('.personel_info').empty();
$('.personel_info').show();
var trHTML = '';
$.each(data.records, function (i, o){
$('#name_emp').text(o.name);
$('#mobileno_emp').text(o.mobileno);
$('#employee_email').text(o.employee_email);
});
}
}
});
}
});
Your controller's method search_addSalaryrecord should be like this :
public function search_addSalaryrecord()
{
$employee_id = trim($this->input->post('employee_id'));
if(!empty($employee_id))
{
$arr_result = $this->Employee_model->get_salary_search_emp_id($employee_id);
if (! empty($arr_result))
{
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
);
}
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($respnonse);
exit;
}

Posting data using Ajax

I've been trying to post data using AJAX that will update a field in my database however I am having trouble doing so. Everything seems like it should run fine and I get no errors in the console but I've no idea why my db won't update.
Can someone help me out here please?
AJAX:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
console.log("success");
}
});
}
Confirm.php:
$name=$_POST['var1'];
$age=$_POST['var2'];
if($name == "Stuart") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
else if($name == "Peter") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
The connection to my database is working as I have $connection setup and went to the page /ajax/confirm.php in my browser and I see "Connection successful" in my console as I defined if successful.
So I am unsure as to why this isn't updating?
Are my values not being posted correctly?
I'm new to AJAX so forgive me if this is something very simple!
Thanks
Try the following:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: arr,
success: function(data) {
console.log("success");
}
});
}
Instead of converting the object into json string send it as is.
Edit: Also remove dataType and probably contentType too. Your code is at risk of SQL Injection. Look into prepared statements and escaping mysql data.
Maybe this well help.
<script type="text/javascript">
function ajaxUpdate() {
var data = $('#formID').serialize();
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: data,
dataType: 'json',
encode : true,
success: function(data) {
if(data == "ok"){
console.log("success");
}else{
console.log(data);
}
}
});
}
</script>
confirm.php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
switch ($name) {
case 'Stuart':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
case 'Peter':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
default:
echo json_encode('Unknown name ');
}

Categories