Ajax PHP Call not working - php

I tried to run the code below but it doesn't work, and I tried everything I remember and couldn't get to work.
AJAX Call
var status = $(this).prop("checked");
var room_id = id;
$.post('maintenanceControl.php', {action: status, id: room_id});
PHP Script
<?php
if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
$action = $_POST['action'];
$id = $_POST['id'];
if ($action) {
return manageMaintenance($id, true);
} else {
return manageMaintenance($id, false);
}
}
function manageMaintenance($room_id, $status)
{
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString, true);
foreach ($data['rooms'] as $key => $entry) {
if ($key == $room_id) {
$data[$key]['maintenance'] = $status;
}
}
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
return true;
}
At first I thought it was a malfunction but the example below worked just fine
$.post( "test.php", function( data ) {
alert(data);
});
PHP
<?php
echo "test";

In order to get data back into the Javascript ajax call, you need the php script to echo something.
Return values in php do not find their way back into the Ajax call.
Often, php scripts echo a value, either a single value or if you want the get more complex data from php back into the Ajax call, you can json encode several values and echo that.

You have to echo/print something in php script to send response to ajax request. You have to do something like below.
$response=false;
if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
$action = $_POST['action'];
$id = $_POST['id'];
if ($action) {
$response=manageMaintenance($id, true);
} else {
$response=manageMaintenance($id, false);
}
}
function manageMaintenance($room_id, $status)
{
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString, true);
foreach ($data['rooms'] as $key => $entry) {
if ($key == $room_id) {
$data[$key]['maintenance'] = $status;
}
}
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
return true;
}
echo $response==true? "OK" : "FAILED";

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.

How to set limitations for checkbox using ajax and session?

I have never done combining ajax and session before. So far i have done something like this.
var sessionvar;
$.ajaxSetup({cache: false})
$.get('test.php' ,function (data) {
sessionvar = data;
alert(sessionvar);
var checkedCbs = $('sessionvar:checked');
if (checkedCbs.length === 4) {
alert("You can only select 3 books");
this.checked = false;
}
});
I want to try set the limitations based on session. Inside the test.php i have something like this
<?php
session_start();
if(isset($_POST['sBorrow']) && $_POST['action']){
if(isset($_SESSION['sBorrow']) && is_array($_SESSION['sBorrow'])){
$sborrow = $_POST['sBorrow'];
$set = $_SESSION['sBorrow'];
}
else{
$set = array();
}
if($_POST['action'] == "SET"){
array_push($set, $_POST['sBorrow']);
$_SESSION['sBorrow'] = $set;
}
else if($_POST['action'] == "UNSET"){
$unset = $_SESSION['sBorrow'];
if(($key = array_search($_POST['sBorrow'], $unset)) !== false) {
unset($unset[$key]);
$_SESSION['sBorrow'] = $unset;
}
}
}
//session_destroy();
if(isset($_SESSION['sBorrow'])){
$countses = count($_SESSION['sBorrow']);
echo $countses;
}
// nothing requested, so return all values
print json_encode($_SESSION);
?>
Inside these i have create some array to store something. Never mind that, i just want to know how to run an ajax with session. Im not sure if my codes is right for implementing that.

GET JSON provides two values, I want to add these two togther using php, and then return to callback

$_GET['numberofwelds']; & $_GET['numberofconwelds']; are sent to this script using GET JSON. I want to add these together, and then use json_encode to send a total back to the callback (in another php script) . If both $_GET 's are empty, then I want nothing to happen. How should I change this?
$numberofwelds = $_GET['numberofwelds'];
$numberofconwelds = $_GET['numberofconwelds'];
if (isset($_GET['numberofwelds']) && $_GET['numberofwelds'] != '' {
$numberofwelds + $numberofconwelds = $sum_total;
echo json_encode($sumtotal);
} else {
exit()
}
Firstly, you are trying to access your $_GET variables without checking they exist first.
Secondly, you should be throwing Exceptions instead of just calling exit() or die(). You can then log them with $e->getMessage() or write them to the local filesystem.
Finally, you need to validate your data. Make sure it is what you expect it to be.
if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
{
// Now we know both values definitely exist, VALIDATE them
$numwelds = $_GET['numberofwelds'];
$numconwelds = $_GET['numberofconwelds'];
if (is_int($numwelds) && is_int($numconwelds))
{
// Calculate your total
$total = $numwelds + $numconwelds;
echo json_encode($total);
}
else
{
// We get here because your GET variables do exist but they aren't
// numbers as you expect (you or someone else has sent rubbish data)
// You want to do nothing, although I would return an error in your json
// to be displayed to the user or logged by the consumer of the service
}
}
else
{
// We get here because your GET variables simply don't exist. They haven't been
// passed in as you are expecting them to be
// You want to do nothing, although I would return an error in your json
// to be displayed to the user or logged by the consumer of the service
}
Always code defensively.
I'm going to show you what I would do in this situation.
if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
{
$numwelds = $_GET['numberofwelds'];
$numconwelds = $_GET['numberofconwelds'];
if (is_int($numwelds) && is_int($numconwelds))
{
$total = $numwelds + $numconwelds;
$response = array("status" => "success", "message" => $total);
echo $response;
}
else
{
$response = array("status" => "failure", "message" => "GET params were not numbers");
echo $response;
}
}
else
{
$response = array("status" => "failure", "message" => "GET params do not exist");
echo $response;
}
Then, in your consuming service (most likely a JavaScript / jQuery AJAX call), you can do the following:
.done(function(data) {
var json = $.parseJSON(data);
if (data.status === "success") {
// Yay, we got a success back
console.log("The total is: " + data.message);
} else if (data.status === "failure") {
// Uh oh, something's gone wrong server-side
console.log(data.message);
}
});
change this
if ($_GET['numberofwelds'] != '' && $_GET['numberofconwelds'] != '') {
$numberofwelds + $numberofconwelds = $sum_total;
echo json_encode($sumtotal);
} else {
exit()
}
to this
if ($numberofwelds && $numberofconwelds ) {
$sum_total = array(
'sumTotal' => $numberofwelds + $numberofconwelds,
);
echo json_encode($sum_total);
}else {
exit();
}
Please always check existence of the array keys with isset() construction or array_key_exists() function.
if (isset($_GET['numberofwelds']) && $_GET['numberofwelds'] != '' && isset($_GET['numberofconwelds']) && $_GET['numberofconwelds'] != '') {
echo json_encode(array("total" => $_GET['numberofwelds'] + $_GET['numberofconwelds']));
} else {
exit();
}
UPDATE
With is_numeric() function this code should be more robust:
if (isset($_GET['numberofwelds']) && is_numeric($_GET['numberofwelds']) && isset($_GET['numberofconwelds']) && is_numeric($_GET['numberofconwelds'])) {
echo json_encode(array("total" => $_GET['numberofwelds'] + $_GET['numberofconwelds']));
} else {
exit();
}
PHP reference: array_key_exists()
PHP reference: isset()
$numberofwelds = json_decode($_GET['numberofwelds'], true);
$numberofconwelds = json_decode($_GET['numberofconwelds'], true);
$mergedJson = array_merge(numberofwelds, numberofconwelds);
echo json_encode($mergedJson);
This should do it. It grabs the json, decodes and turns it in to an array (second parameter of json_decode set to true) and then combines them.

Return True or False & how to get just on true in a loop

I have this script that sends via $.post some information
$("#clickme").click(function(e){
var selected = $(".img input:checked").map(function(i,el){return el.name;}).get();
var prelucrare = selected.join(";")
$.post('test.php', {
rezultat: prelucrare,
},
function(data){
$('#rez').html(data)
});
});`
And the PHP file that handles the $.post
<?php
require_once '../config.php';
If(isSet($_POST['rezultat'])) {
$d = explode(';', $_POST['rezultat']);
foreach($d as $numar_inregistrare){
$SQL = "DELETE FROM galerie_foto WHERE numar_inregistrare = '$numar_inregistrare'";
$rezultat = mysql_query($SQL) or die(mysql_error());
return true;
}
} else {
exit;
}
?>
I have two questions:
1. How can I make the js script do a thing if the return value is true and an other thing if the return value is false ? Something like this ?
$.post('test.php', {
rezultat: prelucrare,
success: function(msg){
valid = (msg == 1) ? true : false;
if(!valid) {
$("#valid_input").html("Please enter valid info");
} else {
$("#valid_input").html("");
}
}
)};
My other question is about the returning result, because I'm in a loop if there are 3 things in the array the result will be truetruetrue instead of just one true, what can I make to get just one true ?
You can use "return" only in functions and methods. To print "true" or "false" once, in the foreach loop you can break out or in your case just exit with 'false' if there's an error. You'll have something like this:
foreach($d as $numar_inregistrare){
$SQL = "DELETE FROM galerie_foto WHERE numar_inregistrare = '$numar_inregistrare'";
$rezultat = mysql_query($SQL);
if (!$rezultat) {
exit('false');
}
}
echo 'true';
....

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
}
});
}

Categories