I create dynamic html buttons
I want for each button, when i press one of them, then create a ajax call to take value. But my problem is, that I get as many consoles as their number of buttons..
My php code is:
if(isset($_POST['disable_appointment'])) {
$query = "SELECT * FROM appointments";
$result = mysqli_query($db, $query);
$return_arr = array();
while($row = mysqli_fetch_array($result)){
$appointment_date = $row['appointment_date'];
$appointment_time = $row['appointment_time'];
$return_arr[] = array("appointment_time"=> $appointment_time);
}
exit(json_encode($return_arr));
}
My JQuery code is:
$( ".appointment_button" ).each(function(index) {
$.ajax({
url:'../../groomer/groomer_server.php',
type: 'post',
dataType: 'JSON',
data:{
disable_appointment:1
},
success: function(response){
console.log(response);
}
});
});
It's difficult to understand exactly what your question is, but my best guess is that you want to use .click or .on('click', instead of the .each...
$( ".appointment_button" ).click(function(index) {
// Do something when the individual button is clicked...
$.ajax({
...
});
});
At the moment, your code will just run the .ajax against all the found elements
Related
Student.php -here i am getting list of students from a specific Institution in a tag
<?php
if(isset($_POST['c_id'])) { //input field value which contain Institution name
$val=$_POST['c_id'];
$sql="select RegistrationId from `students` where `Institution`='$val' ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$number=$row['RegistrationId'];
?>
<a href='<?php echo "index.php?StudentID=$number"; ?>' target="index" id="link">
//getting student id in the dynamic link
<?php echo "$number";
echo "<br/>";
}}
?>
<div id="index" name="index"> </div>
<div id="Documents"> </div>
<script>
$(document).on('change', 'a#link', function()
{
$.ajax({
url: 'Documents.php',
type: 'get',
success: function(html)
{
$('div#Documents').append(html);
}
});
});
</script>
In index.php - I am Getting students details based on $_GET['StudentID'] ('a' tag value)
<?php
$link=$_GET['StudentID'];
$sql = "select StudentName,Course,Age,Address from `students` where `RegistrationId`="."'".$link."'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['StudentName']."<br/>";
echo $row['Course']."<br/>";
echo $row['Age']."<br/>";
echo $row['Address']."<br/>";
}
?>
In Documents.php -I am getting documents related to the speific student selected in 'a' tag
$link=$_GET['StudentID'];
$qry = "select Image,Marksheet from `documents` where `RegistrationId`='$link'";
$result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$image = $row["Image"];
$image1 = $row["Marksheet"];
echo '<embed src='. $image.'>';
echo ' <object data='. $image1.'width="750" height="600">';
echo ' </object>';
}
On click of student id i am trying to get result from index.php to div()
and result from Documents.php to div()
(i.e)two target for one click in tag
My code only take me to the index.php file result in a new Window
Please Help me to solve this problem
(sorry if my question seems silly i am new to php)
Update:
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
});
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
From your question, it seems that you want to load the two results, one from index.php and one from Documents.php in two separate divs on the same page when the link is clicked.
But you're using a change event on the link, not a click event. The change event is not fired when the link is clicked, so JavaScript does not get executed and the page loads to the URL specified in the href attribute of the link. So first you need to change $(document).on('change') to $(document).on('click').
Furthermore, since you want two results to load - one from index.php and one from Documents.php, you'll need to create two ajax requests, one to index.php and the other for Documents.php. In the success function of each of the ajax requests, you can get the response and put it in the corresponding divs.
In addition to this, you'll also need to prevent the page from loading to the new page specified in href attribute when the link is clicked, otherwise the ajax requests fired on clicking the link will get lost in the page load. Thus, you need to add a e.preventDefault(); to your onclick event handler like this:
$(document).on('click', 'a#link', function(e) {
// Stop new page from loading
e.preventDefault();
// Two ajax requests for index.php and Documents.php
});
Update: You don't need to add two click handlers for each ajax request. Inside one click handler, you can put both the ajax requests.
Also your event handlers won't register if you're adding them before jQuery, or if you're adding them before the DOM has loaded. So move your code to bottom of the HTML page, just before the closing </body> tag.
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link
You can change your <a> tag like below :
..
Then , in your jquery code do below changes :
$(document).on('click', 'a.link', function(e) {
var StudentID = $(this).attr("data-id") //get id
console.log(StudentID)
e.preventDefault();
$.ajax({
url: "details.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
call_next_page(StudentID);//next ajax call
}
});
});
function call_next_page(StudentID) {
$.ajax({
url: "index.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
}
});
}
And then at your backend page use $_POST['StudentID'] to get value of student id instead of $_GET['StudentID'];
i have implemented live search with jquery typeahead library, it is working fine for the case of data being received from database i have the issue on front end
right now the typeahead is working fine for displaying data what i want to do is add url in the href attribute of the li'sbeing generated from the dropdown but i havent still been able to even attach an onclick method with the li's here's my code so far.
HTML
<input autocomplete="off" id="type" placeholder="Search for product / category"/>
JAVASCRIPT
$('#type').typeahead({
source: function (query, result) {
$.ajax({
url: "<?php echo base_url()?>ajax_search/search2",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
PHP CI Model Function
public function search($query){
$keyword = strval($query);
$search_param = "{$keyword}%";
$conn =new mysqli($this->db->hostname, $this->db->username, $this->db->password , $this->db->database);
$countryResult[]=array();
$sql = $conn->prepare("SELECT * FROM category WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["name"];
}
echo json_encode($countryResult);
}
}
this is the html structure that is being generated when typeahead is called
this is what i have tried so far!
$(".typeahead").on( "click", "li", function() {
alert("1");
});
$(".typeahead .dropdown-item").delegate("click", function(){
alert("12");
});
$(".typeahead .dropdown-item").on("click", function(){
alert("123");
});
i copied one of the code from this thread stackoverflow thread but it is still not working for my case i have not idea why it is not working any help?
Since the element you are attaching the click event to will have been added to the DOM dynamically by typehead, you'll want to do so like this:
$('body').on('click', '.typeahead .dropdown-item', function() {
// do something
});
I'm getting undefined in the console when trying to log the "data.billAmount" statement. Why is this happening and how do I fix it?
I tried doing JSON.parse and JSON.stringify but those didn't work. I tried using dataType: 'json' but that didn't work. I'm not sure what else to try. I'm stuck.
PHP:
if (#$_POST['action'] == 'addBill')
{
$billName = $_POST['bill_name'];
$billAmount = intval($_POST['bill_amount']);
$data = array(
'billName' => $billName,
'billAmount' => $billAmount,
);
echo json_encode($data);
$stmt = $db->prepare("INSERT INTO bills (billName, billAmount) VALUES(?,?)");
$stmt->bindParam(1, $billName);
$stmt->bindParam(2, $billAmount);
$stmt->execute();
}
JavaScript:
$(".addBill").on("click", function(e) {
e.preventDefault();
var billAmount = $('.billAmount').val();
var billName = $('.billName').val();
$.ajax({
type: "POST",
url: "index.php",
data: {
billAmount: billAmount,
billName: billName,
action: 'addBill'
},
success: function(data) {
console.log(data.billAmount);
}
});
});
Suggest you to move functionality which is responsible for adding bill into separate file. Then make AJAX call to that file and everything would works well, because if you want a particular value point request to particular file which echo that value for you...
No needs to looking for workaround when that could be done in clear and right way by separating functionality into smaller junks.
In case if you insist to use index.php
after
$stmt->execute();
put one more line
exit();
As Mohamed-Yousef commented on question.
I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
Data1
Data2
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
You are not using the data as mentioned in the other answers:success: function(data){
$("#someid").html(data);
},
You are not cancelling the default click action so your link will be followed:$('a[class="some-class"]').click(function(e){
e.preventDefault();
...;
As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:data: {"id": somedata},;
You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:$data = (int) $_POST['id'];;
As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }
I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>