for each ajax post to another file - javascript

So i have a for each function that prints the "local" column from this database:
https://i.imgur.com/IzKOzkt.png
It is working all good till here, this is what i get:
https://i.imgur.com/WH7d4uh.png
Now i want to send variables by post, when the user clicks on different menu items, i've tried everything, but i cant get it to work. Here is my code:
<?php
$query = "SELECT * FROM credenciais_sensores where ambiente = '1'";
$results = mysqli_query($conn, $query);
foreach ($results as $result){
$local = $result['local'];
$local = substr($local,0,7);
echo "<li><a class='clsPostData' data-oxiid='".$result['oxi_sensorid']."' data-oxikey='".$result['oxi_apikey']."' data-redoxid='".$result['redox_sensorid']."' data-redoxkey='".$result['redox_apikey']."' href='#'>".$local."</a></li>";
}
?>
This is working fine, the menu is being printed as i want, but now i cant get to post the data i want, like the "oxi_sensorid", etc... Here is my javascript:
<script type="text/javascript">
$(function(){
$('.clsPostData').click(function(e){
e.preventDefault();
var objPost = {};
objPost.oxiid = $(this).data('oxiid');
objPost.oxikey = $(this).data('oxikey');
objPost.redoxid = $(this).data('redoxid');
objPost.redoxkey = $(this).data('redoxkey');
$.ajax({
url: 'getObjects.php',
type: 'post',
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});
});
});
</script>
And my getObjects.php file:
<?php
$oxiid = $_POST["oxiid"];
$oxikey = $_POST["oxikey"];
$redoxid = $_POST["redoxid"];
$redoxkey = $_POST["redoxkey"];
$response["message"] = "Grettings from php, we receive your data: ".$oxiid . $oxikey . $redoxid . $redoxkey;
echo json_encode($response);
?>
But i'm always getting the popup saying "undefined" when i click on any menu item... Any help?

I think the problem there is you need to set the dataType to json. Try adding dataType: 'json' after type: 'post' on your ajax code:
$.ajax({
url: 'getObjects.php',
type: 'post',
dataType: 'json', // add this
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});

Related

Display content from the database when a div with an ID is clicked (AJAX)

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;

updating a database when clicking on a button

I have a button here:
<button type="button" class="btn btn-primary">add me</button>
I tried to use AJAX; in my database I have a sp_status ( in my $UserData which is an array). I wanted to change the user sp_status in database with id of $UserData['sp_id'] from 5 value to 0.
Here is the code I try to do this with it:
<script>
$(document).ready(function(){
$(".btn").click(function(){
alert("PROBLEM IS HERE!");
$.ajax({
url: "update.php",
type: "POST",
data: {uid: $UserData['sp_id']}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
}
});
});
});
</script>
The $UserData array has sp_id as identifier of the user.
Inside of update.php in same folder I wrote this code:
<?php
if(isset($_POST['uid'])){
$query = mysql("UPDATE `signup_participant` SET sp_status = 0 WHERE sp_id = ".$_POST['uid']));
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
There are two main problems I face with. First when I move alert("PROBLEM IS HERE!");one line down, and click, nothing happens.
The other problem is about update.php. I copy and paste UPDATEsignup_participantSET sp_status = 0 WHERE sp_id =10 (static value of 10) and everything works fine in console of phpMyadmin.I read a lot of questions here on stack, but no one helps.
Can anyone fix this?
EDIT:
As friends said, I change my code to this ( the AJAX part):
<script>
$(document).ready(function(){
$(".btn").click(function(){
alert('Hello');
$.ajax({
url: "update.php",
type: "POST",
data: {uid: "<?php echo $UserData['sp_id'];?>"}
success: function(data){
data = JSON.parse(data);
}
});
});
});
</script>
The weird thing is that the popup alert is not shown anymore. Is there any ideas?
Yes, you have to mistakes:
The first one is "$UserData['sp_id']" which you called in a Javascript code, it's not clear what do you mean from this variable or where did it come from, if it's a value of an Html element then it should be:
data: {uid: $('#sp_id').val();},
And if it's a Php variable it would be:
data: {uid: <?php $UserData['sp_id']; ?>},
The next mistake is in the Php server code:
$query = mysql("UPDATE `signup_participant` SET sp_status = 0 WHERE sp_id = ".$_POST['uid']));
$results = mysql_fetch_assoc($query);
Those two commands are separated, the first one is for updating database and the second one for showing results from it and they must be like follow:
$query = "UPDATE `signup_participant` SET sp_status = 0 WHERE sp_id = ".$_POST['uid'];
mysql_query($query);
$query = "SELECT * from `signup_participant` WHERE sp_id = ".$_POST['uid'];
$select = mysql_query($query);
$results = mysql_fetch_assoc($select);

Using two Ajax calls to post then retrieve data

I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.

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