execute javascript from dom in ajax response - javascript

I have a page which loads it's content from ajax response. The problem is that ajax igonres all my scripts from the head tag in my html page. Is there any way to make those javascript files to execute in my ajax response?
ajax:
$(document).ready(function () {
$(".all").click(function () {
var all = $(this).attr("id");
if (all != '') {
$.ajax({
type: "POST",
url: "php/searchbrowselist.php",
data: "all=" + all,
async: true,
success: function (option) {
var $this = $("#browsemusic")
$this.html(option);
$('#sortable1, #sortable2').sortable({
connectWith: ".connected"
}).disableSelection();
}
});
}
});
});
php:
<?php
include ('dbcon.php');
if (isset($_REQUEST['all']) && $_REQUEST['all'] != '') {
// ===============================Button "ALL"====================================
unset($_REQUEST['kw']);
unset($_REQUEST['genre']);
$query = "select * from music";
$result = mysqli_query($link, $query) or die(mysqli_error());
echo '<ul id="sortable1" class="connected">';
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
echo '</ul>';
}
elseif (isset($_REQUEST['kw']) && $_REQUEST['kw'] != '') {
// ============================= Search for music ================================
$kws = $_REQUEST['kw'];
$kws = mysqli_real_escape_string($link, $kws);
$query = "select * from music where title like '%" . $kws . "%' or artist like '%" . $kws . "%'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
echo '<ul id="sortable1" class="connected">';
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
echo '</ul>';
}
elseif (isset($_REQUEST['genre']) && $_REQUEST['genre'] != '') {
// =====================================Browse By Genre ===========================================
$genre = $_REQUEST['genre'];
$genre = mysqli_real_escape_string($link, $genre);
$gquery = "select music_id from musicgenre where genre_id = '$genre'";
$results = mysqli_query($link, $gquery) or die(mysqli_error($link));
$music = array();
while ($id_result = mysqli_fetch_array($results)) {
$music[] = $id_result['music_id'];
};
echo '<ul id="sortable1" class="connected">';
foreach($music as $song) {
$query = "select * from music where music_id = '$song'";
$result = mysqli_query($link, $query) or die(mysqli_error());;
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
};
echo '</ul>';
}
else {
// ================================ Default =========================================
$query = "select * from music";
$result = mysqli_query($link, $query) or die(mysqli_error());
echo '<ul id="sortable1" class="connected">';
while ($info = mysqli_fetch_array($result)) {
echo '<li><div class="ui360"><button type="button" class="addtoplaylist" >Add</button> ' . $info['artist'] . ' - ' . $info['title'] . ' (' . $info['album'] . ') ' . '</div><hr /></li>';
};
echo '</ul>';
};
?>
html:
<div id="browsemusic">
<?php include ( 'php/searchbrowselist.php'); ?>
</div>
so, the php file gets some values from ajax and loads the results in my div. I need it to also execute my scripts loaded in the head:
<head>
<script src="js/berniecode-animator.js"></script>
<script src="js/soundmanager2.js"></script>
<script src="js/360player.js"></script>
</head>

Related

Adding a filter search button to w2ui grid

For my w2ui grid, I want to have a few search buttons to filter the data is pre-defined ways. (e.g. a "Big West" button to search for rows with "Big West" as the conference.
<button class="w2ui-btn" onclick="var obj = w2ui['grid']; obj.search({ field : 'conference', value : 'Big West', operator : 'contains', type: 'text' });">Big West</button>
When I click this button, the data doesn't change. Ideally, the first click would do the search, and clicking it again would take the search away.
if you use w2ui grid it has wonderful search button , but you need to do customize in the data source file to filter rows I paste a script with
PHP and its work perfect for w2ui grid, and will simplify the whole process, and use it as backend with suitable customize for your work :
$action = $_REQUEST[request];
$action = json_decode($action, true);
$vlimit = $action['limit'];
$voffset = $action['offset'];
$str = "";
$err = "";
$sql = "";
switch ($action['cmd']) {
case 'get':
if (isset($action['search']) && is_array($action['search'])) {
foreach ($action['search'] as $s => $search) {
if ($str != "")
$str .= " " . $action['searchLogic'] . " ";
$field = $search['field'];
switch (strtolower($search['operator'])) {
case 'begins':
$operator = "LIKE";
$value = "'" . $search['value'] . "%'";
break;
case 'ends':
$operator = "LIKE";
$value = "'%" . $search['value'] . "'";
break;
case 'contains':
$operator = "LIKE";
$value = "'%" . $search['value'] . "%'";
break;
case 'is':
$operator = "=";
if (!is_int($search['value']) && !is_float($search['value'])) {
// $field = "LOWER($field)";
// $value = "LOWER('".$search['value']."')";
$value = "'" . $search['value'] . "'";
} else {
$value = "'" . $search['value'] . "'";
}
break;
case 'between':
$operator = "between";
$value = "'" . $search['value'][0] . "' and '" . $search['value'][1] . "'";
break;
case 'more':
$operator = ">";
$value = "'" . $search['value'] . "'";
break;
case 'less':
$operator = "<";
$value = "'" . $search['value'] . "'";
break;
default:
$operator = "=";
$value = "'" . $search['value'] . "'";
}
$str .= $field . " " . $operator . " " . $value;
}
$sql = "select * from [table] "
. " WHERE ~search~ limit $vlimit offset $voffset ";
$sql = str_ireplace("~search~", $str, $sql);
}
else
{
$sql = "select * from [table] ";
}
echo '{"status": "error","message":"' . $sql . '"}';
break;
$stm = $conn->query($sql);
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
$number = $stm->rowCount();
$json = json_encode($result, JSON_UNESCAPED_UNICODE);
header("Content-type: application/json");
echo '{"total" : "' . $number . '","records" : ' . $json . '}';
break;
case 'delete':
$rec_id = $action['selected'][0];
$sql = "DELETE FROM [table] WHERE rec_id = :recid";
$stmt = $accountdb->prepare($sql);
$stmt->bindParam('recid', $rec_id);
try {
$stmt->execute();
echo '{"status" : "success"}';
break;
} catch (Exception $err) {
echo '{"status": "error","message":"' . $err->getMessage() . '"}';
break;
}
case 'save':
/**/
break;
default:
$err = 'default error';
echo '{"status": "error","message":"' . $err . '"}';
break;}

I would like to add a search box by date.to my table using mysql php

I have a table associated with a database mysql, All I want is to add a search box by date.
Although I have tried many methods, but unfortunately all of them did not work for me as I should This is my code:
<form action="" method="GET"">
<input type="date" name="search" class="form-control" placeholder="Start" >
<button type="submit" class="btn btn-primary">Search</button>
</form>
function getRecords($params)
{
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) {
$page = $params['current'];
} else {
$page = 1;
}
$start_from = ($page - 1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if (!empty($params['searchPhrase'])) {
$where .= " WHERE ";
$where .= " ( fullname LIKE '" . $params['searchPhrase'] . "%' ";
$where .= " OR email LIKE '" . $params['searchPhrase'] . "%' ";
$where .= " OR phone LIKE '" . $params['searchPhrase'] . "%' )";
}
if (!empty($params['sort'])) {
$where .= " ORDER By " . key($params['sort']) . ' ' . current($params['sort']) . " ";
}
// getting total number records without any search
$sql = "SELECT * FROM `api` where DATE_FORMAT(created_at, '%Y-%m-%d') = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY)";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if (isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp != -1)
$sqlRec .= " LIMIT " . $start_from . "," . $rp;
}

append php echo in javascript

This is image want to make selct2 function... thanks .append($(<?php echo $property_address1;?>)) this is my javascript code that i want to append.. this is select2 function actually i want multiple select2 onchange fucntion is required...
public function test($id = null)
{
$this->layout->set(
array(
'property_address1' => $this->mdl_quotes->property_address1()
)
);
$this->load->model('mdl_quotes');
$this->layout->buffer('content', 'quotes/test');
$this->layout->render();
}
My controller function
function property_address1()
{
$query = $this->db->query('SELECT host,price,city,property_thumbnail, apartments_type, contactnumber, contactperson,photographlinks,emailid, propertyaddress FROM tbl_contacts')->result();
$output = '<select id="neww" class="property_add_ form-control">';
foreach ($query as $row)
{
//echo $row->location;
$output .= "<option value='". $row->propertyaddress ."'";
$output .= " data-propertyaddress='" . $row->propertyaddress ."'" ;
$output .= " data-host_name='" . $row->host ."'" ;
$output .= " data-apartments_type ='" . $row->apartments_type."'" ;
$output .= " data-city ='" . $row->city."'" ;
$output .= " data-property_thumbnail='" . $row->property_thumbnail."'" ;
$output .= " data-price='" . $row->price."'" ;
$output .= " data-contactperson='" . $row->contactperson ."'" ;
// $output. = $row->pincode.", ".$row->city.", ".$row->location;
$output .= " data-photographlinks='" . $row->photographlinks ."'" ;
$output .= " data-emailid='" . $row->emailid ."'" ;
$output .= " data-contactnumber='". $row->contactnumber . "'>" ;
$output .= $row->host . ' , '.$row->propertyaddress . ' ,'.$row->price. ' ,'.$row->apartments_type. ' , '. $row->contactperson . ' , ' . $row->contactnumber. "</option>";
}
$output .= '</select>';
//var_dump($output);
return $output;
}

Jquery Clone select not working properly

In my code of wordPress I am trying to clone <select> box with its options it works but the problem is all of its option went outside ending select tag </select> I am not confirm whats wrong with it
Preview Image
HTML Output: https://jsfiddle.net/h5voq4nt/
PHP Code
$output .= '<label for="_jwppp-video-url-' . $number . '">';
$output .= '<strong>' . __( 'Media URL', 'jwppp' ) . '</strong>';
$output .= '<a class="question-mark" href="http://www.ilghera.com/support/topic/media-formats-supported/" title="More informations" target="_blank"><img class="question-mark" src="' . plugins_url('jw-player-7-for-wp-premium') . '/images/question-mark.png" /></a></th>';
$output .= '</label> ';
$output .= '<p>';
$output .= '<input type="text" id="_jwppp-video-url-' . $number . '" name="_jwppp-video-url-' . $number . '" style="margin-right:1rem;" placeholder="' . __('Video (YouTube or self-hosted), Audio or Playlist', 'jwppp') . '" ';
$output .= ($video_url != 1) ? 'value="' . esc_attr( $video_url ) . '" ' : 'value="" ';
$output .= 'size="60" />';
$output .= '<input type="text" name="_jwppp-' . $number . '-main-source-label" id ="_jwppp-' . $number . '-main-source-label" class="source-label-' . $number . '" style="margin-right:1rem;';
$output .= '" value="' . $main_source_label . '" placeholder="' . __('Label (HD, 720p, 360p)', 'jwppp') . '" size="30" />';
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
$output .= '<option name="NoAds" value="NoAds"';
$output .= ($ads_client == 'NoAds') ? ' selected="selected"' : '';
$output .= '>No Ads</option>';
$output .= '<option name="AdCode1" value="AdCode1"';
$output .= ($ads_client == 'AdCode1') ? ' selected="selected"' : '';
$output .= '>Ad Code 1</option>';
$output .= '<option name="AdCode2" value="AdCode2"';
$output .= ($ads_client == 'AdCode2') ? ' selected="selected"' : '';
$output .= '>Ad Code 2</option>';
$output .= '<option name="AdCode3" value="AdCode3"';
$output .= ($ads_client == 'AdCode3') ? ' selected="selected"' : '';
$output .= '>Ad Code 3</option></select>';
JQuery Code
<script>
(function($) {
$(document).ready(function() {
var number = <?php echo $number; ?>;
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
//CHANGE PLAYLIST-HOW-TO
var tot = $('.jwppp-input-wrap:visible').length;
if(tot > 1) {
$('.playlist-how-to').show('slow');
var string = [];
$('.order:visible').each(function(i, el) {
string.push($(el).html());
})
$('.playlist-how-to code').html('[jw7-video n="' + string + '"]');
} else {
$('.playlist-how-to').hide();
}
$('.jwppp-more-options-' + number).hide();
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
};
$('#_jwppp-video-url-' + number).on('change',function() {
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
$('.jwppp-more-options-' + number).hide();
} else {
$('.more-options-' + number).show();
}
});
});
})(jQuery);
</script>
In PHP code has
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
this has an end slash (/), please remove it.

Detect difference of form submit via submit button or javascript submit function in PHP

I am using a date picker in PHP, but I experience a small problem.
When selecting a month, I automatically submit the form to change the amount of days:
<script>
function change()
{
document.getElementById("datepickerform").submit();
}
</script>
But, when I press submit, I also want to execute some extra code (querying a database for some info with the selected date.
Is there a way to make a difference when the OK button is pressed or when the form is "submitted" via the function above?
Hereunder is the entire code (not finished, leap year also not included yet) of my datepicker.php:
<script>
function change(){
document.getElementById("datepickerform").submit();
}
</script>
<?php
// Include global Definitions and variables
// http://stackoverflow.com/questions/18179067/select-from-drop-down-menu-and-reload-page
// Form
define("FORM_DAY", "theday");
define("FORM_MONTH", "themonth");
define("FORM_YEAR", "theyear");
// Date related
$days = array(31,28,31,30,31,30,31,31,30,31,30,31);
// Get result from FORM POST
$submittedday = $_POST[FORM_DAY];
$submittedmonth = $_POST[FORM_MONTH];
$submittedyear = $_POST[FORM_YEAR];
if ($submittedday != '')
{
$currentday = $submittedday;
$currentmonth = $submittedmonth;
$currentyear = $submittedyear;
}
else
{
$currentday = intval(date("d"));
$currentmonth = intval(date("m"));
$currentyear = intval(date("Y"));
}
//DEBUG ON
echo $submittedday."/".$submittedmonth."/".$submittedyear."<br>\r\n";
echo $currentday."/".$currentmonth."/".$currentyear."<br>\r\n";
// DEBUG OFF
echo '<form id="datepickerform" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
echo '<table border="1" cellpadding="2">';
echo '<tr><td>';
echo '<table border="0" cellpadding="2">';
echo '<tr><th>Day</th><th>Month</th><th>Year</th></tr>';
echo '<tr>';
echo '<td><select name=' . FORM_DAY . '>';
$i = 1;
for ($i==1; $i<=$days[$currentmonth-1]; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentday)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_MONTH . ' onchange="change()">';
$i = 1;
for ($i==1; $i<=12; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentmonth)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_YEAR . '>';
$i = 2015;
for ($i==2015; $i<=2020; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentyear)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '</tr>';
echo '</table>';
echo '</td></tr>';
echo '<tr><td align="middle">';
echo '<input type="submit" value="OK"></td>';
echo '</td></tr>';
echo '</table>';
echo '</form>';
?>
Could anybody help?
Most JS libraries that preform AJAX calls pass an extra header with the request, typically X_REQUESTED_WITH with a value of XMLHttpRequest. If you were using something like jQuery you can check for this using PHP, or you could just use a hidden field that your JS creates and fills in when it is submitted that way.
function change()
{
var form = document.getElementById('datepickerform'),
el = document.createElement('input');
el.type = 'hidden';
el.name = 'js';
el.value = '1';
form.appendChild(el);
form.submit();
}
And then when handling in PHP, use
if (isset($_POST['js'])) {
// ...
}
You can Keep a hidden field in form and if the form is beig submitted using js then change the value of hidden field before submitting the form.
You could change it so that there is an Ajax call when the month changes, and use a button that can be used to invoke processing prior to submit.
Thanks for the above tips, this solved my problem. Also Change value of input then submit form in javascript helped solving my problem.
<script>
function change(){
document.getElementById("datepickerform").submitform.value = '1';
document.getElementById("datepickerform").submit();
}
</script>
<?php
// Include global Definitions and variables
// https://stackoverflow.com/questions/18179067/select-from-drop-down-menu-and-reload-page
// Form
define("FORM_DAY", "theday");
define("FORM_MONTH", "themonth");
define("FORM_YEAR", "theyear");
// Date related
$days = array(31,28,31,30,31,30,31,31,30,31,30,31);
// Get result from FORM POST
$submitform = $_POST["submitform"];
$submittedday = $_POST[FORM_DAY];
$submittedmonth = $_POST[FORM_MONTH];
$submittedyear = $_POST[FORM_YEAR];
if ($submittedday != '')
{
$currentday = $submittedday;
$currentmonth = $submittedmonth;
$currentyear = $submittedyear;
}
else
{
$currentday = intval(date("d"));
$currentmonth = intval(date("m"));
$currentyear = intval(date("Y"));
}
//DEBUG ON
echo $submitform."<br>\r\n";
echo $submittedday."/".$submittedmonth."/".$submittedyear."<br>\r\n";
echo $currentday."/".$currentmonth."/".$currentyear."<br>\r\n";
if ($submitform == '0')
{
echo 'Button pressed.<br>';
}
else
{
echo 'Javascript executed.<br>';
}
// DEBUG OFF
echo '<form id="datepickerform" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
echo '<table border="1" cellpadding="2">';
echo '<tr><td>';
echo '<table border="0" cellpadding="2">';
echo '<tr><th>Day</th><th>Month</th><th>Year</th></tr>';
echo '<tr>';
echo '<td><select name=' . FORM_DAY . '>';
$i = 1;
for ($i==1; $i<=$days[$currentmonth-1]; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentday)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_MONTH . ' onchange="change()">';
$i = 1;
for ($i==1; $i<=12; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentmonth)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_YEAR . '>';
$i = 2015;
for ($i==2015; $i<=2020; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentyear)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '</tr>';
echo '</table>';
echo '</td></tr>';
echo '<tr><td align="middle">';
echo '<input type="hidden" name="submitform" value="0">';
echo '<input type="submit" value="OK"></td>';
echo '</td></tr>';
echo '</table>';
echo '</form>';
?>

Categories

Resources