Returning multiple ajax response on dropdown change - javascript

Im trying to have my ajax respond multiple values based on the dropdown I selected.
Here's my JS updated
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$('#student_infor').change(function()
{
var first = $('#student_infor').val();
var req = $.get('frm_get_stud_record.php', {dd: first,action: 'ajax'});
req.done(function(row)
{
var whatever = JSON.parse(row);
$('#studen_title').val(whatever.stu_title);
$('#student_first_name').val(whatever.stu_first_name);
});
});
</script>
And here's my ajax php
<?php
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if(isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd']))
{
$dbValue = intval( $_GET['dd'] );
$ajax = true;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college_school_system";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT distinct a.stu_unique_id,
a.stu_title,
a.stu_first_name,
a.stu_middle_name,
a.stu_last_name,
a.stu_gender,
a.stu_email_id,
a.stu_mobile_no,
a.stu_dob,
b.stu_course_id,
b.stu_batch_id,
b.stu_section_id,
c.course_name,
d.batch_name,
e.section_name
from stu_info a INNER JOIN stu_academics b
ON
a.stu_unique_id = b.stu_acad_stu_info_id
inner join courses c
ON
b.stu_course_id = c.course_id
INNER JOIN batches d
ON
b.stu_batch_id = d.batch_id
INNER JOIN section e
ON
b.stu_section_id = e.section_id
where a.stu_unique_id = $dbValue
ORDER BY d.batch_name DESC";//die($sql);
$res = mysqli_query($conn,$sql);
$title = '';
$f_name = '';
while ($row = mysqli_fetch_array($res)){
$f_name = $row['stu_first_name'];
$m_name = $row['stu_middle_name'];
$l_name = $row['stu_last_name'];
$title = $row['stu_title'];
$gender = $row['stu_gender'];
$email = $row['stu_email_id'];
$mobile = $row['stu_mobile_no'];
$birth = $row['stu_dob'];
//$title = "$title";
if($ajax) echo $title;
if($ajax) echo $f_name;
}
//die($dataTable);
?>
What I'm trying to achieve here is to have the Ajax return multiple values so i can insert those returned values in their respective input type text boxes.

Related

API receiving Half Data

I have a PHP API but when I send data to it using a post or get request the API receives half data, I don't know what the issue is. this same API works on the localhost but gives error on the Public server.
API sendrequset URL:
https://peer.infusiblecoder.com/android/loanapp/sendrequesttoperson.php?request_is_seen=hjhj&loan_request_code=100&req_status=hjh&request_sender_user_name=ghjgjh&request_reciver_user_name=hjhjh&request_sender_user_id=jkjkj&request_reciver_user_id=hjhj&request_time_stamp=ghhgjhh
And this is my Api sendrequesttoperson.php
<?php
require 'db.php';
if(isset( $_GET["$req_status_db"]) && isset($_GET["$loan_request_code_db"]) && isset($_GET["$request_sender_user_name_db"]) && isset($_GET["$request_reciver_user_name_db"]) && isset($_GET["$request_sender_user_id_db"]) && isset($_GET["$request_reciver_user_id_db"]) && isset($_GET["$request_is_seen_db"]) && isset($_GET["$request_time_stamp_db"])){
$loan_request_code = $_GET["$loan_request_code_db"];
$request_sender_user_name = $_GET["$request_sender_user_name_db"];
$request_reciver_user_name = $_GET["$request_reciver_user_name_db"];
$request_sender_user_id = $_GET["$request_sender_user_id_db"];
$request_reciver_user_id = $_GET["$request_reciver_user_id_db"];
$request_time_stamp = $_GET["$request_time_stamp_db"];
$request_is_seen = $_GET["$request_is_seen_db"];
$req_status = $_GET["$req_status_db"];
$sql = "select * from $table_requests where $loan_request_code_db like '".$loan_request_code."';";
$result = mysqli_query($con, $sql);
$response = array();
if(mysqli_num_rows($result) > 0){
$code = "failed";
$message = "Request already exists";
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
} else {
$sql = "INSERT INTO $table_requests VALUES (NULL,'$loan_request_code','$request_sender_user_name','$request_reciver_user_name','$request_sender_user_id','$request_reciver_user_id','$request_time_stamp','$request_is_seen','$req_status')";
if (mysqli_query($con, $sql)) {
$code = "success";
$message = "Request sent";
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
echo "Request sent successfully";
} else {
$code = "failed";
$message = "Error: " . $sql . "<br>" . mysqli_error($con);
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
}
//$message = "Thank you for registration";
// array_push($response, array("code" => $code, "message" => $message));
// echo json_encode($response);
}
mysqli_close($con);
}else{
$loan_request_code = $_GET["$loan_request_code_db"];
$request_sender_user_name = $_GET["$request_sender_user_name_db"];
$request_reciver_user_name = $_GET["$request_reciver_user_name_db"];
$request_sender_user_id = $_GET["$request_sender_user_id_db"];
$request_reciver_user_id = $_GET["$request_reciver_user_id_db"];
$request_time_stamp = $_GET["$request_time_stamp_db"];
$request_is_seen = $_GET["$request_is_seen_db"];
$req_status = $_GET["$req_status_db"];
$myresponse = 'Enter missing fields_'.$request_sender_user_name."_".$loan_request_code."_".$request_reciver_user_name."_".$request_sender_user_id."_".$request_reciver_user_id."_".$request_time_stamp."_".$request_is_seen."_".$req_status."_";
echo json_encode($myresponse);
}
?>
And this is my db.php file required for the variable names and db connection
<?php
$host = "localhost";
$db_user = "ur5kq7835fnc4";
$db_password ="ch%2#3/^c<1b";
$db_name = "dbhrzz2e49skck";
//Folder Path
$mainpath = "http://192.168.0.101/android/loanapp/";
$profilepic_folder = "profilepics/";
$fileupload_folder="uploadedFiles/";
$fileuploadfullpath_folder="uploadedFiles/";
// loan request statuses {"pending", "rejected","accepted","awaiting money", "paid out", "completed"};
// Table RegisteredUser attributes:
$table_user = "registered_users";
$user_id_db = "user_id";
$firstname_db = "firstname";
$lastname_db = "lastname";
$address_db = "address";
$whatyoupretend_db = "whatyoupretend";
$fieldofactivity_db = "fieldofactivity";
$phone_db = "phone";
$email_db = "email";
$password_db = "password";
$status_db = "status";
$user_img_url_db = "user_img_url";
// Table LoanRequest attributes:
$table_loan_request = "loan_request";
$loan_id_db = "loan_id";
$loan_request_code_db = "loan_request_code";
$user_full_name_db = "user_full_name";
$user_img_url_request_db = "user_img_url_request";
$loan_amount_db = "loan_amount";
$loan_purpose_db = "loan_purpose";
$loan_collateral_db = "loan_collateral";
$loan_market_value_db = "loan_market_value";
$loan_type_db = "loan_type";
$loan_due_date_db = "loan_due_date";
$loan_doc_urls_db = "loan_doc_urls";
$loan_borrowing_rate_db ="loan_borrowing_rate";
$loan_loan_ratio_db ="loan_loan_ratio";
$loan_status_db = "loan_status";
$loan_paid_out_date_db ="loan_paid_out_date";
$loan_duration_db = "loan_duration";
//loan_duration
//loan_paid_out_date
// Table Requests
$table_loan_request = "loan_request";
$loan_id_db = "loan_id";
$loan_request_code_db = "loan_request_code";
$user_full_name_db = "user_full_name";
$user_img_url_request_db = "user_img_url_request";
$loan_amount_db = "loan_amount";
$loan_purpose_db = "loan_purpose";
$loan_collateral_db = "loan_collateral";
$loan_market_value_db = "loan_market_value";
$loan_type_db = "loan_type";
$loan_due_date_db = "loan_due_date";
$loan_doc_urls_db = "loan_doc_urls";
$loan_borrowing_rate_db ="loan_borrowing_rate";
$loan_loan_ratio_db ="loan_loan_ratio";
$loan_status_db = "loan_status";
$loan_lender_id_db = "loan_lender_id";
$loan_paid_out_date_db ="loan_paid_out_date";
$loan_duration_db = "loan_duration";
/*
Table User attributes:
tbname = registered_users
user_id
firstname
lastname
address
whatyoupretend
fieldofactivity
phone
email
password
status [true,false]
user_img_url
*/
/*
Table LoanRequest attributes:
tbname = loan_request
loan_id
loan_request_code
user_full_name
loan_amount
loan_purpose
loan_collateral
loan_market_value
loan_type
loan_due_date
loan_doc_vehicle_id_url
loan_doc_owner_id_url
loan_doc_insurance_url
loan_status
Vehicle ID,Owner´s ID,Insurance
*/
/*
Table Requests attributes:
tbname = requests
request_id
loan_request_code
request_sender_user_name
request_reciver_user_name
request_sender_user_id
request_reciver_user_id
request_time_stamp
request_is_seen
*/
$con = mysqli_connect($host, $db_user,$db_password,$db_name);
if (!$con){
die("connection failed". mysqli_connect_error());
}
/*
else{
echo "connected susscesful";
}
*/
?>
it gives this result
The problem is $_GET["$req_status_db"]
It should be $_GET["req_status_db"]
You will have to remove $ from all the $_GET keys.
Also, you do not have req_status_db as query param in the URL you have shared.

displaying data from mysql where if value is in database show true if its not show false

My overall goal is if there is a Value pull in ID then change the cell where ID matches the number
e.g. the below data has been pulled in change cell 1,120,17,40,61,69,70,81,82,9 green and the rest of them red.
if there is something i need to change mysql side then let me know i did try it so that it got entered into the database from node red to say if where number between 1-100 is present in mqtt feed add value present to column present if it isnt in the feed add value false but i couldnt get that to work.
Data
[{"id":"1","present":"present","date":"2018-07-17","time":"10:53:20"},
{"id":"120","present":"present","date":"2018-07-17","time":"10:54:24"},
{"id":"17","present":"present","date":"2018-07-17","time":"10:53:40"},
{"id":"40","present":"present","date":"2018-07-17","time":"10:53:27"},
{"id":"61","present":"present","date":"2018-07-17","time":"10:53:14"},
{"id":"69","present":"present","date":"2018-07-17","time":"11:02:01"},
{"id":"70","present":"present","date":"2018-07-17","time":"10:53:17"},
{"id":"81","present":"present","date":"2018-07-17","time":"10:56:50"},
{"id":"82","present":"present","date":"2018-07-17","time":"10:59:28"},
{"id":"9","present":"present","date":"2018-07-17","time":"10:53:15"}]
PHP
<?php
header('Content-type: application/json');
$servername = "localhost:3306";
$username = "user";
$password = "password!";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = 'SELECT
*
FROM test.test where time > NOW() - interval 30 minute group by id';
$result = $conn->query($sql);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$conn->close();
?>
HTML side
<script>
$(document).ready(function() {
for (var i = 0; i < 12; i++) {
var row = $('<tr>').appendTo("#zoning tbody");
for (var j = 1; j < 11; j++) {
$(`<td class='${i * 10 + j}'>${i * 10 + j}</td>`).appendTo(row);
}
}
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
if (item.id == "notNULL") {
return $('td.coloured').css('background-color','green').toggleClass('coloured');
} else {
return $('td.coloured').css('background-color','red').toggleClass('coloured');
} });
});
function updateTable() {
//console.log('function called');
$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$.get('php/test.php', function(response) {
response.forEach(function(item, index) {
console.log(item.beacon);
//$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
if (item.id == "notNULL") {
return $('td.coloured').css('background-color','green').toggleClass('coloured');
} else {
return $('td.coloured').css('background-color','red').toggleClass('coloured');
}
});
});
}
var updateTableInterval = setInterval(updateTable, 40000);
});
</script>
</head>
<body>
<table id='zoning'>
<tbody></tbody>
</table>
</body>
</html>
You shlould change the if (item.id = present) to if(item.id == present) in the first one you are setting the item.id to present and that is wrong you need to test . It is just a Syntax error

passing multiple values using xmlhttp.send

I am trying to pass two different values into an XMLHttpRequestObject.send but cannot seem to get the php script to read them both, it will only read the first value passed. How can I get the PHP to read both the values, here is the sample code:
HTML
<select id="mes" onchange="callCourseYards(this);">
<option>-</option>
</select>
Javascript
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function callCourseYards(selectObject){
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("POST", "php/CourseChoiceTeeOff.php");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var returnData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('tee');
messageDiv.innerHTML = returnData;
}
}
var data = selectObject.value;
var course = selectObject.value;
XMLHttpRequestObject.send("data=" + data + "course=" + course);
}
return false;
}
PHP
<?php
$pdo_dsn='localhost';
$dbname ='XXX';
$mysql_user='XXX';
$mysql_pass='XXX';
$db = mysqli_connect($pdo_dsn, $mysql_user, $mysql_pass, $dbname);
if(!$db){
print "Unable to connect to MySQL";
}
$myData = $_POST['data'];
$myData1 = $_POST['course'];
$sql_state = "SELECT * FROM ".$myData1." WHERE CourseCode = '".$myData."' ORDER BY CourseCode";
$result = mysqli_query($db, $sql_state);
$out = "";
$myrowcount = 0;
if(!$result){
$out = "Error";
}else{
$out = "<option>Selecciona un campo</option><br/ >";
$numresults = mysqli_num_rows($result);
for ($i = 0; $i < $numresults; $i++){
$row = mysqli_fetch_array($result);
$teeOff = $row['TeeOff'];
$out .= "<option id='".$myData."' value='".$teeOff."'> ".$teeOff."</option>";
}
$out .= "<br/ >";
}
print $out;
?>
I cannot seem to get the values through the XMLHttpRequestObject to go through into the PHP. I am not sure if its the syntax or how they should get past into the PHP.
I have tried using the & and the + symbols to concatenate both values, but I am not sure if this is possible. Does anyone know how I can fix this problem? I need both values to be able to do the mySQL search in the database.
Any help would be greatly appreciated. Thanks

ajax search bar multiple url value

In ajax url parameter i try to use multiple value to search. one value's data from user what they're enter. The other value will detect event.
but after i enter value there's no result.
here's my code(JS):
var currentURL = window.location.href;
currentURL = currentURL.split("=");
currentURL = currentURL[1];
console.log('php/Search.php?key=%QUERY' + currentURL);
$('#search.typeahead').typeahead({
name: 'typeahead',
remote: 'php/Search.php?key=%QUERY&map='+parseInt(currentURL[1]),
limit: 100
});
here's my code(PHP):
$key = $_GET['key'];
$map = $_POST['map'];
echo $map;
$array = array();
$array2 = array();
list($key2, $map) = split(',_+', $key);
$con = mysql_connect("localhost","test","test");
mysql_set_charset('utf8');
$db = mysql_select_db("test",$con);
$query = mysql_query("select `indicate_id`,`indicate_name` from `map_node` where `indicate_id` LIKE '%{$key}%' and map_sn =".$map." ;");
while ($row = mysql_fetch_assoc($query))
{
$array[] = $row['indicate_id'] ."\n\n". $row['indicate_name'];
}
echo json_encode($array);

Turning PHP into JSON array when parsed in Javascript

So, in order to create a page that has dynamic HTML, the following Javscript code was used:
function add0(Text, Value){
var x = document.getElementById("thingy");
var option = document.createElement("option");
option.text = Text;
option.value = Value;
x.add(option);}
function add(Text, Value){
var x = document.getElementById("stuff");
var option = document.createElement("option");
option.text = Text;
option.value = Value;
x.add(option);}
var c = 0;
var value =<?php echo json_encode($ToAndFromR); ?>;
var formula = <?php echo json_encode($FormulaR); ?>;
while(c < <?php echo $countr ?>){
add0(value[c], formula[c]);
add(value[c], formula[c]);
c++;
}
This was done after recieving $ToAndFromR and $Formula from a SQL Query, in which the code is :
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//declare variables
$countr = null;
$sql = "SELECT * FROM `convert`";
$drippage = mysqli_query($conn, $sql);
//this counts the number of rows
if (mysqli_num_rows($drippage)) {
$countr = mysqli_num_rows($drippage);
}
$ToAndFrom = mysqli_query($conn, "SELECT ToAndFrom FROM `convert`");
$ToAndFromR = null;
$ToAndFromR = mysqli_fetch_all($ToAndFrom, MYSQLI_BOTH);
$FormulaR = null;
$Formula = mysqli_query($conn, "SELECT Formula FROM `convert`");
$FormulaR = mysqli_fetch_all($Formula, MYSQLI_BOTH);
However, the HTML gets shown as [object Object] in the dropdown list, as opposed to their actual values when a regular PHP array is used. Is there a way to fix this?
Each Text and Value passed to your JavaScript functions will be an object with two properties (because you're using MYSQLI_BOTH fetch mode), eg
{"0": "some value", "ToAndFrom": "some value"}
You're attempting to assign this to the option's text and value properties.
You also appear to be running three queries when you should be running one.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8');
$result = $conn->query('SELECT `ToAndFrom` AS `text`, `Formula` AS `value` FROM `convert`');
$options = $result->fetch_all(MYSQLI_ASSOC);
and in your JavaScript
var options = <?= json_encode($options) ?>;
for (var i = 0, l = options.length; i < l; i++) {
add0(options[i].text, options[i].value);
add(options[i].text, options[i].value);
}
Also, you could cut down on the almost identical JavaScript functions add0 and add by simply passing the <select> ID, eg
function add(selectId, text, value) {
var x = document.getElementById(selectId);
// and so on
}
with
add('thingy', options[i].text, options[i].value);
add('stuff', options[i].text, options[i].value);
I think you should write a separate PHP script which echo the JSON.
Then in the javascript, you should call this PHP and parse the JSON. A simple code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "sql.php", true);
var htmltext= '';
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var jsoninfo = xhr.responseText;
var obj = JSON.parse(jsoninfo);
// text = obj.attribute;
// add0(text,formula[c])
}
}
}

Categories

Resources