Making a html alert using ajax, sql and php - javascript

I am trying to make some code where a click of a SQL html button can display a different SQL table as a popup. I have already gotten the variable from the table to pass through using this:
echo "<td><a class='btn-floating btn-large waves-effect waves-light black' onclick='partSearch(".$product.")' value='display'><i class='material-icons'>search</i></a></td>";
The 'part search' code is as follows:
<script type="text/javascript">
function partSearch() {
$.ajax({
url: 'serv.php?id=<?php echo $product ?>',
type: 'GET',
success: function(result){
var obj = jQuery.parseJSON(result)
alert(obj)
}
})
}
</script>
Even though the variable is passed through to 'serv.php', I can't manage to get the sql data to be returned as a popup using alert. All I get is either nothing or [object, Object]. This is the SQL/php code:
<?php
include 'includes/dbh.inc.php';
$id = $_GET['id'];
$result = mysqli_query($conn,"SELECT * FROM pr WHERE product_ID='".$id."'");// test this
$rows = array();
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
?>
Any help is appriciated

<script type="text/javascript">
function partSearch() {
var product_id = "<?php echo $product; ?>";
$.ajax({
url: 'serv.php?id=product_id',
type: 'GET',
success: function(result){
alert(result);
}
})
}
</script>

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;

Onclick link to save multiple data without refresh

With this code I can see empty data saving into my db once I click on the link button. But i need to the GET's data in my database. Any solution to this.
<a href="?id=1&pid=238874" id="day" onclick="this.form.submit();><button type="button" class="label label-danger" >Select</button></a>
<script>
$('#day').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "index.php",
data: $("select.day").serialize(),
});
return false;
});
</script>
For PHP Code to save data
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
// query
$sql = "INSERT INTO hos_patient(reg_id,pid) VALUES ('$a','$b')";
mysqli_query($db, $sql);
?>
Thanks
You specified using POST in your ajax function. But then you try to get the data by GET in your PHP-Script. I'd suggest you just use POST for this.
Alter your PHP-Script to use $_POST instead of $_GET
Try with this :
...
$.ajax({
type: 'post',
url: "index.php?id=1&pid=238874",
data: $("select.day").serialize(),
});
...
Use this in script file and in PHP file use below code
<script>
$('#day').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "index.php?id=1&pid=238874",
data: $("select.day").serialize(),
});
return false;
});
</script>
<?php
$a = $_POST['id'];
$b = $_POST['pid'];
// query
$sql = "INSERT INTO hos_patient(reg_id,pid) VALUES ('$a','$b')";
mysqli_query($db, $sql);
?>
<button type="button" class="label label-danger" >Select</button>
<script>
$(function () {
$('.login_form_1').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'show.php?id=22&pid=33',
data: $('.login_form_1').serialize(),
success: function (data) {
$('div.logerrors').html(data);
}
});
});
});
</script>
For PHP output
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
// query
$sql = "INSERT INTO hos_patient(reg_id,pid) VALUES ('$a','$b')";
mysqli_query($db, $sql);
?>

jquery ajax return values into html form

I need help with returning values from jQuery/AJAX to html form inside index.php
index.php :
<script type="text/javascript">
$(document).ready(function () {
$('#display').ready(function () {
var pageid = '<?php echo $_GET[\'ID\'] ;?>';
var powiat = '<?php echo $row[\'powiat\'] ;?>'
$.ajax({ //create an ajax request to display.php
type: 'GET',
url: 'display.php?ID=' + pageid + '&powiat=' + powiat,
dataType: 'html', //expect html to be returned
success: function (response) {
$('#responsecontainer').html(response);
//alert(response);
}
});
});
});
(...)
echo "<form action=\"save.php\" method=\"GET\">";
echo "<tr><td>IP</td><td><div id=\"responsecontainer\"></td></tr>";
echo "<input type=\"submit\" value=\"Save\">" ;
echo "</table></form>
display.php file contains:
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
echo "<option value=\"".$disp_row_1['ip']."\">".$disp_row_1['ip']</option>";
}
In return I have filed html as expected but when I try submit form filed by jquery/ajax I have error
Notice: Undefined index: ip.
How can I handle with that?
Thanks.
Syntax error in your code when you are printing the option.
Updated code is as below.
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
?>
<option value="<?php echo $disp_row_1['ip'];?>" ><?php echo $disp_row_1['ip'];?></option>
<?php }

'Unexpected token ;' when trying to pass PHP variable in jQuery AJAX request

So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";

Getting the value

I just need some ideas how i get the value from the dropdown
<select id="ins" name="instructor" required>
<?php
//dropdown instructor name
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from instructor";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value=".$row['insA_I'].">".$row['insname']."</option>";
}
?>
</select>
and put the value in this .php file in $_POST['instructor']
<?php
session_start();
require 'connection.php'; //connection
$qry = "select course from instructor where insA_I = '".$_POST['instructor']."'";
$result = mysqli_query($con,$qry);
$_SESSION['row'] = mysqli_fetch_array($result);
$data = $_SESSION['row']['course'];
echo $data;
?>
am still new in ajax
$(document).ready(function() {
$('#ins').change(function(){
$.ajax({
type: "POST",
url: "json_php.php",
data: '',
datatype: 'json',
success: function(result){
alert(result);
}
});
});
});
i already searched this in internet but didn`t get my answer after some modifcation
just need idea, techniques .etc.
Try this ajax code
$(document).ready(function() {
$('#ins').change(function(){
$.ajax({
type: "POST",
url: "json_php.php",
data: {instructor:$(this).val()},
success: function(result){
alert(result);
}
});
});
});
php code for query
$qry = "select course from instructor where insA_I = '".$_POST['instructor']."'";
$result = mysqli_query($con,$qry);
$fetch = mysqli_fetch_array($result);
$_SESSION['row']['course']=$fetch['course'];
$data = $_SESSION['row']['course'];
echo $data;
Since you're using jQuery, use jQuery:
data: { instructor: $('#ins').val() }
Also, please note that your SQL query is wide open to SQL injection. This is a good place to start reading about that.

Categories

Resources