editableSelect() does not fire after ajax method - javascript

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();
}
});

Related

working with ajax, mysql and php

I have to transfer data from one div to another, I am using AJAX to do this.
<script type="text/javascript" src="lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#aq").click(function(){
var name1 = $("#n1").val();
$.ajax({
type: "POST",
url: "risultato.php"
data: "name1=" + name1 ,
dataType: "html",
success: function(msg)
{
$("#risultato1").html(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...");
}
});
});
});
</script>';
<form name="modulo1'.$dationennx['id'].'">
<input type="hidden" name="name1" value="'.$dati['id'].'"
id="n1'.$dationennx['id'].'">
<a href="javascript:rispondithread(\'homeq\');"
id="aq">'.stripslashes($dationennx['oggetto']).'</a><br>
</form>
<script>
function rispondithread(h) {
$("#rispondithreadforum").attr("style", "display:block;");
}
</script>`
I am fetching the data from my table from the 'risultato.php' page, which i want to use to show a textarea on my main page with the fetched data.
<?php
$nome = $_POST['name1'];
$query = "SELECT * FROM login2.podcast
WHERE login2.podcast.id = '$nome'
ORDER BY login2.podcast.data DESC";
$dati = mysql_query($query);
while($ris = mysql_fetch_array($dati) ){
echo'
<textarea class="form-control textareaabc" readonly tabindex="8">'.stripslashes($ris['testo']).'</textarea>';
}
?>
It doesn't work if i try to fetch the data using mysql_query, but it does when i try echoing the post data in the page.
$nome = $_POST['name1'];
echo $nome
This writes the '$nome' variable in my main page.
$nome = $_POST['name1'];
echo'<input type="text" value="'.$nome.'" name="nome">';
i don't understand this. why it doesn't work? what's wrong?
It is highly likely that there is no data for the '$nome' variable in your table
Make sure that you are actually receiving data from the database, does it print out the textarea? If not, you do not have any id in your podcast table table matching the '$nome' variable.
Testing your code
Try checking if you actually get anything back when you print something out in that page, could you possibly be pointing to the wrong page?
other
Overall, i would recommend using PDO or atleast mysqli, MySQL is no longer supported since PHP 7 and deprecated since PHP 5. See: PHP.net documentation about mysql extension
sorry, i forget to include the connection to the database into the file risultato.php :P
thanks to everybody

Partial Update a list with AJAX

I have a list from the database and I want to implement edit functionality where in onclicking a table column, the column becomes editable and on clicking out of column, the value gets updated.
I have used AJAX for this purpose. My code is as under:
Page1.php
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
The column of my table is as under:
<td contenteditable="true" onBlur="saveToDB(this, 'exmid','<?php echo $p0; ?>')"
onClick="showEdit(this);"><?php echo $p3 ?>
Note: $p0 contains the serial no of row from mysql database table and $p3 contains the displayed text.
The code for page2.php is:
<?php
include_once 'includes/db_connect.php';
?>
<?php
$result = mysql_query("UPDATE examlist1 set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE sno=".$_POST["id"]);
?>
Problem:
When I click on the column it becomes editable. Using alert() inside saveToDB() I have checked that the function is called on clicking out of the column and also values of column and id are correct.
Then I tried the alert() function inside $.ajax and it was not called. I am not sure whether ajax is running or not. This is the first time I am trying to use ajax in a php code myself.
Please suggest what is the problem and what is the solution? The code is being implemented on a Linux based server hosted at Godaddy using PHP 5.4.
Also I would like to set the background color on fail. How to write it inside ajax block?
If you are getting the correct values when alerting.In your page2.php. Use mysqli instead of mysql and also use $connection object in mysqli_query().
<?php
include_once 'includes/db_connect.php';
$column=$_POST["column"];
$editval=$_POST["editval"];
$id=$_POST["id"];
$result = mysqli_query($connection,"UPDATE examlist1 SET $column='$editval' WHERE sno=$id");//$connection is database connection variable
if ($result)
{
echo json_encode(array('success'=>true));
}
else
{
echo json_encode(array('success'=>false));
}
?>
Here is Javascript: Try 100% works (Define what you want on if/else statement)
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
var res=eval(data);
//if success then
if (res.success)
{
//write JS code that you want after successful updation
$(editableObj).css("background","#FDFDFD"); //<- according to problem
}
//if fails then
else
{
//write JS code that you want after unsuccess
}
}
});
}
</script>

Ajax with PHP same page not working

I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work

accordion won't work with new content loaded

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

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

Categories