How to pass onclick variable to mysql query in php - php

I'm getting text value from an onclick event. I have saved the data in (var id) in using jQuery. In the variable data will check the database and if it is matching it will display all the records.
My html code:
<div class="col-lg-3 col-md-6 test" data-idtest="Diabetes">
<a href="" class="box_cat_home">
<i class="icon-info-4"></i>
<img src="assets/img/icon_cat_3.svg" width="60" height="60" alt="">
<h3>Diabetes</h3>
<ul class="clearfix">
<li><strong>124</strong>Doctors</li>
<!-- <li><strong>60</strong>Clinics</li> -->
</ul>
</a>
</div>
My jquery code:
<script type="text/javascript">
$(document).ready(function() {
$('.test').click(function (){
var id = $(this).data('idtest') ;
//alert(id);
$.ajax({
url : "getting.php",
type: 'POST',
data : {id:id },
}).done(function(response) {
});
})
});
</script>
How can I achieve this?
Here my php code:
<?php
echo "ejejejej";
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'mysql';
$dbName = 'fre';
$id =$id;
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$men ="select * from tbl_users where doctor_speciality = $id";
$men_result=$db->query($men);
$projects=array();
while($row=mysqli_fetch_assoc($men_result)){
$projects[] = $row;
}
?>
please how can i achive this?

You should use $.ajax in jquery library
check Ajax for reference.
Basic example:
$.ajax({
url : "your_server_url",
type: 'POST',
data : {id:id },
}).done(function(response) {
//when request is success , done function is call so you should write anything or leave it empty
});
replace your_server_url with your server url that call php script which contain mysql query for save id

You need to use ajax.
You send the ID to a controller (in case you are using laravel or any other MVC frameworks)
or just post it to a PHP file. You select all the needed values from using php and return it as a JSON. ex:
And then you loop through it in jQuery and display it as needed.
$.post( "/php/getRecordsById.php", { id: yourSelectedId }, function( data ) {
//Do Something with recieved data here
}, "JSON");
Returning JSON data from php:
echo json_encode($yourSelectedData);

Related

How to add ID from PHP script to JavaScript code

I have a PHP script which Edit and Delete cars on my website. Now I want to make Edit and Delete buttons inside a dropdown, and I did but its adding dropdown just to the first car from the row, since the ID is the same for every dropdown. Now I know how to get the unique ID from every car from PHP but how can I achieve it in JavaScript. I will show you my code.
PHP:
$id = $row["id"];
<div class='dropdown'>
<button onclick='myFunction()' class='dropbtn'>Settings</button>
<div id='myDropdown".$id."'class='dropdown-content'>
".($featured!=1 ? "<a title='Make ".$title." Featured'href='forms/addfeatured.php?id=".$id."'>Make Featured</a>" : "<a title='Remove ".$title."' href='forms/removefeatured.php?id=".$id."'>Remove Featured</a>")."
<a title='Delete ".$title."' href='forms/deletecars.php?id=".$id."'>Delete</a>
</div>
JavaScript:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
So how can I have different ID in javascript so I can open dropdowns for each entry?
Only use , No need to technically learn AJAX or JSON !
You Just need to use the simple functions which has been prepared for use and has been put in the libraries. And set a few parameters that they need.
The important thing is that, You should know PHP runs on the server machine, not your browser or your PC.
So the PHP variables too.. They are not in your machine to easily put them in a JS variable.
At his point we need to communicate with the server to send them(using AJAX function) in a proper format(using JSON function) for us to use.
So, Your question :
How to add ID from PHP script to JavaScript code?
has the easiest solution just with these functions:
(At your browser page):
$.ajax({ .. some parameters .. });
$(document).ready(function() {
$.ajax({
type: 'post', //Transfer Protocol
url: 'serving.php', //Address of Server Page
dataType: 'json', //Data Structure
data: {action: 'demo'},
success: function(output) {
$variables = output;
}
});
});
and
(At your PHP page on the server)
json_encode(.. some data ..);
$variables = array("Chevy", "BMW", "Ford");
echo json_encode($variables ); // Encoded variable array
Unfortunately your codes and description are not clear for me to help directly in your project.
But I attach a simple practical Example :(in Jquery)
// carSelection.html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs
/jquery/2.1.1/jquery.min.js"> //jquery CDN
</script>
</head>
<body>
<div style="margin:2em">
<form id="myForm">
<select id="selectNumber">
<option>Choose a car</option>
</select>
</form>
</div>
<script>
var $cars = '';
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'carServs.php',
dataType: 'json',
data: {action: 'demo'},
success: function(output) {
$cars = output;
var option = '';
for (var i=0;i<$cars.length;i++){
option += '<option value="'+ $cars[i] +
'">' +
$cars[i] + '</option>';
}
$('#selectNumber').append(option);
}
});
});
</script>
</body>
</html>
And
// carServs.php page
<?php
// ...
$cars = array("Chevy", "BMW", "Ford");
echo json_encode($cars);
//...
?>
just remeber to attach the jquery CDN at your code, In the head section or just before ending the body tag </body>
And if you insist to have it in JavaScript, It's possible just with a few changes in syntax.

I want to show image in img tag when ajax is call in codeigniter

I want to show an image in img tag. when ajax is called in CodeIgniter.
this is the code which receives the data from the database and displays it in a bootstrap model. but the main problem is that I want to show an image in img tag but it not showing.
$(".Edit-modal").on("shown.bs.modal", function (e) {
var button = $(e.relatedTarget);
var ID = button.parents("tr").attr("data-id");
var modal = $(this);
$.ajax({
url: "'.base_url().'Employees/master_get_employees",
data: {ID:ID},
type: "POST",
success:function(output){
try{
var outputData = JSON.parse(output);
modal.find("#EditImage").attr("'.base_url().'src",outputData.pic);
}
catch(ex){
var split = output.split("::");
if(split[0] === "FAIL"){
Shafiq.notification(split[1],split[2])
}else{
Shafiq.notification("Could Not Load Data, Please Contact System Administrator For Further Assistance","error");
}
}
}
});
});
And This is the Img tag where I want to display image.
<div class="col-md-3">
<div class="form-group">
<label for="EditcontactNoSelector">Employee Picture</label>
<img src="" id="EditImage" alt="Not Found">
</div>
</div>
And this is the function through which data is fetched from the database
public function master_get_employees()
{
if ($this->input->post()) { //If Any Values Posted
if ($this->input->is_ajax_request()) { //If Request Generated From Ajax
$ID = $this->input->post('ID');
if (!isset($ID) || !is_numeric($ID)) {
echo "FAIL::Something went wrong with POST request, Please contact system administrator for further assistance::error";
return;
}
$table = "employees e";
$selectData = "e.id AS ID,e.Phone,e.Mobile,e.CNIC,e.Perm_Address,e.Picture as pic,d.name as Designation,s.title as Shift, e.Name,e.Father_Name AS FatherName,e.Phone AS Contact,e.JoinDate,e.BasicSalary, e.Pres_Address AS Address,e.IsEnabled";
$where = array(
'e.id' => $ID, 'e.IsActive' => 1
);
$result = $this->Common_model->select_fields_where_like_join($table, $selectData,$where, TRUE);
print json_encode($result,JSON_UNESCAPED_SLASHES);
}
}
}
I guess you have base_url() function in javascript to find base url of you site.
If so then you can use
$("#EditImage").attr("src",base_url()+outputData.pic);
If you don't have base_url() function in javascript you can find it here:
how to get the base url in javascript
instead of this
url: "'.base_url().'Employees/master_get_employees",
You can use below,
url: "<?php echo site_url('Employees/master_get_employees'); ?>",
Also at server side if you need only image url then just create image url from $result, store it in variable like $img_path in "master_get_employees" function and then just
echo json_encode(['img_path'=>$img_path]);
And in ajax success just do below
$("#EditImage").attr('src',outputData.img_path);

Jquery, Call is only done one time successfully and after that it stays on the same result

I have a problem concerning my code which should change content in a div onclick "More News articles" as the change will happen only once. I see in Chrome Developer mode that it fires every click a request. What goes wrong?
Output.php
<?php
require_once('../pe13f/SSI.php');
require_once ('../PE13/smf_2_api.php');
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function MakeRequest(id)
{
$.ajax({
url : 'display.php',
data:{"id":id},
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
}
});
}
</script>
<div id="stream" class="bg4 roundedcrop shadow">
<div class="ph25 pv20">
<h1>News</h1>
<input id="streamcnt" name="streamcnt" type="hidden" value="" />
</div>
<div id="streamadd"></div>
<div id="streaminnern">
<?php
$num_recent = 5;
echo $num_recent;
?>
</div>
<div onclick="MakeRequest(<?php echo $num_recent; ?>);" id="streammore">More News articles</div>
</div>
backend php display.php
<?php
$num_recent = $_GET['id']+5;
echo $num_recent;
?>
Greetings Emil
Check the source that is produced by output.php. You'll find there onclick="MakeRequest(5);". Basically - on every click you call MakeRequest(5) which always fires call display.php?id=5 (you probably see that in your dev console).
Try something like this:
<script>
var lastId = 0; // var that stores last fetched ID
function MakeRequest(id)
{
if(!lastId) // if there is no last ID use the one from initial onclick
lastId = id;
$.ajax({
url : 'display.php',
data:{"id":lastId}, // note that we are using the lastId var
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
lastId = data; // save fetched ID in our global var
}
});
}
</script>
The request is always the same. Suppose $num_recent is initially set to 5.
Then as per your code MakeRequest(5) will be executed. And your ajax call updates a div with class streaminnern. So the new id has no impact on the next ajax call. For the ajax request to be sent updated value you may set
$.ajax({
url : 'display.php',
data:{"id":$('#streaminnern').html()},
.................
});

How to mesh codeigniter with ajax

I am trying to implement a ajax plus one button with my site in code igniter. I am very new with Ajax and codeigniter so I'm needing some guidance.
Here is the portion of my controller where I'm starting. Please note, this is inside the method that creates my profile view in which I'm trying to create this.
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->community_model->updateUpVote($voteId);
}else{
$updateRecords = $this->community_model->updateUpVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
// This variable will be accessed from the view
$data['airwave'] = $airwave;
$data['profile_id'] = $profile_id;
$this->load->view('includes/templates/main_page_template', $data);
}
Here is the method in the model:
function updateUpVote($voteId){
$sql = "UPDATE airwaves_comments set thumbsup = thumbsup+1 WHERE thumbsup =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
here is my view:
<div id='thumb_holder'>
<div id='thumb_report'>
<a href='mailto:info#cysticlife.org'>
&#149 report
</a>
</div>
<div class= 'thumb_counter'>
+0
</div>
<div id='thumb_thumb'>
<a class='myButtonLink voteMe' id='1_upvote'<span id="1_upvote_result">+</span>></a>
</div>
</div>
here is the script:
<script>
$(document).ready(function(){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "account/profile/voteMe",
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
</script>
additionally here is what it looks like to give a better idea of what's going on, but I want there to be the number of votes after the plus sign:
To summarize: Essentially I was taking a tutorial on a demo tutorial that is similar, but it was not exactly what I am trying to do. This is basically me taking the code from the tutorial and trying to splice it with my code and meet my specific needs and learning ajax at the same time. I feel like I'm close as it's updating the specified column in my table (incorrectly),however can't get it to visibly function.
I'm not exactly sure what your saying your problem is. But This I do see.
When trying to fetch a view for ajax you have to return the view as data
http://ellislab.com/codeigniter/user-guide/general/views.html (bottom of the page)
Like this
$view = $this->load->view('includes/templates/main_page_template', $data, true);
echo $view;
This will send the rendered view to the browser
Put this code in view file
<input type="hidden" name="siteurl" id="siteurl" value="<?php echo site_url(); ?>">
<input type="hidden" name="baseurl" id="baseurl" value="<?php echo base_url(); ?>">
Then get hidden value in your script
var site_path = $("#siteurl").val();
var base_path = $("#baseurl").val();
$.ajax({
type: "post",
url: site_path+"account/profile/voteMe",....

Ajax Call with Post in PHP

<!doctype html>
<html>
<head>
<title>jQuery Tagit Demo Page (HTML)</title>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
var availableTags = [];
$('#demo2').tagit({tagSource:availableTags});
$('#demo2GetTags').click(function () {
showTags($('#demo2').tagit('tags'))
});
/*
$('li[data-value]').each(function(){
alert($(this).data("value"));
});*/
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
function showTags(tags) {
console.log(tags);
var string = "";
for (var i in tags){
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
}
});
</script>
</head>
<body>
<div id="wrap">
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
<div class="box">
<div class="note">
You can manually specify tags in your markup by adding <em>list items</em> to the unordered list!
</div>
<ul id="demo2" data-name="demo2">
<li data-value="here">here</li>
<li data-value="are">are</li>
<li data-value="some...">some</li>
<!-- notice that this tag is setting a different value :) -->
<li data-value="initial">initial</li>
<li data-value="tags">tags</li>
</ul>
<div class="buttons">
<button id="demo2GetTags" value="Get Tags">Get Tags</button>
<button id="demo2ResetTags" value="Reset Tags">Reset Tags</button>
<button id="view-tags">View Tags on the console </button>
</div>
</div>
</div>
<script>
</script>
</body>
</html>
This code will just transfer the list of items in the dostuff.php but when I try to print_r it on PHP nothing won't come out. why is that?
I am doing an ajax request on this line
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
and the code in PHP
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
This is just a shot in the dark, given the limited information, but it would appear that you're expecting something to happen with the data sent back from the server.. but you literally do nothing with it. On success, you have it display an alert... and nothing else.
Try changing your success entry to the following:
success: function(data) {
$("#wrap").html(data);
}
This will fill the div with the data from the POST request. The reason it shows up as nothing as it is..., you aren't loading the currently executing page with the data needed for the print_r to actually echo anything.
Edit: How to insert values into database;
Database interaction now-a-days is done with either custom wrappers, or the php Data Object, also referred to as PDO, as opposed to the deprecated mysql_* functions.
First, you prepare your database object, similar to how a connection is done in the aforementioned deprecated functions:
$dbh = new PDO("mysql:host=hostname;dbname=database", $username, $password);
Then, you can begin interaction, preparing a query statement..
$stmt = $dbh->prepare("UPDATE table_name SET column1 = :column1 WHERE id = :id");
Binding a parameter in said statement..
$stmt->bindParam(':column1', $column1);
$stmt->bindParam(':id', $id);
$id = $_POST['id'];
And finally executing the query:
try {
$stmt->execute();
}
catch (Exception $e) {
echo $e;
}
PDO auto-escapes any strings bound in the prior statements, making it save from SQL-injection attacks, and it speeds up the process of multiple executions. Take the following example:
foreach ($_POST as $id) {
$stmt->execute();
}
Since the id parameter is already bound to $id, all you have to do is change $id and execute the query.
Where where you expecting the PHP result of print_r to "come out"?
Try changing your AJAX call to this (only the value of success is different):
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: function(data, textStatus, jqXHR){
alert(data);
}
});
With this, the output of your PHP template, which you would normally see if you posted to it the old fashioned way (ie. with a form and a full page reload), will display in an alert.
Hope that helps.
Try to add encodeURI for the jQuery part,
$.ajax({
url: "demo3.php",
type: "POST",
data: { items: encodeURIComponent (list.join("::")) },
success: function(response) {
console.log(response);
}
});
And urldecode for the PHP part:
$lis = $_POST['items'];
$liarray = explode("::", urldecode($lis));
print_r($liarray);
3 things:
Set your AJAX's success to show the echos/prints given in your PHP script
success: function(result)
{
$("#somecontainer").html(result);
}
That way ANYTHING that gets printed in a PHP script otherwise, will be put in i.e.
<div id="somecontainer">
Result of PHPcode here
</div>
Second, instead of
var string = "";
for (var i in tags)
{
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
use push(). This adds the value at the next unoccupied index in the array:
var string = "";
for (var i in tags)
{
list.push(tags[i].value);
}
That way you don't have to pop the last element off.
Third point: put your PHP code in a separate file (and your JavaScript/jQuery as well). Have like:
/root/index.html
/root/script/dostuff.php
/root/script/myscript.js
then let your AJAX call to url: "/script/dostuff.php"

Categories