Hello im doing some try and error. This is the code where select-option populate from database but this gives me null value
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from try where name = '".$_POST['name']."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
datatype: 'json',
success: function(result){
alert(result);
document.getElementById("sub").innerHTML = result;
}
});
<select id="sub" name="subb"></select>
my problem is whether i select from dropdown the content is there but no value. pls help..
PHP:
$ajaxAnswer = "<option value=\"\">"."Select"."</option>";
$instructor = mysqli_real_escape_string($conn,$_POST['instructor']);
$qry = "select * from try where name = '".$instructor."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
$ajaxAnswer .= "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
echo $ajaxAnswer;
Jquery:
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
success: function(result){
$("#sub").html(result);
}
});
data: {instructor:$('#SELECT_ELEMTN_ID').val()},
Depending on scope and stuff, you may not wanna use "this".
Jquery
$(document).ready(function () {
$.ajax({
type: "GET",
url: "phpfile.php",
dataType: "json",
success: function (data) {
$.each(data, function (idx, obj) {
$('#selectdata').append('<option value="'+obj.user_id+'">'+obj.user_name+'</option>' )
});
}
});
});
</script>
</head>
<body>
<select id="selectdata">
</select>
</body>
phpfile.php
<?php
$host = "localhost";
$user = "root";
$password ="";
$database= "databasename";
$con = mysqli_connect($host , $user , $password);
$database_connect = mysqli_select_db($con, $database);
$result = mysqli_query($con, "select Id as user_id,Name as user_name from users");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
?>
Related
My jQuery Ajax code:
$(".comment").click(function(){
var id = $(this).data("id");
var name = $("#username_"+id).val();
if(name==''){
alert("Please Fill All Fields");
}else{
$.ajax({
type: "POST",
url: "comments",
data:{username:name},
dataType: "JSON",
success: function(jsonStr){
$("#cmt_output").html(JSON.stringify(jsonStr));
}
});
}
});
My Php Code:
............
$con = mysqli_connect("localhost","root","","quotes") or die("Error".mysqli_error($con));
$name = $_POST['username'];
$user = get_userdetails();
$vw_id = $user->id;
$query = mysqli_query($con,"INSERT INTO tlb_comments(user_id,comments) values ('$vw_id','$name')");
$comments = mysqli_query($con,"SELECT * FROM tlb_comments");
$avatar = mysqli_query($con,"SELECT * FROM tlb_avatar WHERE `vw_id`='".$vw_id."'");
$avatar_select = mysqli_fetch_all($avatar);
$comment_select = mysqli_fetch_all($comments);
array_push($avatar_select,$comment_select);
echo json_encode($avatar_select);
I have the following code:
<?php
session_start();
?>
<html>
<head>
<title>Dashboard</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<button id="openjob">View open job requests</button>
<button id="jobtoday">View all job requests today</button>
<div id="responsecontainer"></div>
<script type="text/javascript">
$('#openjob').click(function() {
<?php
$_SESSION["flag"] = 0;
?>
$.ajax({
type: "GET",
url: "cssdashsubmit.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
$('#jobtoday').click(function() {
<?php
$_SESSION['flag'] = 1;
?>
$.ajax({
type: "GET",
url: "cssdashsubmit.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
</script>
</body>
</html>
cssdashsubmit.php includes
session_start();
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
echo $_SESSION['flag'];
if (isset($_SESSION['flag']) && $_SESSION["flag"] === 0) {
$sql = "SELECT * FROM Ticket WHERE ticket_close_open = 'open'";
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
unset($_SESSION['flag']);
}
if (isset($_SESSION['flag']) && $_SESSION["flag"] === 1) {
$sql = "SELECT * FROM Ticket WHERE DATE(ticket_open_datetime) = date('Ymd')";
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
unset($_SESSION['flag']);
}
?>
Now when I click on the buttons, it always echoes 3, irrespective of which button I click. I've tried changing the session variable name, but it still persists. Can anybody point where I am erroring?
Instead of session - use simple url parameter:
$('#openjob').click(function() {
$.ajax({
type: "GET",
url: "cssdashsubmit.php?type=jobs",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
$('#jobtoday').click(function() {
$.ajax({
type: "GET",
url: "cssdashsubmit.php?type=requests",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
On server side code can be:
session_start();
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
switch ($_GET['type']) {
case "jobs":
$sql = "SELECT * FROM Ticket WHERE ticket_close_open = 'open'";
break;
case "requests":
$sql = "SELECT * FROM Ticket WHERE DATE(ticket_open_datetime) = date('Ymd')";
break;
}
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: $mapCode,
used: $used,
active: $active,
},
dataType: "text",
});
}
</script>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
?>
I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working
If the file extension is .php and not .js then this should work
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: "<?php echo $mapCode; ?>",
used: "<?php echo $used; ?>",
active: "<?php echo $active; ?>",
},
dataType: "text",
});
}
</script>
If you have .js file then declare javascript variable before including your js in .php file
<script>
var mapCode = "<?php echo $mapCode; ?>";
var used = "<?php echo $used; ?>";
var active = "<?php echo $active; ?>";
</script>
then in .js file you will get easily
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: mapCode,
used: used,
active: active,
},
dataType: "text",
});
}
</script>
You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag
My current project is actually dealing with lots of ajax calls,
here is the simplified version of what I use to communicate with server:
// php
// needed functions
function JSONE(array $array)
{
$json_str = json_encode( $array, JSON_NUMERIC_CHECK );
if (json_last_error() == JSON_ERROR_NONE)
{
return $json_str;
}
throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
header('Content-Type: application/json');
print JSONE($array);
exit();
}
// pack all data
$json_output = array(
'mapCode' => $mapCode,
'used' => $used,
'active' => $active
);
// output/exit
output_array_as_json( $json_output );
// javascript
function _fetch()
{
return $.ajax({
url: 'getMapCode.php', // url copied from yours
type: 'POST',
dataType: 'json',
success: function(data, textStatus, req){
console.log('server respond:', data);
window.mydata = data;
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}
window.mydata = null;
_fetch();
I have not tested this, but let me know I'll fix it for you.
How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
// Outputing results:
echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>
Then in ajax, use success for listening return message after ajax finished:
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
/** Your data to send to server **/
},
dataType: "text",
success: function(data) { /** Here is data returned by php echo **/
var temp = $.parseJSON(data);
mapCode = temp['mapCode'];
used = temp['used'];
active = temp['active'];
}
});
}
</script>
I have drop down Select box as follows
<?php
$sql = "SELECT scheduleName FROM schedule";
$result = mysqli_query($link,$sql);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
?>
And I have a file called processClg.php as follows
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE 'Row id of drop down selection'";
$res = mysqli_query($link,$qry);
}
?>
How can I call processClg.php file on $("#schedule").change(function ());by assigning Row id of drop down selection as where condition.
Update
Am getting Response from processClg.Php as follows
[{"id":"2","scheduleName":"shanth","subject":"Patho","university":"Dali","facultyName":"Dr","scheduleStartDate":"2015-06-05","scheduleEndDate":"2015-06-09"}]
How to assign response values from ajax call to the following Php variables
<?php
$scheduleStartDate = '';
$scheduleEndDate = '';
?>
Any help my greatly appreciated.
$("#schedule").change(function() {
var value = $('#schedule option:selected').text();
var ajaxCheck = $.ajax({
url: 'processClg.php',
type: 'POST', // had mention post bcoz u mention in processClg.php
dataType: 'json', // processClg.php will return string means change to text
data: { id: value },
success: function(data){
console.log('success');
itrToRead(data);
}
});
});
function itrToRead(data) {
$(data).each(function(key, value){
console.log('key is: '+key+' and value is: '+value);
});
}
processClg.php
<?php
include "config.php";
if ($_POST['type']=='POST') {
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['id']."'";
$res = mysqli_query($link,$qry);
echo $res;
}
?>
You can call ajax as follows:
var RowId;
$.ajax({
type: "POST",
async: false,
url: url,
data: postdata,
//dataType: "json",
success: function (data) {
RowId = data;
}
});
The fact is that to assign response to variable is pass the parameter async: false,
Then its work.
I guess you have your dropdown in your rendered page and you want to send the selected value to the php page:
$("#schedule").change(function(){
var val2pass = $(this).find(':selected').val(); // get the value
$.ajax({
url: 'processClg.php',
type:'post', // <-----you need to use post as you are using $_POST[]
data: { rowid : val2pass }, //<---pass the value
success: function(data){
itrToRead(data);
}
});
});
So now on the php side you need to do this:
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['rowid']."'";
$res = mysqli_query($link,$qry);
}
?>
Your procellClg.php will be
<?php
include "config.php";
if (isset($_REQUEST['qid']))
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_REQUEST['qid']."'";
$result = mysqli_query($link,$qry);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
}
?>
and then make Ajax function call
$("#schedule").change(function() {
val = $(this).val();
$.ajax({
type: "POST",
async: false,
url: 'processClg.php',
data: {qid:val},
success: function(data){
$(this).html(data);
}
});
});
I have here a ajax. What I need to know if it possible to send back the post value and store it in php variable in the mainpage depending in onchange event? $_POST["mainlist_id"] store in php var?
getajax.php
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
$option1 = '';
while($row = $result1->fetch_assoc())
{
$option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
}
echo $option1;
}
?>
Mainpage
<script type="text/javascript">
$('#main').change(function () {
$.ajax({
url: 'getajax.php',
data: {
mainlist_id: $(this).val()
},
dataType: 'html',
type: 'POST',
success: function (data) {
$('#languages').html(data);
}
});
});
</script>
getajax.php
<?php
session_start();
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$_SESSION['mainlist_id']=$main;
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
$option1 = '';
while($row = $result1->fetch_assoc())
{
$option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
}
echo $option1;
}
?>
Mainpage
<?php session_start();
$main_id=$_SESSION['mainlist_id'];
?>
<script type="text/javascript">
$('#main').change(function () {
$.ajax({
url: 'getajax.php',
data: {
mainlist_id: $(this).val()
},
dataType: 'html',
type: 'POST',
success: function (data) {
$('#languages').html(data);
}
});
});
</script>