Post to PHP with Ajax and read Results - php

I have read through dozens of similar questions on this website, and am having a lot of trouble trying to understand what is wrong with my code. I am trying to dynamically update select boxes based on the value of another one, but for some reason cannot seem to get any type of response data back once I post to PHP with Ajax.
JAVASCRIPT:
function toggleHiddenDIV()
{
var dc = document.getElementById("datacenter");
var dcVal = dc.options[dc.selectedIndex].value;
// Check if Datacenter selection has no Value selected
if(dcVal != '')
{
document.getElementById("hidden-options").style.display="block";
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action_type': 'update_inventory_fields', id: dcVal },
success: function(response)
{
alert(response);
}
});
}
else
{
document.getElementById("hidden-options").style.display="none";
}
};
</script>
PHP:
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
return json_encode($data);
}

Don't call return (since you're not returning a function); just echo then content onto the page:
echo json_encode($data);

Change to this...no need to return, just echo, since youre outside of a function call
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
echo json_encode($data);
}

If the php code you posted is inside a function than you need to use echo functionname();
If the php code is not in a function, then just use echo json_encode($data);

Related

PHP/MySQL/AJAX - Refresh query values with AJAX

I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.

How to use angularjs $resource with php script

i have question related to PHP - AngularJs, so i have simple PHP script
<?php
require_once '../../dbConnect.php';
$driverId = $_POST['driverId'];
if (isset($_POST['driverId'])) {
$sql = "delete from drivers where driver_id='$driverId'";
if ($mysqli->query($sql) === TRUE) {
echo mysqli_insert_id($mysqli);
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
At the moment i pass data to script like this
return $http({
method: 'POST',
url: '/api/drivers/deleteDriver.php',
data: $.param(driverObject),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
And i don't like that code, on other Java project i send params to end points with angularjs $resource service like this
var deleteDriverResouce = $resource('/api/drivers/deleteDriver.php');
function deleteDriver() {
deleteDriverResouce.save(driverObject);
}
And as you can see that is cleaner code and easier to use, i'm wondering can i use $resource service to pass object to php script ?
So i have found solution and i will share it here so maybe someone will need it. In order to use AngularJs $resource service you just need to make small change in PHP script, just add $object = json_decode(file_get_contents("php://input"), true); on that way you can access to object that you sent via $resource. And here is example of one working PHP script.
<?php
require_once '../dbConnect.php';
session_start();
$object = json_decode(file_get_contents("php://input"), true);
if (isset($object['email']) && isset($object['password'])) {
$email = $object['email'];
$password = $object['password'];
$query="select * from members where email='$email'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$row = mysqli_fetch_assoc($result);
if($row) {
if (password_verify($object['password'], $row['password'])) {
$_SESSION["id"] = $row['id'];
echo 'Login Success!';
} else {
session_destroy();
var_dump(http_response_code(400));
}
} else {
session_destroy();
var_dump(http_response_code(406));
}
$mysqli->close();
} else {
session_destroy();
var_dump(http_response_code(400));
}
?>
And on UI i have this simple and minimal code:
var userLoginObject = {
email: 'login#email.com',
password: 'password123'
};
var authenticationResource = $resource('/api/authentication/authenticate.php');
function logIn() {
authenticationResource.save(userLoginObject );
}
That's much better and cleaner than using ugly
return $http({
method: 'POST',
url: '/api/drivers/authenticate.php',
data: $.param(userLoginObject),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

ajax call must get response from method in ajax.php?

This is my ajax call.
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
I have many methods in ajax.php. Each and every method throws some response.
<?php
function respose()
{
$query = "select * from quote where template IS NOT NULL";
$result = mysql_query($query, $con);
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['template'].'">' . $row['template'] . '</option>';
}
$query1 = "select * from template";
$data = mysql_query($query1,$con);
while ($row = mysql_fetch_assoc($data)) {
echo json_encode($row);
}
}
function result()
{
}
?>
But i want to get response from one method [ie. from response()].
How can this be done?
You could include a selector in the ajax request data. Like this for example:
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
data: "function=result",
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
Then in your PHP code, a simple if-statement will check which one to output.
if(isset($_GET['function'])) {
if($_GET['result'] == 'result') {
// do result stuff
} elseif($_GET['function'] == 'response') {
// do response stuff
}
}

How to cast a php array into javascript array

I run a mysql query and get the results successfully. However, I cannot read the elements of the array from javascript side. Can anyone help??
//JAVASCRIPT makes a request
function profiles(){
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "text");
}
function fillProfileCombo(res) {
alert(res);
}
//dbConn.php takes the request , gets the result and passes via echo as it is shown as follows:
//RETURN PROFILE LIST
else if (!strcmp($opType, "getProfileList")){ //no param is coming
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
mysql_select_db( $db_name ) or die( mysql_error() );
$profiles = mysql_query(" SELECT DISTINCT profileName FROM `map_locations` ");
$row = mysql_fetch_array($profiles);
/*while() {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
*/
//$data = array();
//$row = mysql_fetch_assoc($profiles)
/*while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}*/
if ($row){
echo $row;
} else {
echo "ERROR occured";
}
}
//PROBLEM:
//when I change echo $row; into echo $row[0]; , I see the first element in an alert box...query is definitely working..
//however when I change res to res[0], it does not show anything - which is normal because I do not know how to cast php array into js array..
function fillProfileCombo(res) {
alert(res[0]); // does not work..
}
I do not want to use json by the way... I am not very good at. I do not want to mess it up. Any suggestion and help is appreciated.
// PHP
$res = array();
while ($row = mysql_fetch_array($profiles)) {
$res[] = $row['profileName'];
}
header('Content-type: application/json');
echo json_encode($res);
// JavaScript
$.post('dbConn.php', { opType:"getProfileList" }, function(data) {
alert(data.length + " profiles returned");
}, "json");
Thanks Phil..This works now.. I followed your way by changing sth.. Maybe it was working but I couldnt run it. Very similar except a couple of changes. I changed it as like this:
//PHP
$data = array();
while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}
if ($data){
echo json_encode($data);
} else {
echo $data;
}
//JS
function profiles(){
//$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
}
function fillProfileCombo(data) {
alert(data[1].profileName);
}

Categories