How to assign ajax response to Variables - php

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

Related

Getting the value from option

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

Ajax post value and store in php variable

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>

How to Retrieve Values Resulting From AJAX Live Search?

Below is a jQuery function that retrieves 2 textbox values and posts them to another file ("Student Search Results.php"), where a live search is run using the values.
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {
query: Search_Data
},
cache: false,
success: function() {
alert('The values were sent');
}
});
});
</script>
Below is the PHP script on the search page ("Student Search Results.php") that makes use of these values.
<?php
include "Connection.php";
if(isset($_POST['query'])){
$searchData = explode('?????', $_POST['query']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
echo $query;
?>
How would I be able to take variables from the PHP script (such as $result) to the first page, so I can create a result table? Simply including the PHP file does not work, as the file is only included once.
Thank you for your time.
Best option is to serialize to JSON using json_encode
I think best you can do is,
success: function(result) {
alert(result);
}
and Student Search Results.php print result in tabular format.
P.S. : Please follow proper file naming convention
use a proper URL, and send the data (and stop using camelcase for everything) :
$(".search").on('keyup', function() {
var data = {
team_name : $('#TeamName').val(),
teacher : $('#Teacher').val()
}
$.ajax({
type: "POST",
url: "student_search_results.php",
data: data,
cache: false
}).done(function(result) {
console.log(result);
});
});
And in PHP, you have to actually get the result into an array and json_encode it :
<?php
include "Connection.php";
$team_name = !empty( $_POST['team_name'] ) ? $_POST['team_name'] : null;
$teacher = !empty( $_POST['teacher'] ) ? $_POST['teacher'] : null;
if ($team_name && $teacher) {
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
?>
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = "Team_Name="+'Team_Name'&Teacher='+Teacher;
$.ajax({
type: "POST",
url: "Student_Search_Results.php",
data: Search_Data,
cache: false,
success: function(result) {
$('$output').html(result);
}
});
});
</script>
Here is output div
<div id="output"></div>
On Student_Search_Results.php page get
$tname = $_POST['Team_Name'];
$teacher = $_POST['Teacher'];
//your search query & print data

Ajax post in oscommerce

I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});

How to insert a variable in a query from .ajax post

I thought this will be very simple but i think there is a bug when posting a variable from .ajax to a query. Is there any other way I ca get my result?
here is my jquery:
jQuery_1_4_2(document).ready(function()
{
jQuery_1_4_2('.mainfolder').live("click",function()
{
event.preventDefault();
var ID = jQuery_1_4_2(this).attr("id");
var dataString = 'folder_id='+ ID;
if(ID=='')
{
alert("Serious Error Occured");
}
else
{
jQuery_1_4_2.ajax({
type: "POST",
url: "display_folder.php",
data: dataString,
cache: false,
success: function(html){
jQuery_1_4_2(".right_file").prepend(html);
}
});
}
});
});
here is my display_folder.php
<?php
$folder_id = $_POST['folder_id'];
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>
Can anybody explain why this not work? i tried to echo $folder_id and it is working, but when you put it inside the query it is not working.
Note: This is not a dumb question where i forgot my connection of db. Thanks
I agree with both you and here I am providing (just for clean display) the same with some little formatting.
var dataString = 'folder_id=1';
$.ajax({
url: "folder.php",
type:'post',
async: false,
data:dataString,
success: function(data){
alert(data);
}
});
and php part where I am getting folder_id properly.
<?php
$postid = $_POST['folder_id'];
//echo $postid;
$link = mysql_connect("localhost","root","");
mysql_select_db("test", $link);
$query = mysql_query("select * from post where id='$postid'");
while($row=mysql_fetch_array($query))
{
echo $row['text'] . "<br>"; //a, b etc in each row
}
?>
So it should work.
Try this in your php code
<?php
$folder_id = addslashes($_POST['folder_id']);
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>

Categories