returned ajax query data undefined - php

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.

Related

How to put object into string and print

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

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

Passing json to php and updating mysql

I'm trying to pass image coordinates via json to a php file that should update the database.
I have this in jquery:
var coords=[];
var coord = $(this).position();
var item = { coordTop: coord.top, coordLeft: coord.left };
coords.push(item);
var order = { coords: coords };
$.ajax({
type: "POST",
data : +$.toJSON(order),
url: "updatecoords.php",
success: function(response){
$("#respond").html('<div class="success">X and Y Coordinates
Saved</div>').hide().fadeIn(1000);
setTimeout(function(){
$('#respond').fadeOut(1000);
}, 2000);
}
});
This is what updatecoords.php looks like:
<?php
$db = Loader::db();
$data = json_decode($_POST['data']);
foreach($data->coords as $item) {
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
$x_coord = mysql_real_escape_string($coord_X);
$y_coord = mysql_real_escape_string($coord_Y);
$db->Execute("UPDATE coords SET x_pos = '$x_coord', y_pos = '$y_coord'");
}
?>
The success message shows from the javascript however nothing gets updated in the database?
Any thoughts?
You have a + before $.toJSON. Meaning that the json string it returns will be converted to an integer - probably 0 or NaN.
Alex is right, but you can also take the quotes out from the preg_replace pattern. PHP naturally uses /.../ slashes to "quote" a regular expression.
try this
UPDATE coords SET x_pos = '".$x_coord."', y_pos = '".$y_coord."'
and look here how to use toJSON
EDIT :
try this
$.ajax({
type: "POST",
data : { coordTop: coord.top, coordLeft: coord.left ,coords: coords },
and in second code do this
$data = json_decode($_POST['data']);
$coordTop = mysql_real_escape_string($_POST['coordTop']);
$coordLeft = mysql_real_escape_string($_POST['coordLeft']);
$coords = mysql_real_escape_string($_POST['coords']);
foreach(.........
.....
.....
and then use those variables $coordTop , $coordLeft , $coords
Thanks for the help but this seemed to do the trick....
In javascript:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){ alert (response + mydata);
In Updatecoords.php:
$data = json_decode(stripcslashes($_POST['data']));

jquery autcomplete returning source array

I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )

Categories