How to put object into string and print - php

I have a script that takes variables from an html form and sends them to a php script. I query new data based on these numbers and format them into a string to be sent back to the script. The problem is that my php variables aren't printing and I think it is because they are objects. Here is my code:
//GET VENDOR PO NUMBER AND APPEND ONCHANGE OF # OF EXISTING POS
$('#numvendpo').mouseover(function(){
var countpre = $(this).val();
var p = $('#pro').val();
var c = $('#custponumhold').val();
var v = $('#vendorid').val();
var cp = (parseInt(countpre)+1);
var data_String;
data_String = 'p='+p+'&c='+c+'&v='+v+'&cp='+cp;
$.post('ft-final-v-po-num.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
});
});
I then post the values to this php script:
<?php
require "../inc/dbinfo.inc";
$p = $_POST['p'];
$c =$_POST['c'];
$v = $_POST['v'];
$cp = $_POST['cp'];
if ($c == 'null') { //cant use (!$customerpo) because $customerpo is passing the string of 'null' instead of the actual null value
$c = NULL; //so we change that to the actual null value
}
$getprojectnum = "SELECT ProjectNumber FROM tblProjects WHERE PROJECTNOID = '$p'"; //check
$getcustomerpo = "SELECT SequentialPONum FROM tblCustomerPOs WHERE CustomerPOID = '$c'"; //check
$getvendornum = "SELECT VendorNumber FROM tblVendors WHERE VENDORID = '$v'"; //check
$acpnhold = $conn->query($getprojectnum);
$accphold = $conn->query($getcustomerpo);
$acvnhold = $conn->query($getvendornum);
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
if($c){
$string = $acpn.'-'.$accp.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}elseif(!$c){
$string = $acpn.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}else{
echo json_encode('Error');
exit();
}
?>
The response on my webpage is ---2 instead of (ex: 18000-1-2-2). As mentioned earlier I think it is because they are objects but I am not quite sure. Any advice is appreciated.

Your problem is with this bit:
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
From the php docs:
object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, array $params ]] )
Your $acpn $accp and $acvn are not result objects. They are not even defined before you use them in those calls.
This should get the single column from each query result:
$acpn = $acpnhold->fetch_row()[0];
$accp = $accphold->fetch_row()[0];
$acvn = $acvnhold->fetch_row()[0];
Bear in mind you still have a major SQL Injection vulnerability with the original query calls.

Try like this code below:
$.ajax({
type: 'POST',
url: 'ft-final-v-po-num.php',
data: {
'p': p,
'c': c,
'v': v,
'cp': cp
},
success: function(msg){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
}
});

Related

Break array retrieved from php using jquery

Im retrieving an array from php file called check_num.php :-
check_num.php
<?php
include 'config.php';
session_start();
$VALUE = $_SESSION["some_session_variable"];
if(isset($_POST['default'])){
$ert = "SELECT * FROM table_name WHERE something = '$VALUE' ORDER BY p_id ASC ";
$qty = mysql_query($ert);
$fgh = mysql_num_rows($qty);
$ertz = "SELECT something, COUNT(something) FROM table_name WHERE something = '$VALUE'
AND something >= 1 GROUP BY p_id ORDER BY p_id ASC";
$qtyz = mysql_query($ertz);
$tyui = mysql_num_rows($qtyz);
$data = array(
"post" => $fgh,
"likes" => $tyui
);
echo json_encode($data);
} else {
echo "0";
}
?>
Now comes the jquery part :-
<script>
$(document).ready(function(){
setInterval(function(){
var def = "one";
$.post("check_num.php", {'default': def }, function(response){
if(response != 0){
document.getElementById("total_array_count").innerHTML = response;
//document.getElementById("total_like_count").innerHTML = response.likes;
//document.getElementById("total_post_count").innerHTML = response.post;
------------------OR THIS Method-----------------
var my_array = response;
//var post_number = my_array["post"];
document.getElementById("total_array_count").innerHTML = my_array;
//document.getElementById("total_post_count").innerHTML = '<b>'+post_number+'</b>';
}
else {
document.getElementById("total_array_count").innerHTML='Error occured !';
}
});
},2500);
});
</script>
Now received output is {"post":10,"likes":1} , its an array . But when i access array values response.post or my_array["post"] the value returned is undefined.
I had gone through this :- http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_object
And kind of this too:- jQuery .val() returns undefined for radio button
Followed it but no success !
Please correct my mistakes .
Run JSON.parse() on your result before trying to access the values. The result comes as a raw string and you have to convert it to an object first.
result = JSON.parse(result);
Alternatively, since you're already using jQuery, you can use jQuery's alias for the function.
result = $.parseJSON(result);
They are essentially the same thing.

returned ajax query data undefined

Hello I am attempting to create an ajax query but when my results are returned I get Undefined as a response. Except for the object called "hello" which returns back as "h" even though it is set to "hello". I have a feeling it has something to do with the way ajax is sending the data but i'm lost as to what may be the issue. Any help would be greatly appreciated.
here is the ajax
function doSearch() {
var emailSearchText = $('#email').val();
var keyCardSearchText = $('#keyCard').val();
var userNameSearchText = $('#userName').val();
var pinSearchText = $('#pin').val();
var passwordSearchText = $('#password').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: {
"hello": "hello",
"emailtext": "emailSearchText",
"keycardtext": "keyCardSearchText",
"usernametext": "userNameSearchText",
"pinText": "pinSearchText",
"passwordtext": "passwordSearchText"
},
dataType: "json",
success: function (data) {
alert(data.msg);
var mydata = data.data_db;
alert(mydata[0]);
}
});
}
Then here is the php
include_once('connection.php');
if(isset($_POST['hello'])) {
$hello = $_POST['hello'];
$emailSearchText = mysql_real_escape_string($_POST['emailSearchText']);
$keyCardSearchText = mysql_real_escape_string($_POST['keyCardSearchText']);
$userNameSearchText = mysql_real_escape_string($_POST['userNameSearchText']);
$pinSearchText = mysql_real_escape_string($_POST['pinSearchText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordSearchText']);
$query = "SELECT * FROM Students WHERE (`User name`='$userNameSearchText' OR `Email`='$emailSearchText' OR `Key Card`='$keyCardSearchText')AND(`Password`='$passwordSearchText'OR `Pin`='$pinSearchText')";
$students = mysql_query($query);
$count = (int) mysql_num_rows($students);
$data = array();
while($student = mysql_fetch_assoc($students)) {
$data[0] = $student['First Name'];
$data[1] = $student['Last Name'];
$data[2] = $student['Date of last class'];
$data[3] = $student['Time of last class'];
$data[4] = $student['Teacher of last class'];
$data[5] = $student['Membership Type'];
$data[6] = $student['Membership Expiration Date'];
$data[7] = $student['Free Vouchers'];
$data[8] = $student['Classes Attended'];
$data[9] = $student['Classes From Pack Remaining'];
$data[10] = $student['5 Class Packs Purchased'];
$data[11] = $student['10 Class Packs Purchased'];
$data[12] = $student['Basic Memberships Purchased'];
$data[13] = $student['Unlimited Memberships Purchased'];
$data[14] = $student['Groupon Purchased'];
};
echo json_encode(array("data_db"=>$data, "msg" => "Ajax connected. The students table consist ".$count." rows data", "success" => true));
};
Your PHP script is likely producing error messages because the $_POST values you are trying to access don't match the key names you are sending in the request. For example: $_POST['emailSearchText'], yet you used emailtext in the AJAX call.
This is most likely causing jQuery to not be able to parse the response as JSON, hence the Undefined.
First of all, you have to remove the quotes or you will be passing those literals instead of the variables.
$.ajax({
...
data: {
hello: "hello",
emailtext: emailSearchText,
keycardtext: keyCardSearchText,
usernametext: userNameSearchText,
pinText: pinSearchText,
passwordtext: passwordSearchText
},
...
});
And then, like ashicus point out, in your PHP file:
$emailSearchText = mysql_real_escape_string($_POST['emailtext']);
$keyCardSearchText = mysql_real_escape_string($_POST['keycardtext']);
$userNameSearchText = mysql_real_escape_string($_POST['usernametext']);
$pinSearchText = mysql_real_escape_string($_POST['pinText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordtext']);
JS file looks ok, so this few clues to check PHP file.
See if there are even POST params there (printr all $_POST in php)
Check if your even enters IF. Add an else statement and echo some dummy json.
Check what is actually in encoded json that is echoed. Assign it to var then print.

Pass an array from PHP (from DB) to JS?

My goal is to get - finally - a 'normal' JS array in my js-file. Maybe json is the way to do it - but the elements in the array should remain in order and its just an array of three arrays: [["1","2","3"]["1","2","3"]["1","2","3"]].
my php-query (it does produce the array above - I mean: it does work):
// this is file 'dbquery.php'
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo $cd_answer;
?>
I assume json is not the adequat form here.
Now all I want is an js-array in my js-file like : my_array = [[1,2,3],[1,2,3],[1,2,3]]
But I terribly fail to achieve this.
With $.ajax() I don't know how to get ALL the data at once without 'data: ' each single value. I just want to "catch" my echo from the php - how to do so?
do like this
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo json_encode ($cd_answer); // encode in json format
?>
and in ajax:
$.ajax({
type: "GET",
url: "test.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON( data ); // parse the answer
// if you want in an array format then just use eval()
x = eval(x);
alert(x);
}
});
If you just need a PHP variable passed to JS when the page is rendered, then do this in your PHP view layer:
<script type="text/javascript">
var myInt = <?php echo $int ?>;
var myString = '<?php echo $string ?>';
var myArray = <?php echo json_encode($array) ?>;
// All these JS variables can now be used here
</script>
Obviously, you need to ensure that the variables are valid - so in the case of the int, if it is null or undefined, you need to ensure you don't render the assignment - otherwise it will produce a client-side error.

User provided array name in javascript

So i am fetching rows from my database using AJAX and then turning them into an array with a variable identifier Here is the code
PHP:
$query_val = $_GET["val"];
$result = mysql_query("SELECT * FROM eventos_main WHERE nome_evento LIKE '%$query_val%' OR local_evento LIKE '%$query_val%' OR descricao_evento LIKE '%$query_val%'");
for($i=0;$i<mysql_num_rows($result);$i++){
$array = array();
$array[$query_val] = mysql_fetch_row($result); //fetch result
echo json_encode($array);
}
Here is the javascript:
$('#s_query').keyup(function(){
var nome = document.getElementById('s_query').value;
$.ajax({
url: 'search.php',
data: '&val='+nome,
dataType: 'json',
success: function(data)
{
console.log(nome);
var image_loc = data.nome[7];
console.log(image_loc);
If i change the line var image_loc = data.nome[7]; to var image_loc = data.nidst[7]; it works perfectly. Nidst is the term i search for.
This code returns the error:
"Uncaught TypeError: Cannot read property '7' of undefined".
What should i do?
data.nome[7]; is trying to access a property of data named nome, which doesn't exist. Since you declared a variable nome which holds your desired property name, you need to reference the value as the property name, like data[nome][7].
Example: If var nome = 'foo', then data[nome][7] will evaluate to data['foo'][7] which is the same as data.foo[7].
What you are doing is data.nome[7] which is the same as data['nome'][7], and the only way that would work is if var nome = 'nome'.
use:
var image_loc = data[nome][7];
Another problem is that server does not resond with valid json data. Try to modify the code:
$array = array();
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$array[$query_val] = mysql_fetch_row($result);
}
die(json_encode($array));

Accessing json array by string? (Converting string to var. name)

I'm trying to post the "lang_id" var. to "get_lang.php" with jquery to get (json) data.
But I can't access the data.
Now trying to do
var r = $(this).attr('rel');
var v = data.r;
But this doesn't work because of "r" is string IMO.
Also tried
data.window[r] // but...
"get_lang.php";
$lang_id = (int) ($_POST['lang_id']);
if($lang_id == 1)
{
$lang['simple'] = 'aaa';
$lang['array'] = 'bbb';
}
if($lang_id == 2)
{
$lang['simple'] = 'ccc';
$lang['array'] = 'ddd';
}
print json_encode($lang);
my.js;
$.post("get_lang.php", { "lang_id": 2}, function(data){
$('.lang').each(function() {
var r = $(this).attr('rel');
var v = data.r;
$(this).text(v);
});
},"json");
thanks for help.
Try
var v = data[r];
The dot notation interprets r as a string and not as a variable.
I think maybe you need to tell jQuery the right content type. Put this at the TOP of your get_lang.php file
header("Content-Type: application/json");
And see if jQuery likes it.

Categories