ajax function on change dropdown Value - javascript

Hie Everyone!
In PHP page1 my code is here..
<html>
.
...
<select id="customer">...</select>
..
....
<div id="show"></div>
//and Java script function (ajax call)
<script>
$('#customer').change(function(){
var Id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "ID="+id,
success: function( data ) {
document.getElementById("show").innerHTML = data;
}
});
});
</script>
</html>
In php page2 as code..
<?php
$ID=$_GET['ID'];
...
//db connection code
..
$sql="select * from Table1 where id='$ID'";
//result code..
//while loop..
//echo something..
// all working without error..
?>
So, when I was trying to do this.It does not showing the success data or may be Ajax function not work.I had check with alert(data);
but does not Alert anything.
please help.

You will give echo infront of the $get_id variable. But you will make sure only one echo in the page2.php page.
<?php
echo $get_id=$_GET['pass_id'];
...
//db connection code
..
$sql="select * from Table1 where id='$get_id'";
//result code..
//while loop..
//echo something..
// all working without error..
?>
Then in page1.php check your ajax response. using alert function.
<script>
$('#customer').change(function(){
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id="+id,
success: function( data ) {
alert(data);
document.getElementById("show").innerHTML = data;
}
});
});
</script>

Related

How to put the ajax response/result into variable php

Can I put the ajax response into variable? So that I can echo the variable into php?
ajax.php
<script>
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
$("#random_no_container").html(result);//the result was displayed on this div
}
});
}
</script>
On my sample code above, i call the query result from test.php and the result was displayed on the div but i want to put that on the variable and echo the variable. something like the code below
<?php echo $variable;?>
Can this possible? please help me. Thank you so much.
You can't PHP is executed on server and Ajax from the client so you cannot assign PHP variable an ajax response.
Once a PHP is rendered on the client side it is just HTML no PHP code.
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
var result_val=result;
alert(result);
}
});
}
As #dev answered , you need to execute server and client code differently ! I answered here for your need variable only .But in developing website, should not use javascript in php tag <?php ?>
ajax.php
<div id="random_no_container">
<?php
if(isset($_GET['variable'])) {
$variable = $_GET['variable'];
echo $variable;
} else {
echo "<script>sessionStorage.setItem('stopped',0);</script>";
}
?>
</div>
<script>
var stopped = sessionStorage.getItem("stopped");
if(stopped == 0) {
random_no();
}
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
sessionStorage.setItem("stopped",1);
//$("#random_no_container").html(result);//the result was displayed on this div
location.href = "ajax.php?variable="+result;
}
});
}
</script>

Ajax submit returning Error but updating the database fine

<script>
function addprescription() {
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
}
</script>
I have a function to submit the form. But ajax function alerts its as failure. But data base seems to be updated. when I click the button. I couldn't find the reason for the cause in the console.
this is the php file
<?php
echo "I'm in";
include "../../Adaptor/mysql_crud.php";
include ("Prescription.php");
$prescription=new Prescription();
if(isset($_POST)){
$Note=htmlspecialchars($_POST['Note']);
$Case_Histroy=htmlspecialchars($_POST['Case_Histroy']);
$medication = htmlspecialchars($_POST['Medication']);
$pname=$_POST['pname'];
$danme=$_POST['dname'];
$id=$_POST['id'];
$prescription->insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
<div class="alert alert-success" id="alert"><strong><?php echo "Submitted succesfully"; ?></strong></div>
<?php
}
?>
Try adding an else statement to your if:
insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
}
?>
Also, it's not necessary to stick the php in the middle of the <div> you can just use echo at the beginning since you're not introducing any variables to it:
echo '<div class="alert alert-success" id="alert"><strong>Submitted successfully</strong></div>';
Finally I got the answer for the Problem! Actual problem is button that fired up the AJAX request also reloaded the page interrupting AJAX inner workings. So the error message will be alerted.
I tried this code.
<script>
$(function() {
$("#button_Add_p").click(function(e){
e.preventDefault();
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
dataType: 'html',
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
});
});
</script>

How to get data from one php page using ajax and pass it to another php page using ajax

I am trying to get data from one php page and pass it to another page using Ajax.
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id=data"
}
});
action.php :
<?php
$test= 1;
?>
data.php :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
<?php
$id = $_GET['id'];
echo $id;
?>
First of all, you need to echo your data in action.php, and second, use data parameter of AJAX request to send data to data.php.
Here's the reference:
jQuery.ajax()
So the organization of pages should be like this:
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php",
data: {id: data},
success: function(data){
// your code
// alert(data);
}
});
}
});
action.php :
<?php
$test = 1;
echo $test;
?>
data.php :
<?php
$id = $_GET['id'];
echo $id;
?>
Try to use $.get() method to get/send data :
$.get("action.php",{}, function(data){
//data here contain 1
$.get("data.php", {id: data}, function(id){
alert(id);
}
});
Just echo $test since just the data printed in page will return as responce to the query request.
action.php :
<?php
$test=1;
echo $test;
?>
Hope this helps.
For example,
Test
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
action.js
$('.dataClass').click(function(){
var value=$(this).attr('data-value');
$.ajax({url:"Ajax_SomePage.php?value="+value,cache:false,success:function(result){
alert("success");
}});
});
Ajax_SomePage.php
<?php
$value = $_GET['value'];
echo $value;
?>
To get data as response in ajax call, you need to echo the result from your php page; action.php page.
echo $test = 1;
In your provided code
$.ajax({
url: "data.php?id=data"
} // closing bracket is missing
you are sending the string data as id to data.php page. Instead you have to append the result with the url using + symbol like shown in the below code.
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id="+data
})
}
});

javascript array in php using Ajax on submit not working

I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.

How to get a row from database using ajax in codeigniter

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.

Categories

Resources