AJAX request causes change function unbind - php

I want to implement simple functionality to allow users to save their message text as template to be used in the future.
php:
echo '<div id="container">';
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>" . $lang['my_template'] . "</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> ' . $lang['no_saved'] . '</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select></div>";
echo '<input id="send" name="Message" value="send" disabled="disabled" type="submit" />
<input id="temp" name="temp" type="button" value="save as template" />"
<textarea style="width: 99%;" id="textarea" name="TextBox" rows="8" disabled="disabled" type="text" value=""/></textarea>';
javascript:
$("#temp").bind("click", function(){
name=prompt("template name?");
temp_text = $("#textarea").val();
if (name!=null && name!="" && name!="null") {
$.ajax ({
data: {temp_text:temp_text, name:name},
type: 'POST',
url: 'save_template.php',
success: function(response) {
if(response == "1") {
alert("template saved successfully");
} else {
alert(response);
}
}
});
} else {
alert("invalid template name");
}
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
}
});
});
$("select").change(function () {
$("select option:selected").each(function () {
$("#textarea").removeAttr("disabled");
$("#send").removeAttr("disabled");
});
$("#textarea").val($(this).val());
})
.trigger('change');
update_temp.php
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>".$lang['my_template']."</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> '.$lang['no_saved'].'</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select>";
the last ajax request in #temp click function is used to updated the droplist with the newly created template, the problem is that when i click save template; ajax request is performed successfully and droplist is updated, however something wired happen which is that the change function of select is not working anymore! anyone knows where's the problem?

Because ajax will inject new elements to your DOM and those elements don't know about the binding you already defined.
Solution : use jQuery on
Change
$("select").change(function () {
to
$(document).on("change","select", function(){
jQuery on is available from 1.7+ version onwards, if you are using a previous version of jQuery, consider using delegate.

If you are rewriting the select with Ajax you should use .delegate() rather than simply .change, like:
$("someSelector").delegate("select", "change", function() {
// do stuff...
});
where someSelector is an element that contains your select.

Yes, because you have replaced the drop down inside of container, which will unhook all of the events on the drop down. The solution would be to modify the code as below:
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
$("#container select").change(
// your drop down change functionality here //
);
}
});
What this is doing is saying, "After the drop down has been refreshed, also refresh the event."
I hope this helps.

Related

Dropdown Options Based on Previous Selection

I'm hoping this is a simple solution. I am trying to make the first drop down determine the options available for the second. In my database, each flavor for the drink type has "type_id" column set as an integer (i.e. 1,2,3). The integers are meant to reflect the category in which they belong. Is it possible/make sense to base the available options for the second drop down off of the "type_id" that I determined?
I was hoping to accomplish this by using PHP, but I am not opposed to jQuery. I am not very well versed in one over the other. Thank you for your help in advance!
<?php
require "db-connect.php";
$dtype = "SELECT name FROM drinktype";
$typedata = mysqli_query($connection, $dtype);
echo "<select id='slctType'>";
if (mysqli_num_rows($typedata) > 0) {
while($row = mysqli_fetch_assoc($typedata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
$dflavor = "SELECT type_id,name FROM drinkflavor";
$flavordata = mysqli_query($connection, $dflavor);
echo "<select id='slctFlavor' ";
if (mysqli_num_rows($flavordata) > 0) {
while($row = mysqli_fetch_assoc($flavordata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
mysqli_close($connection);
?>
I have sample code for fetching the city according to their state. I have do that code with ajax, jquery and php. I think you have similar type of requirement. Please try below code concept for your requirement.
$(document).on('change','#state',function () {
$('#city').remove();
if($(this).val() != 'none')
{
var state_id = $(this).val();
$.ajax({
type: 'POST',
url: 'page.php',
data: { state_id: state_id },
success: function (city_response) {
if(city_response == '')
{
return false;
}
else
{
var city = '<select name="city" id="city" class="form-control">';
city += '<option value="-----">Please select any City</option>';
$.each(city_response, function (ck, cv) {
city += '<option value="' + cv['city_id'] + '">' + cv['city_name'] + '</option>';
});
city += '</select>';
$("#city_div").css('display', 'block');
$('#cities').append(city);
}
}
})
}
else
{
$("#city_div").css('display', 'none');
}
});

Handling Infinite Scroll Effect Jquery and PHP

Why is the url I created getting 404 instead of loading the page data set to each group I want to show on scroll?
I implemented a infinite scroll effect to paginate my data from a table in my mysql database. Now that I am trying to load the page I am getting a 404 error for the url my query is creating.
example.com/inventory-search.php?limit=15&offset=0&_=1455489762864 404 (Not Found)
I am operating under the impression that the url being formed was specifying the amount of pages and my logic should be keeping track on which page set to be shown. Loading more on scroll.
I did use a tutorial online to get this part of the logic done so I am wondering if I am assuming something that is wrong.
My code looks like this,
DB Config
$db_host = "localhost";
$db_user = "username";
$db_pass = "password";
$db_name = "dbName";
try
{
$DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
?>
Inventory search script,
<?php
require_once get_stylesheet_directory() . '/wuno-search/Dbconfig.php';
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 15;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>
My Jquery
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = false;
var limit = 15;
var offset = 0;
var assetPath = "<?php echo $assetPath; ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
busy = true;
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
define $assetPath
$assetPath = get_stylesheet_directory() . '/wuno-search/inventory-search.php';
?>
There are a number of things that could be factors, but what may be the biggest issue is that you are trying to access result properties that you have not SELECTed. For example, you are trying to get $res['wuno_product'] when you have only selected id in your query. You can always do a print_r($results) or var_dump($results), etc. to see what the query is returning.

Autofill a select after submission via jQuery

I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $_POST['brand_car']);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
echo json_encode($model);
}
jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
}}
});
});
XHTML + PHP
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
getModels(id, 0);
}
function getModels(id, select) {
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="0">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
$('#model_car').val(select);
}}
});
}
This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
Tag this at the end:
<?php
echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>
This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
// I know nothing about your design, but globals are no good
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $brand_car);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
return $model;
}
AJAX.php
if ($_POST['brand_car']) {
echo json_encode(getModels($dbh, $_POST['brand_car']));
}
In your XHTML + PHP
<select id="model_car" name="model_car">
<?php
foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
}
?>
</select>
PS. It looks like your $_SESSION['brand_car'] is never updated.

Load the next 10 record via Ajax Search Box using PHP MySQL and JQUERY

I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . WÄ°thout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;

Insert PHP code in JQuery

Good day every one. I want to insert my php code in my jquery. I want to show my data in database using PHP and I want to put it in a option box. I used var in jquery plus the code of my php but isn't working. Please help me.
Shows the data:
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
while ($result2 = mysql_fetch_assoc($res)){
$name = $result2["name"];
?>
jquery code(dynamic adding text box)
var nitem =0;
var ntotal = 0;
var option = <?php echo" <option value='$name'>$name</option>";} ?>;
function totalItemExpence(){
ntotal = 0;
$('.expense_cost').each(function(){
if($(this).val() != ""){
ntotal += parseFloat($(this).val());
}
});
//$('#total').val(ntotal);
}
$(document).on('change keyup paste', '.expense_cost', function() {
totalItemExpence();
mytotal();
});
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'<select class="expense_name" id="' + nitem '">"'+ option +'"</select>' +
'<input class="expense_desc" placeholder="Expense Description" id="' + nitem + '" required/>' +
'<input class="expense_cost" onkeypress="return isNumber(event)" placeholder="Expense Cost" id="' + nitem + '" required/> ' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem + " .expense_cost").each(function(){
if($(this).val() != ""){
ntotal -= parseFloat($(this).val());
}
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
Try this for while loop :
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
$options = '';
while ($result2 = mysql_fetch_assoc($res)){
$options .= "<option value='{$result2["name"]}'>{$result2["name"]}</option>";
}
?>
And JS part :
...
var option = "<?php echo $options; ?>";
...
This line:
var option = "<?php echo "<option value='$name'>$name</option>"; ?>";
must be in your .php file, because php code won't be executed in a .js file (that's why it's called .php)...
You can wrap that line in a <style> tag in your .php file
Also, don't forget to add these things --> "
And to remove this one --> }

Categories