I need help on how to post and retrieve multiple variables using Ajax Post. I actually needed to retrieve the posted variables for SQL query. See below the Ajax Code where i needed to include variable names selschool, selprogram, selsession to the post
<script>
$("#session").change(function()
{
$("#loding2").show();
var id=$(this).val();
var dataString = 'id='+ id;
var selschool=document.getElementById("selectedschool").val();
var selprogram=document.getElementById("selectedprogram").val();
var selsession=document.getElementById("selectedsession").val();
$("#semester").find('option').remove();
$("#class").find('option').remove();
document.getElementById("selectedclass").value= " ";
document.getElementById("selectedsemester").value= " ";
$.ajax
({
type: "POST",
url: "get_class.php",
data: dataString,
cache: false,
success: function(html)
{
$("#loding2").hide();
$("#class").html(html);
}
});
});
</script>
Also see below PHP script where i wanted to use the posted variable for the query;
<?php
include('dbconfig.php');
if($_POST['id'])
{
$id=$_POST['id'];
// Todo: I actually needed something like where session SELECT * FROM class where session_id=$id and program_id="selprogram" and school_id="selschool"
$stmt = $DB_con->prepare("SELECT * FROM class where session_id=$id ");
$stmt->execute(array(':id' => $id));
?><option selected="selected">Select Class :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
}
?>
Let me explain the solution
consider the ajax call to demo.php
$.ajax({
url: 'demo.php',
type: 'post',
data: {
'name': 'abc',
'phone': '1234567899'
}, //data is in json form
success: function(res) {
console.log(JSON.parse(res)); //parsing because we will pass the data from demo.php in encoded form you will get it.
}
});
now in demo.php you will access data as $_POST['name'] and $_POST['phone']. lets pass the same to ajax call. will store it in array and will pass it.
<?php
$Arr = [];
$Arr[0] = $_POST['name'];
$Arr[1] = $_POST['phone'];
echo json_encode($Arr);
?>
like this, we can pass data to ajax and can pass the data from PHP file to request.
Hope that you got the result. Thank you.
Related
I have a list of divs with unique IDs (they are inserted from my database). When I click on one of them I want to display content from my database in another div. For example, I have a div with class pizza. The query should look like this: SELECT * FROM product WHERE name = 'pizza'. So depending on what div you click you get different content. The code below doesn't work and is incomplete. I was trying to do some research myself, but I couldn't find anything useful.
//head
<script>
$(function () {
$('.product').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
},
error: function () {
}
});
});
});
</script>
//HTML
<div class="product" id="pizza">pizza</div>
<div class="product" id="lasagna">lasagna</div>
<div class="product" id="sushi">sushi</div>
<div class="display_recipe"></div>
// PHP (recipe-container.php)
<?php
function display_recipe(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = "'pizza'"; //just a placeholder
$sql = "SELECT * FROM product WHERE name = $product";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$name = $row['name'];
$description = $row['description'];
$date = $row['date'];
echo $name;
echo "<br>";
echo $description;
echo "<br>";
echo $date;
echo "<br>";
}
mysqli_close($con);
}
display_recipe();
?>
Right now when I click the button nothing happens, even "pizza" placeholder doesn't work. Is there a simple way to do it?
JS file (AJAX code)
You can get the id attribute on click of the div with the class 'product' as coded below:
jQuery(function () {
jQuery('.product').on('click', function (e) {
var product = jQuery(this).attr('id');
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: {data:product},
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
}
});
});
});
PHP file: get the posted data in this file use it in a query to fetch the result and return the result to the AJAX success handler as a response.
To fetch the data posted from the ajax in this php file you can use $_POST['data'] as stated below:
$product = $_POST['data'];
Use that variable in your sql query to fetch the result and then change the structure of your response as stated below:
//saving the html response in a variable named "response"
$response = $name.'<br>';
$response .= $description.'<br>';
$response .= $date.'<br>';
//echo response will send the response variable back to the AJAX success handler.
echo $response;
I have data in localStorage and POST successfully to the self php file using ajax as code below:
<script type="text/javascript">
var cartID = JSON.parse(sessionStorage.getItem("magiohang"));
console.log("your cart ID is:"+cartID);
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: {cartID: cartID},
success: function(data){alert("data transfered successfully")}
});
</script>
then I want to recall this data to a variable inside this php file so that I can send it to my email. Code as below:
<?php
$name = "";
error_reporting(E_ALL); ini_set('display_errors', 1);
if (isset($_POST["cartID"])) {
$name = $_POST["cartID"];
}
echo $name."\n";
$values = json_decode($name);
echo "your cartID is: ".$values."\n";
?>
I test it in inspect view there is no error message but the variable $name doesnot have recalled data. Please help me to fix it. Thank you.
You are most likely missing the JSON.stringify call on your data:
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: JSON.stringify({cartID: cartID}),
success: function(data){alert("data transfered successfully")}
});
Below is my ajax call code. I want to send one data in .php file via ajax call and want to get two values from .php file. This two values I want to set in different 'input' tags whose id are 'course_name' and 'course_credit'.
Here my ajax call return correct value(real value from DB table) of 'course_name' input tag.
But 'MY PROBLEM IS' the value of input tag whose id is 'course_credit' shows 'success'. How can I get the correct value(real value from DB table) of id 'course_credit' ?
I have a 'select' tag which id is 'c_select'
HTML:
<input type="text" name="course_name" id="course_name" value=""/>
<input type="text" name="course_credit" id="course_credit" value=""/>
AJAX :
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
});
});
get_course_info_db.php
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name,$c_credit;
exit();
?>
AJAX code:-
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
$('#course_name').val(data[0]);
$('#course_credit').val(data[1]);
}
});
});
PHP code:-
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name.",".$c_credit;
exit();
?>
The success callback is Function( PlainObject data, String textStatus, jqXHR jqXHR ); http://api.jquery.com/jQuery.ajax/
php:
$data = array(
'name' => $c_name,
'credit' => $c_credit,
);
echo json_encode($data);
javascript:
success: function(data) {
var result = $.parseJSON(data);
$('#course_name').val(result.name);
$('#course_credit').val(result.credit);
}
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
second arguement is the status of http request, you have to encode the answer, i suggest you JSON
in your php
$c_credit = $all_course_data['c_credit'];
echo json_encode(array('name' => $c_name,'credit' => $c_credit));
exit();
and in your javascript
success: function(response,status){
var datas = JSON.parse(response);
$('#course_name').val(datas.name);
$('#course_credit').val(data.credit);
}
this is not tested, but this is the way to do it
I'd suggest using JSON to encode the data you fetch from the database.
Try changing your ajax call as follows:
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
dataType: 'json', // jQuery will expect JSON and decode it for you
success: function(reply_data){
$('#course_name').val(reply_data['c_name']);
$('#course_credit').val(reply_data['c_credit']);
}
});
});
And your PHP as follows:
include('db_connection.php');
// Escape your input to prevent SQL injection!
$c_id = mysql_real_escape_string($_POST['c_id']);
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
echo json_encode($all_course_data);
exit();
I haven't tested this but I imagine it'd work for you.
I have a php code (no functions, just direct code) which queries a data base stores values
in an array and returns the array
<?php
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo $arr['min(date)'].'</br>';
echo $arr['max(date)'];
return $array;
?>
this is my jquery ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
url: $url,
success: function(data) {
document.getElementById("from_date").value = data['min_date'];
document.getElementById("to_date").value = data['max_date'];
}
});
}
when I echo the php variables I do get the data which I want. but logging the jquery variables the give me result as undefined.
maybe the php return data is not fetches by ajax success(data)? or do I need to have a function in my php code? how do I fetch returned array in my jquery?
Thanks!
Try encoding the array in php side with json_encode().
In your PHP
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo json_encode($array); //add this
In ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
dataType:'json', //add dataType
url: $url,
success: function(data) {
document.getElementById("from_date").value = data.min_date;
document.getElementById("to_date").value = data.max_date;
}
});
}
i am trying to get a row of data from database using ajax in codeigniter.
Here is the javascript function-
$(function(){
$("button[name='program_view_details']").click(function(e){
e.preventDefault();
var program_id=$(this).attr('id');
$.ajax({
url: "<?php echo base_url();?>program_management/get_program_data",
type: "POST",
dataType: "html",
data: "program_id="+program_id,
success: function(row)
{
alert(row.program_name);
}
});
});
I am not sure if the datatype and post is correct or not.
Here is my controller function-
public function get_program_data( ){
$program_id = $this->input->post('program_id');
$this->load->model('program_management_model');
$data['programs']= $this->program_management_model->get_program_specific($program_id);
echo $data;
}
Here is the model-
function get_program_specific($program_id){
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
return $query->result();
}
I am searching the way of returning the row from controller to javascript. But the alert() is showing "undefined" in the success. Please anyone tell me the whole way through. Thanks in advance.
$data['programs']= $this->program_management_model->get_program_specific($program_id);
The $data which you are echoing in the controller is basically an array[] and programs is an array which is present in $data. Either echo the $data in controller using the
foreach(){}
or echo the $query array in your model. That will do the trick.And in ajax success call just append the data to the element in which you want to show the result.
Change names as per your page.
in your script:
$.ajax({
url: '<?php echo base_url();?>managealerts_edit/editalerts',
type: "POST",
data: {'id': edit_id},
cache: false,
dataType: "json",
success: function(row){
//alert(row.sub);
$('#edit').show();
$('#sub').val(row.sub);
$('#mess').val(row.mess);
}
});
in your model:
$query = $this->db->query("SELECT fld_id, fld_course_id,fld_sub,fld_mess from tbl_alerts where fld_id='".$det."' ");
if ($query->num_rows() > 0)
{
$row = $query->row_array();
$data=array("sub" => $row['fld_sub'], "mess" => $row['fld_mess']);
echo json_encode($data);
}
in your controller:
$det = $this->input->post('id');
//$alertsres['tbl_alerts'] = $this->managealerts_m->select_editalerts($det);
$this->managealerts_m->select_editalerts($det);`
in model
function get_program_specific($program_id){
$temp=array();
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
$temp= $query->row_array();
echo $temp['program_name'];
}
in controller change the line
$data['programs']= $this->program_management_model->get_program_specific($program_id);
with
$this->program_management_model->get_program_specific($program_id);
and finally in javascript
alert(row);
please let me know if you face any problem.