Using jQuery and php to pull data from database - php

I have a page that is pulling data through jQuery but it is only pulling the return code. Here is my code:
<script type='text/javascript' language='javascript'>
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val()
},
function (response) {
$('#contact').val(response).show();
$('#email').val(response).show();
$('#phone').val(response).show();
})
}
</script>
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . $_POST['id'] . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
if (mysql_num_rows($query) > 0) {
while ($get = mysql_fetch_array($query)) {
$priContact = $get['priContact'];
echo $priContact;
echo $get['priEmail'] . " | " . $get['priPhone'];
}
} else {
echo "No users";
}
So the call is pulling from getCU.php whenever the onchange event handler is called. That is why this is in a function. What I want to do is every time a user chooses something from the option list the text values change according to what was selected. I have the php page pulling from a db and echoing out the code correctly. jQuery id pulling the data from the php page correctly, but I cannot get the code to place the single details in each of the text boxes.
So what I want to happen is this:
A user selects a name from a drop-down box. Then the mysql data attached to that name would be displayed on the page in form text fields.
Let me know if more information or code is needed.

I think you'll be better off structuring your data. My general recommendation is JSON.
// QUICK WARNING: Don't take unparse GET/POST responses.
// This is asking for trouble from SQL injection.
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . mysql_escape_string($_POST['id']) . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
$retVal = array();
if (mysql_num_rows($query) > 0) {
$retVal['data'] = array();
while ($get = mysql_fetch_array($query))
{
$retVal['data'][] = $get;
}
} else {
$retVal['error'] = 'No users';
}
header('Content-type: application/json');
echo json_encode($retVal);
Javascript:
<script type="text/javascript">
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val(),
dataType:'json'
},
function (response) {
if (response.error) {
//handle error
}
else
{
$('#contact').val(response.data.priContact).show();
$('#email').val(response.data.priEmail).show();
$('#phone').val(response.data.priPhone).show();
}
})
}
</script>

Related

Passing values from a php page to a modal from other page

I'm trying to edit a post using this snippiet of from my query.php page:
echo '<button type="submit" onclick="openModal(this)" id="btn-edit"
name="edit" value='.$postID.'></button>';
function openModal(id)
{
var editpost = id.value;
$.ajax({
url:"query.php",
method:"POST",
data:{ editpost : editpost },
success:function(data)
{ //
},
error: function () {//
}
});
$('#edit').modal('show');
}
The function to get the data from the post selected is on the same php page. This is the code:
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$_SESSION['editpostdesc'] = $row['PostDesc'];
$_SESSION['editpostfile'] = $row['PostFile'];
$_SESSION['editpostid'] = $row['PostId'];
}
}
}
}
But the modal is on the other page (main page). I want to get the data of the post and display it on the modal, so I tried using $_SESSION. Yes, I got the data and was able to display it on the modal, but the problem is when I try to edit another post, the first value assigned to the session cannot be replaced. Is there is any other way that I can pass the values without using session? I'm really running out of ideas, I'm just starting my first web project.
if you get multiple row means this methods will worked...
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$res[] = array(
'editpostdesc' => $row['PostDesc'],
'editpostfile' => $row['PostFile'],
'editpostid' => $row['PostId']
);
}
}
}
}

AJAX function putting post in URL, rather than to page

I've got a dropdown, which when selected, should then go query the DB and get a report back. When the user selects the option from the dropdown, it should dynamically change the field without reloading the page.
However, it does seem to reload the page, and the $_POST data is inserted and visible in the URL.
Code in my custom page (This is in Wordpress btw, but I don't think it's a Wordpress issue)
<form class="get_monthly_report_form" role="form" action="">
<input type="submit" id="function" name="function" value="Retrieve Whole Report"> {code excised here that fills the dropdown}
</form>
<div id="search_results"></div>
and here's the code from the .js file
//Monthly Reports
<script>
// wrap everything in a closure
(function($){
// get our references
var $form = $('form.get_monthly_report_form'),
$search_field = $('#function'),
$results = $('#search_results');
// AJAX search call
function do_search_reps() {
// grab the query value from the search field
var search_text = $search_field.val();
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get_and_view_report",
search_text: search_text
}).serialize(),
success: function (response){
console.log(response);
$results.html(response);
}
}); }
// on submit, do the search but return false to stop page refresh
$form.submit(function(e) {
e.preventDefault();
do_search_reps();
return false;
});
})(jQuery);
and the code in my project_functions file is
function get_and_view_report()
{ var_dump ($_POST);
// first, get data passed
$data_passed = explode("++",$_POST["monthly_report_ID"]);
$report_key = $data_passed[0];
$report_type = $data_passed[1];
//print_r ($report_key);
//print_r ($report_type);
//get data about the report as a whole.
$sql = "SELECT * FROM reports_list WHERE report_key ='" . $report_key . "'";
$report_data = $wpdb->get_results ($sql);
//if statement to set up which table to query from NEED TO FINISH THIS
if (substr ($report_data[0]->report_key,0,3) == "sdr")
{
$sql = "SELECT * FROM deployment_list_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,3) == "Off")
{
$sql = "SELECT * FROM officer_list_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,4) == "stat")
{
$sql = "SELECT * FROM status_report_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,3) == "wtr")
{
$sql = "SELECT * FROM service_time_wages_lines WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,3) == "flr")
{
$sql = "SELECT * FROM fleet_ships_list_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
//print_r ($sql);
$reports_in_db = $wpdb->get_results($sql);
if (empty($reports_in_db))
{
echo "No Data Returned. Something's Wrong";
}
else
{
//print_r ($reports_in_db);
//print_r ($report_data);
//Time to start building the file to go out.
//so we're going to build an array of things, bringing together all the things
$total_report = array();
foreach($reports_in_db as $key)
{
$total_report [$key->line_number] = $key;
}
// get subtitles/abstract
$sql = "SELECT line_number, field_text FROM subtitle_abstract_summary WHERE report_key = '" . $report_key . "'";
$abs_sums = $wpdb->get_results ($sql);
//now for a series of conditional things
foreach ($abs_sums as $key)
{
$total_report [$key->line_number] = $key;
}
ksort ($total_report, SORT_NUMERIC); //sorting the lines and subtitles into the correct order.
//Now an if statment- calling the sort functions based on report type- NEEDS TO BE DONE
$arrs_to_be_printed = sort_ship_deployment_data_single_report ($total_report);
//Now Create the File headers
$file_headers = array($report_data[0]->report_title, $report_data[0]->report_date, $report_data[0]->transcription_notes, $report_data[0]->labels_row, $arrs_to_be_printed[0]);
print_report_to_screen ($file_headers, $arrs_to_be_printed[1]);
}
}
add_action('wp_ajax_get_and_view_report', 'get_and_view_report');
add_action('wp_ajax_nopriv_get_and_view_report', 'get_and_view_report');
and when I click submit (and try to use the Ajax call - what happens is that the page reloads (when I don't want it to) and the URL now is something like
"view-monthly-report/?monthly_report_ID=OffRec1514581778%2B%2Bofficer_list&function=Retrieve+Whole+Report"
Which looks to me like the post data is being put into the URL - and when in the function, var_dump, the result is
"array(0) { } No Data Returned. Something's Wrong"
As I do testing- it seems that the action hook isn't working.
I would appreciate any help.

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.

Having an Ajax Save button and save in database

I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.
Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?
Not very sure with AJAX and all so Thanks for helping!
This is for the "Save" button.
<input type="button" onClick="save();" value="Save">
This is the insert query whereby it will be inserted in database.
<?php
include("dbFunctions.php");
$idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);
while ($row = sqlsrv_fetch_array($idResult)) {
$fcID = $row['id'];
$question = $row['question'];
$surveyTitle = $_SESSION['surveyTitle'];
$input = $row['input'];
if (isset($_POST['qns' . $fcID])) {
$answer = implode(",", $_POST['qns' . $fcID]);
$newAns = str_replace($singleQuote,$changeQuote,$answer);
} else {
$newAns = '';
}
if (isset($_POST['others'.$fcID])) {
$others = $_POST['others' . $fcID];
$newOthers = str_replace($singleQuote,$changeQuote,$others);
}else {
$newOthers = 'N.A.';
}
$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo);
if ($input != 'Normal text line, no input required*') {
$query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";
$status = sqlsrv_query($newconn, $query);
} }
if ($status === false) {
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
You can use jquery $.ajax() to send data from client side to PHP. (eg)
$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});
Then in PHP page, use $_POST[] to capture data and insert it into database.
$id = $_POST['id'];
$name = $_POST['name'];
Make sure you escape the values and make it safe for sql insert.

How do I get javascript to read the output of a php file

First off hello, I am new here.
My problem is that I have a php file pulling info from a database. I will post the code below.
What I need is for my JavaScript to take the output and load it into a list that generates some flash cards.
code sample `$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
$query1 = "SELECT * FROM category_tb WHERE cat_name = '$category'";
$result1 = mysql_query($query1) or die ("Error in query: $query1. " . mysql_error());
while ($row = mysql_fetch_array($result1))
{
$cat_num = $row[1];
}
// This establishes a link to MySQL
$query = "SELECT * FROM english_lang, finnish_lang ".
"WHERE english_lang.lang_id = finnish_lang.lang_id AND english_lang.cat_id = $cat_num";
$rt = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
while($nt=mysql_fetch_array($rt)){
echo "{\"english\": \"$nt[1]\", \"finnish\": \"$nt[6]\" , \"asked\": states.notAsked},";
}
`
So this basicly gets some data and formats it to be used by the javascript.
if you want to look at the output of this to get a better idea the go here
http://languagelearner.byethost2.com/vocabulary2.php
select 1 of the first 2 categories as they are the only ones with data right
now.
the javascript is this:
code sample `
var string1;
var string2;
var number;
var states = {"oneVisible": 0, "bothVisible": 1, "notAsked": 2, "asked": 3}
var state = states.bothVisible;
var numberOfWordsAsked = 0;
var words = {"list": [
]
}
function displayWords(){
if (state == states.bothVisible) {
if (numberOfWordsAsked < words.list.length) {
state = states.oneVisible;
number = Math.floor(Math.random() * words.list.length);
while (words.list[number].asked == states.asked) {
number = Math.floor(Math.random() * words.list.length);
}
string1 = words.list[number].english;
string2 = words.list[number].finnish;
document.getElementById("fin").style.display = 'none';
document.getElementById("eng").innerHTML = words.list[number].english;
document.getElementById("fin").innerHTML = words.list[number].finnish;
document.getElementById("b").value = "Show word";
document.getElementById("correct").style.display = 'none';
}
else {
document.getElementById("eng").innerHTML = "You know all the words in this category, congratulations!";
document.getElementById("fin").style.display = 'none';
document.getElementById("b").style.display = 'none';
document.getElementById("correct").style.display = 'none';
}
}
else {
document.getElementById("fin").style.display = 'inline';
state = states.bothVisible;
document.getElementById("b").value = "Wrong";
document.getElementById("correct").style.display = 'inline';
}
}
function setCorrect(){
words.list[number].asked = states.asked;
numberOfWordsAsked += 1;
displayWords();
}
//-->
</script>
`
so the output needs to go in here.
var words = {"list": [
]
Any help would be appreciated. I did not write the javascript, a friend did.
He used static info in the list.
Try AJAX. Check out http://www.w3schools.com/PHP/php_ajax_database.asp
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
alert(ajax.responseText);
}
};
ajax.open("GET", "ajax.php", true);
ajax.send(null);
outputs "hello world" when used in the same directory as a php file ajax.php:
<php
echo 'hello Word!';
?>
To put php data structures into something javascript can parse, use json_encode. That should be enough to help you on your way.

Categories