How to use a value imported from a database - php

Hey Everyone here is my question .
The code below gets data from my database and displays it both in an input field and a button. I want it to be in such a way that if i click the button it should get the value(which is imported from the db).But the problem i am facing is that all the inputs and buttons have the same ids so it only captures the value of the first button(or so i think). How can i make it in such a way that for every button i click it should have its own separate value.
<?php
$dbcon=mysqli_connect("localhost","root","");
mysqli_select_db($dbcon,"codex");
require('config/server.php');
?>
<table class="table table-striped">
<th>ID</th>
<?php
$view_users_query="select * from users";//select query for viewing
users.
$run=mysqli_query($dbcon,$view_users_query);//here run the sql
query.
while($row=mysqli_fetch_array($run))//while look to fetch the result
and store in a array $row.
{
?>
<!--here showing results in the table -->
<form id="loginForm" method="" action="" novalidate>
<tr>
<div class="panel2">
<main class="content">
<td><input name="hanis" id="hanis" type="text" value="<?php echo
$row['email']?>" autofocus /></td>
<td><button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata()" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button><</td>
</main></div>
</div>
</div>
</form>
<?php } ?>
</tr>
<script type="text/javascript">
function hanisdata() {
var hanis=$("hanis").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>

NOTE :- Don't use same id for elements
You can get values by passing this with onclick function like onclick="hanisdata(this)"
Example
<button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata(this)" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button>
Then you can get specific element in js and then can find parent and search for input field in that like below example.
JS CODE
<script type="text/javascript">
function hanisdata(el) {
var hanis=$(el).parent().find("input").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>

Related

How to run a first instance of ajax jquery when page loads

I have a jquery and ajax that performs a query and shows a table when a button is clicked. The problem is that when the page loads for first time, the query not run and do not shows anything, so the button has to be clicked to start showing the query result.
Is there a way that the query runs when page loads? and then just use the button.
My code is:
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
Thanks in advance!
Just call click() on the element to simulate a click.
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}).click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Buscar" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
You could extract the function you're calling in the click handler and call it within ready.
$(document).ready(function() {
const displayContent = () => {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "genquery.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
}
displayContent();
$("#display").click(displayContent());
});

Ajax multiple input not showing all data?

I'm stuck in multiple input. My code is not showing all data. below is the html I am using:
<form id="matkul" class="form-horizontal" method="POST">
<table class="table table-condensed">
<thead>
<tr>
<th>Matakuliah</th>
<th>Data Lain</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<button id="post" type="submit">Save</button>
<button id="get">Get Data!</button>
below is the code to get the data
<script>
$(document).ready(function() {
$("#get").click(function() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22https%3A%2F%2Funisys.uii.ac.id%2Fuii-ras%2Fmatakuliah.asp%3Fidx%3D1%26session_id%3DxxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511%26no_mhs%3D%22&format=json';
$.getJSON(url,
function(data) {
var id = data.query.results.body.table.tr.td.table.tr[2].td.table.tr;
for (var i = 1; i <= id.length; i++) {
$("<tr> <td> <input name='fmatakuliah' value='"+id[i].td[1].a.content+"'> </td> <td> <input name='fdata' value='" + id[i].td[1].a['href'] + "'> </td> </tr>").appendTo("#matkul tbody");
};
});
});
});
</script>
from the above code output will be
Matakuliah Data Lain
StringOne OtherData
StringTwo OtherData
below is the ajax post code, but when it is already sending the data, the alert does not show all the data
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(){
string = $("form").serialize();
alert(string); // this alert is normal, show all data
$.ajax({
type: "GET",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
});
});
</script>
below is the code on save.php
print_r($_GET);
The latest response is showing like this
Array
(
[fmatakuliah] => Wide Area Network
[fdata] => matakuliahdetail.asp?session_id=xxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511&mk=52323605&kur=2010
)
My question is how to show all data and save it to the database?
It looks like you need to change the AJAX type from GET to POST:
$.ajax({
type: "POST",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});

how to insert value in database using php, jquery and ajax

I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>
$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work
if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>
check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.
On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>

multiple select with checkbox in php

i am making a website in which i am to embbed the functionality of delete using multiple checkbox. here is my code. my problem is
1. Ajax call is not working.
2. how can i make search from database for array .
<?php
if(isset($_POST['Delete']))
{
$array=$_POST['check_box'];
}
?>
<form method="post" id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while($selectnumberarr=mysql_fetch_array($selectnumber))
{
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" id="<?php $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}?>
<input type="submit" name="Delete" id="delete">
</table>
</form>
and below is my ajax and javascript code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
any help would be appriciated
your code is almost correct. You need to remove `onChange="show()" for input checkbox, because if you have jquery then you don't need to put events on HTML elements.
Use jquery 'on' method for compatibility for latest php library.
Replace your jquery code with following jquery code :-
<script>
$(document).ready(function(){
$('#delete').on('click',function()
{
var cat_id = $('.check_box:checked').map(function() {
return this.id;
}).get().join(',');
console.log(cat_id);
$.ajax({
type: "POST",
url: "checkbox.php",
data: { "kw ":cat_id },
datatype:'json',
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
Use ".check_box" instead of "element" in jquery to prevent checks for all checkboxes, instead of desired ones.
Hope it helps.
Why you don't use an array for sending the checkboxes like:
HTML part:
<?php
if (isset($_POST['check_box'])) {
var_dump($_POST['check_box']);
echo "ajax call is working";
}
?>
<form id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while ($selectnumberarr = mysql_fetch_array($selectnumber)) {
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" value="<?php echo $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}
?>
</table>
<input type="button"name="delete" id="delete" value="Delete" />
</form>
JQuery part:
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
So you can easily get an array of the selected checkboxes in php with:
$idsArray = $_POST["check_box"];
this looks now like:
array(
"1", "2","etc.."
);
so this array contains all the ids of the selected checkboxes for delete.

Submit an AJAX FORM from within an AJAX Success

I need to perform another AJAX Form Post from within the first forms success function.
Example, this does 2 AJAX requests.
Search Movie => Pick Movie Wanted => View Specific Movie Details
I am able to load the results into a div <div id="results"></div> just fine but once I select a movie title it isnt performing another AJAX Request, the request goes to the main window.
Here is the initial search page that handles the results.
<script type="text/javascript">
$(document).ready(function(){
$("#searchtitle").submit(function() {
var id = $(this).children('input[name="thetitle"]').attr('value');
$.ajax({
type: "POST",
url: "s.php",
data: $('#searchtitle').serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form id="searchtitle">
<input type="text" name="thetitle" />
<input type="submit" name="submit" class="button expand postfix" value="Search" />
</form>
<div id="status"></div>
s.php which returns results within #results
<?php
if(empty($_POST['thetitle'])) {
?>
<div class="alert-box error">
<div class="alert-error"></div>
Error: Nothing Found
</div>
<?php
}
if(!empty($_POST['thetitle'])) {
$myid = strtoupper($_POST['thetitle']);
$searchReults = $tmdb_V3->searchMovie($myid,'en');
?>
<?php
foreach($searchReults['results'] as $result) {
?>
<form class="sform">
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
<h5><?php echo $result['title']; ?></h5>
<span class="mreleased">Year: <?php echo $result['year']; ?></span>
<input type="submit" class="button" value="Select">
</form>
<?php
}
}
?>
This is the code that will post the results from s.php
<script type="text/javascript">
$(".sform").submit(function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize();
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
}
</script>
I have tried putting this within s.php, within the bottom of the initial search page, in the head of the initial page and no luck, it submits fine just not the sx.php where it should.
In s.php the statement:
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
Should be:
<input type="hidden" name="mid" value="<?php echo $result['id']; ?>" /> //remove extra bracket
In your javascript code in s.php there are some typos:
data: $(this).closest("form").serialize(); // here should be comma not semicolon
After return false you should close the script properly } should be });.
And since you are trying to submit the dynamic content $(".sform").submit(function () will not work. You should use on for dynamic contents. So the correct script would be:
<script type="text/javascript">
$(document).on('submit', '.sform', function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize(),
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
});
</script>
I have checked and verified in my localhost (with a simple setup). It is making both ajax request. Hope this helps!

Categories