I have tried to get this to work for a while now.
When I load new Ajax content into my accordion, then the new content won't work. The preloaded content works just fine, both before and after.
I have added my code here
I know you can't run the script with ajax, since my config and mysql runs local.
Here is my "update-data.php":
<?php
include('../../includes/config.inc.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
$query = "INSERT INTO messages(msg,name) VALUES ('$content','$name')";
mysqli_query($sqlCon, $query);
//mysqli_query("insert into messages(msg) values ('$content')");
$sql_in= mysqli_query($sqlCon, "SELECT msg,msg_id,name FROM messages order by msg_id desc");
$r=mysqli_fetch_array($sql_in);
$msg=$r['msg'];
$name=$r['name'];
$msg_id=$r['msg_id'];
}
?>
<div class="accordionButton"><?php echo $msg_id; ?>:<?php echo $name; ?></div>
<div class="accordionContent" style="display: block;"><?php echo $msg; ?></div>
Thanks for your help
Here are the ajax call:
<script type="text/javascript">
$(function() {
$(".comment_button").click(function()
{
var element = $(this);
var boxval = $("#content").val();
var bval = $("#name").val();
var dataString = {content:boxval,name:bval};
if(boxval=='')
{
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "<?php echo $total_path.'/update_data.php'; ?>",
data: dataString,
cache: false,
success: function(html){
$("div#wrapper_ac").prepend(html);
$("div#wrapper_ac .accordionButton:first").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('name').value='';
$("#flash").hide();
}
});
}
return false;
});
</script>
You php is fine, just clean your inputs please and look into PDO
You can read about cleaning inputs here and PDO here
In your js I think your problem is your on statement
$('.accordionButton').on('click', function() {
// DO stuff
});
I think it's just not bubbling up the DOM far enough to capture new data, it's adding he click event onto all accordion buttons and listening for them.
Change it to this
$('#wrapper_ac').on('click', '.accordionButton', function() {
// DO stuff
});
This places the listener on #wrapper_ac so any click events that happen underneath will be caught.
Hope this helps
Edit: For more info on PDO check this site http://www.phptherightway.com/#databases
Related
I have an ajax method that runs as soon as the page is loaded without listening to any event. The ajax fetches student ID from the database and shows the student ID in a select box. I want the select box to be editable (http://indrimuska.github.io/jquery-editable-select/). The function $('#studentID').editableSelect(); runs completely fine when the options are hardcoded in the select tag. However, no data is shown in the selectbox when $('#studentID').editableSelect(); is called and the data is fetched from the database.
Here is the code that is written in the JavaScript file
$('#studentID').editableSelect();
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
}
});
#studentID definition
<label for="studentID">ID</label>
<select id = "studentID" class="form-control">
</select>
php code
<?php
$connection = new mysqli ("127.0.0.1", "root", "", "test");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$query = "SELECT `SID` FROM `student` ORDER BY `SID` ";
$result1= mysqli_query($connection, $query);
while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;
$connection->close();
?>
Any help will be appreciated.
Move the editableSelect into the ajax.success method. The problem is that you are initializeing an empty select element, and then inserting it the options with the asynchronous ajax method. The success will forever happen after the data will successfully loaded, and then you can initialize the select with any framework/library, including editableSelect that you want to.
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
let student_el = $('#studentID');
student_el.html(html);
student_el.editableSelect();
}
});
EDIT:
you might not included the library in the right way, so for any case, here is the two ways to include it:
Inside the head tag
<head>
<!--Include jQuery + you libraries...-->
<script src="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet" />
</head>
Inside the ajax call
$.ajax({
type: 'POST',
url: './public/api/studentID.php',
success: function(html){
let student_el = $('#studentID');
student_el.html(html);
$.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js")
.then(() => {
student_el.editableSelect(); // Call this function after the script have been successfully loaded.
});
//student_el.editableSelect();
}
});
Why don't you try calling editableSelect on your callback
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
$('#studentID').editableSelect();
}
});
I have been at this for few hours now and need some help. I am a little new to jquery - it seems straightforward enough, but I can't get this to work. If I submit the data through a form straight to the php page, it works perfectly, but I can't get the ajax to execute. It is pretty simple with just one variable to send for marking an item for review. Any help is appreciated.
<input type="hidden" id="flag_item" name="flag_item" value="<?php echo $row[0]; ?>" />
<input type="button" class="grn_button2" id="report_btn" name="report_btn" onclick="MM_changeProp('flag1','','display','none','SPAN'), MM_changeProp('flag2','','display','inline','SPAN')" value=" Report Item "/>
the jquery code
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click','#report_btn',function(e) {
var data = $("#flag_item").val();
$.ajax({
data: data,
type: "POST",
url: "flag.php",
success: function(data) {
alert("Item has been reported");
}
});
});
});
</script>
and the php
$flag_item = mysqli_real_escape_string($dbgo, $_POST["flag_item"]);
$query = "SELECT flag FROM listings WHERE item_num = '$flag_item'";
$result = mysqli_query($dbconnect, $query);
if(!$result){
die('Invalid query: ' . mysql_error());
}
$row = mysqli_fetch_row($result);
$new_row = $row[0] + 1;
You missed param name here:
var data = $("#flag_item").val();
Try this:
var data = {"flag_item":$("#flag_item").val()};
I got it working now. I ditched the jquery I was using and started over. This jquery code is working.
$('#flag_form').submit(function(){
return false;
});
$('#flag_form').click(function(){
$.post(
$('#flag_form').attr('action'),
$('#flag_form :input').serializeArray(),
function(result){
alert("Item has been reported");
}
);
});
I also added the form tag and the action to input fields. Thank you for trying to help, I appreciate it.
I want to make my Bootstrap Modal appear only when there is an AJAX response. Otherwise, I want this Bootstrap Modal to be hidden.
I have done the below. However, it does not work properly. The Modal keeps showing even if there is no response.
JavaScript:
<script>
//$(dialog).close();
$(".dialog").parent().hide();
// execute alerts ajax function every 1 second
setInterval(alerts, 10000);
function alerts(){// define alerts function
$.ajax({ //create an ajax request to alerts.php
type: "GET",
url: "alerts.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#myModal").modal();
$("#modalbodyscreen").html(response);
$.playSound('http://alixali.com/taxiapp/taxiappbeep');
}
});
}
// close and delete modals every 10 seconds
setTimeout(function(){
//$(dialog).close();
$(".dialog").parent().hide();
}, 10000);
</script>
alerts.php
<pre>
ini_set('display_errors', 'On');
session_start();
$driver_id = $_SESSION['userId'];
include "header.php";
$result = mysql_query("SELECT * FROM alerts WHERE driver_id = '$driver_id'");
$num = mysql_num_rows($result);
if ($num != 0) {
while($data = mysql_fetch_row($result))
{
echo "<h5>Contact No:</h5><br>";
echo $data[1]."<br>";
echo "<h5>Address:</h5><br>";
echo "https://www.google.com/maps/preview/#".$data[3].",".$data[2].",16z"."<br>";
echo "<h5>Distance (km):</h5><br>";
echo $data[5];
$_SESSION['distance'] = $data[5];
}
$delete_result = mysql_query("DELETE FROM alerts WHERE driver_id = '$driver_id'");
}
</pre>
Please advise and get me with your recommendations/solutions as soon as possible.
You can see this app on:
http://www.alixali.com/taxiapp/
Driver login:
username 1111
password 1111
Passenger login:
username ali
password 12345678
Regards,
Alixali
change $("#myModal").modal(); to $("#myModal").modal("show");
and to hide the modals use $(".myModals").modal("hide");
here's a link to the bootstrap API documentation on modals
try this
success: function(response){
if(response != '')
{
$("#myModal").modal('show');
$("#modalbodyscreen").html(response);
$.playSound('http://alixali.com/taxiapp/taxiappbeep');
}
}`
I'm currently into developing simple 'one score' votting system and I'm facing the problem: though php script workd fine I cant get AJAX updating the answer div without reloading page. I've tried different methods, some do nothing, other reload page, for example, I've tried adding (return: false) after AJAX or PreventDefault in it. Here is html and php index page:
<body>
<div align="center">
<h3>Voting with jQuery, Ajax and PHP</h3>
<?php
include('config.php');
$sql=mysqli_query($bd, "SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$total_score=$row['total_score'];
?>
<div id="main">
<div class="box1">
<img class='image'src="img/thumbsup.png">
<span class='this'><?php echo $total_score; ?></span><div class='tr'></div>
<img class='image' src="img/icon-down.png"></div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php
}
?>
</div>
</body>
And here is my working up_vote.php (down_vote.php is almost same, so I wont add it)
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysqli_query($bd,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysqli_num_rows($ip_sql);
$sql = "update Messages set total_score=total_score+1 where mes_id='$id'";
mysqli_query($bd, $sql);
$sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";
mysqli_query($bd, $sql_in);
$count=mysqli_num_rows($ip_sql);
}
?>
And finally, the complete JQUERY - AJAX script (this's my problem - need to show the results in (div class = 'this') without refreshing the page):
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success:function(data){
$(".this").append(data);
},
complete: function() {alert('complete');};
});} else
{
$(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle" style="height: 10px;width:10px;">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false
}).done(function ( data ) {
$('.this').append(data);
});
}
return false;
});
});
I have spent whole my day and I know the solution is obvious, Im just really new in this all and so I would appreciate any helpful response. Thanks in advance.
I have added this code to up_vote.php at the buttom:
$result=mysqli_query($bd, "select total_score from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result);
$up_value=$row['total_score'];
echo $up_value;
Thanks to all of you guyz!!! It works now! The problem was that php script didnt return anything!!! As I though - obviouse))) THANKS!
HAve NEW PROBLEM NOW - WHEN I CLICK ON ICONS IT UPDATES ALL OF THEM!! IN EVERY DIV! I VOTE FOR ONE THING - AND IT ADDS VOTES FOR EACH ONE!! whats wrong with that?
I have a question which is probably easy to solve but due to my lack of javascripting skills I find it rather hard.
I am using a function to auto-complete database info in a search bar. For that I'm using this javascript function:
<script type="text/javascript">
$(function(){
$(".search").keyup(function(){
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!=''){
$.ajax({
type: "POST",
url: "http://marceldepender.nl:2222/CMD_FILE_MANAGER/domains/marceldepender.nl/public_html/Recap/wp-content/themes/radiate/templates/search.php",
data: dataString,
cache: false,
success: function(html){
$("#divResult").html(html).show();
}
});
}
return false;
});
jQuery("#divResult").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
$('#inputSearch').click(function(){
jQuery("#divResult").fadeIn();
});
});
</script>
As you can see in the first part of the function, there is a value called url: this url includes (at least I think that is what it does) a certain php page when the if statement is true. This php page (search.php) does a query and gives output related to the search terms.
Though for some reason, the javascript function doesn't go to that search.php page. I have done / tested several things:
IN the original document the url was just plan: url: "search.php", - I changed it to the entire link where the search.php is on though since the previous url didn't work (the new one doesn't either though).
I changed the search.php to some easy echo code just so I know the page is being included / redirected to.
For some reason (and I think it is because the search.php isn't being included) the code doesn't work.. The page where the javascript function is on, is located on a directadmin files on the net, the search.php is also located in this same map.
So the question is: why isn't my search.php included and how can I fix this?
For some better understanding of my search.php code I inserted the original code below:
<?php
include('includes/db.php');
if($_POST){
$q=$_POST['searchword'];
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res)){
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="display_box" align="left">
<img src="<?php echo $media; ?>" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $country; ?></span></div>
<?php
}
}
?>