How to create links with GET parameter - javascript

I am trying to create custom links for all the individuals in a page. Each individual has a separate id. How can I create the links using GET parameter. The data is being pulled using JSON
Javascript
$.getInfo = function() {
var selected_reference_id = $.cookie("selected_reference_id");
$.ajax({
url: "assets/functions/editor.php",
type: "post",
data: {selected_reference_id: selected_reference_id},
success: function(data) {
var json_data = JSON.parse(data);
console.log(json_data);
console.log(json_data[0].profile_image_url);
$("#editor_name").html(json_data[0].name);
$("#profile_description").html(json_data[0].profile_description);
$("#profile_picture").html('<img alt="" id="profile_picture" src="' + json_data[0].profile_image_url + '" class="member-img">');
$("#main_video").html('<video id="MY_VIDEO_0" class="video-js vjs-default-skin" controls \n\
preload="none" width="640" height="264" poster="' + json_data[0].thumbnail_url + '"\n\
data-setup="{}">\n\
<source src="' + json_data[0].video_url + '" type="video/mp4">\n\
<p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video</p>\n\
</video>');
$("#editor_tags").append(json_data[0].is_sports);
$("#editor_tags").append(json_data[0].is_weddings);
$("#editor_tags").append(json_data[0].is_travel);
$("#editor_tags").append(json_data[0].is_everyday_moments);
$("#editor_tags").append(json_data[0].is_special_occasions);
$("#editor_tags").append(json_data[0].is_motion_graphics);
$("#editor_tags").append(json_data[0].is_promo);
$("#editor_tags").append(json_data[0].is_tutorials);
$("#editor_tags").append(json_data[0].is_crowdfunding);
$("#editor_tags").append(json_data[0].is_collage);
$.each(json_data, function(index) {
//console.log(data[index].email);
var addRow = '<li class="mix all" style="margin-bottom: 6px;"><video id="MY_VIDEO_' + index + '" class="video-js vjs-default-skin" controls \n\
preload="none" width="100%" height="264" poster="' + json_data[index].thumbnail_url + '"\n\
data-setup="{}">\n\
<source src="' + json_data[index].video_url + '" type="video/mp4">\n\
<p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video</p>\n\
</video></li>';
// var addRow = '<li class="mix webdesign">\n\
// <!-- <img src="themes/demo/assets/dream/images/work/thumbnail-01.jpg" alt=""/> -->\n\
// <video style="width: 100%; height: 100%" controls>\n\
// <source src="' + json_data[index].video_url + '" type="video/mp4">\n\
// <source src="' + json_data[index].video_url + '" type="video/ogg">\n\
// </video>\n\
// </li>';
if (index !== 0) {
$("#work-preview").append(addRow);
}
});
// $("#main_video").html('<video style="width: 40%; height: 40%" class="video" controls>\n\
// <source src="'+json_data[0].video_url+'" type="video/mp4">\n\
// <source src="'+json_data[0].video_url+'" type="video/ogg">\n\
// </video>');
// if (json_reserve.alreadyReserved === 0) {
// $("#upload_row").show();
// $.timer(json_question[0].timeleft);
// } else {
// $.dialogAlreadyReserved(); //a function I defined to pop up a dialog
// $.throbberHide();
// }
}
});
};
$.getInfo();
PHP
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
include_once($root . '/assets/functions/db_dream.php');
$response = array();
$selected_reference_id = $_REQUEST['selected_reference_id'];
$DB = new DB();
$db = $DB->connect();
$stmt1 = $db->prepare("SELECT * FROM editors LEFT JOIN profile_videos pv ON editor_email = email WHERE reference_id = :reference_id ORDER BY pv.priority");
$stmt1->bindValue(':reference_id', $selected_reference_id, PDO::PARAM_INT);
$stmt1->execute();
$results = $stmt1->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
$details = array();
$details["reference_id"] = $row['reference_id'];
$details["email"] = $row['email'];
$details["name"] = $row['name'];
$details["profile_description"] = $row['profile_description'];
$details["profile_image_url"] = $row['profile_image_url'];
$details["video_url"] = $row['video_url'];
$details["thumbnail_url"] = $row['thumbnail_url'];
$details["editor_email"] = $row['editor_email'];
$details["priority"] = $row['priority'];
if($row['is_sports']){
$details["is_sports"] = "<a class='button_custom small' style='margin-right: 5px' >EXTREME SPORTS</a>";
}else{
$details["is_sports"] = "";
}
if($row['is_weddings']){
$details["is_weddings"] = "<a class='button_custom small' style='margin-right: 5px'>WEDDINGS</a>";
}else{
$details["is_weddings"] = "";
}
if($row['is_travel']){
$details["is_travel"] = "<a class='button_custom small' style='margin-right: 5px'>TRAVEL</a>";
}else{
$details["is_travel"] = "";
}
if($row['is_everyday_moments']){
$details["is_everyday_moments"] = "<a class='button_custom small' style='margin-right: 5px'>EVERYDAY MOMENTS</a>";
}else{
$details["is_everyday_moments"] = "";
}
if($row['is_special_occasions']){
$details["is_special_occasions"] = "<a class='button_custom small' style='margin-right: 5px'>SPECIAL OCCASIONS</a>";
}else{
$details["is_special_occasions"] = "";
}
if($row['is_motion_graphics']){
$details["is_motion_graphics"] = "<a class='button_custom small' style='margin-right: 5px'>MOTION GRAPHICS</a>";
}else{
$details["is_motion_graphics"] = "";
}
if($row['is_promo']){
$details["is_promo"] = "<a class='button_custom small' style='margin-right: 5px'>PROMOS</a>";
}else{
$details["is_promo"] = "";
}
if($row['is_tutorials']){
$details["is_tutorials"] = "<a class='button_custom small' style='margin-right: 5px'>TUTORIALS</a>";
}else{
$details["is_tutorials"] = "";
}
if($row['is_crowdfunding']){
$details["is_crowdfunding"] = "<a class='button_custom small' style='margin-right: 5px'>CROWDFUNDING</a>";
}else{
$details["is_crowdfunding"] = "";
}
if($row['is_collage']){
$details["is_collage"] = "<a class='button_custom small' style='margin-right: 5px'>PHOTO COLLAGE</a>";
}else{
$details["is_collage"] = "";
}
array_push($response, $details);
}
echo json_encode($response);

Related

Text message won't clear even after sending the text in chat

I'm working on a chat box and it's working fine but when we enter the text message and sent it after the message is sent it won't clear automatically. It will remain there even after posting the text, we need to clear it manually.
I have tried to change some code but couldn't solve the issue.
Code which I'm using in this.
<div class="row">
<div class="pull-left">
<h3><?php echo sprintf($this->lang->line("conv_with"), $user["username"]); ?></h3>
</div>
</div>
<div class="row">
<div class="main_container clearfix">
<div class="ibox-content-no-bg">
<div class="chat-discussion">
<?php
$last_conv = $last_conv->result_array();
$last_conv = array_reverse($last_conv);
foreach($last_conv as $message):
$activity_thumb = $message["thumb_url"];
if($message["thumb_url"] == "" || $message["photostatus"] == 0) {
$activity_thumb = base_url() . "images/avatar.png";
}
?>
<?php
if($message["user_id"] == $this->session->userdata("user_id"))
$align_message = "left";
else
$align_message = "right";
?>
<div class="chat-message clearfix <?php echo $align_message; ?>" data-id="<?php echo $message["id"]; ?>">
<?php
if($message["gender"] == 0) {
$gender_user_color = "male_color";
} else {
$gender_user_color = "female_color";
}
?>
<a class="nailthumb-msg-container" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><img width="62" alt="" src="<?php echo $activity_thumb; ?>" class="message-avatar"></a>
<div class="message">
<a class="message-author <?php echo $gender_user_color; ?>" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><?php echo $message["username"] ?></a>
<span class="message-date text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
<span class="message-content">
<?php echo $message["content"]; ?>
</span>
<span class="message-date-mob text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
</div>
</div>
<?php
endforeach;
?>
</div>
<div class="chat-message-form">
<div class="form-group">
<p class="lead emoji-picker-container">
<textarea id="pm-write" class="form-control message-input pm-write-answer-textarea" placeholder="<?php echo $this->lang->line("enter_message_here_placeholder"); ?>" name="message" data-emojiable="true"></textarea>
</p>
</div>
<div class="btn-reply-placeholder">
<a class="btn btn-primary btn-send-reply" href="#" data-user-id="<?php echo $user["uid"]; ?>" data-conv-id="<?php echo $current_conv->id; ?>"><?php echo $this->lang->line("send_reply_btn"); ?></a>
</div>
</div>
</div>
</div>
</div>
AJAX
$(document).ready(function() {
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
window.setInterval(function(){
var last_message_id = $(".chat-message:last").attr("data-id");
// Live refresh
$.ajax({
url: base_url + "pm/refresh_conv",
type: 'POST',
data: {conv_id : conv_id, last_message_id: last_message_id},
success: function(data) {
$.each(data.last_messages, function(i, item) {
var message = item;
var avatar = "";
if(message.thumb_url == null || message.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + message.thumb_url;
}
if(message.gender == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
if(message.user_id == user_id) {
var msg_dir = "left";
} else {
var msg_dir = "right";
}
var block_msg = '<div class="chat-message ' + msg_dir + '" data-id="' + message.mid + '">';
block_msg += '<a class="nailthumb-msg-container" href="' + base_url + 'user/profile/' + message.user_id + '"><img width="62" alt="" src="' + avatar + '" class="message-avatar" /></a>';
block_msg += '<div class="message">';
block_msg += '<a class="message-author ' + gender_user_color + '" href="' + base_url + 'user/profile/' + message.user_id + '">' + message.username + '</a>';
block_msg += '<span class="message-date text-muted pm-date" title="' + message.date + 'Z"></span>';
block_msg += '<span class="message-content">';
block_msg += message.content;
block_msg += '</span>';
block_msg += '</div>';
block_msg += '</div>';
$(".chat-message").last().after(block_msg);
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
});
}
});
}, 2000);
$(".btn-send-reply").click(function(e) {
e.preventDefault();
$(':input[name="pmwrite"]').val(null);
var conv_id = $(this).attr("data-conv-id");
var user_id = $(this).attr("data-user-id");
var content = $(".emoji-wysiwyg-editor").html();
$(this).html('<i class="fa fa-circle-o-notch fa-spin"></i>');
$(this).addClass("disabled");
var that = $(this);
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
if(res == 999) {
alert(not_logged_in_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 998) {
alert(write_something_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 500) {
alert(cant_demo_mode_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 997) {
alert(conv_not_exist_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 996) {
alert(user_blocked_you_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else {
var avatar = "";
if(data.user.thumb_url == null || data.user.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + data.user.thumb_url;
}
$(".pm-write-answer-textarea").val("");
if(data.user["gender"] == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
that.html(send_reply_str);
that.removeClass("disabled");
$(".chat-discussion").scrollTop(100000);
}
}
});
});
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
});
I expect the textarea to be cleared after someone send t the message but actual is the text will remain in textarea even after the message is sent.
I assume that this $(".emoji-wysiwyg-editor") is your element for your content. since this is the one you called in
var content = $(".emoji-wysiwyg-editor").html();
Try clearing this element after success by using this code since you're using a jquery here.
$(".emoji-wysiwyg-editor").html('');
Just add this line at the start of your AJAX success() function
$('#pm-write').empty();
Using pure Javascript
document.getElementById('pm-write').innerHTML = "";
It would look like this
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
$('#pm-write').empty(); //Clean the textarea
//Other code
}
});
Using javascript, you can easily achieve this by setting an event listener on the text-area like this
document.addEventListener("DOMContentLoaded", function() {
var submitBtn = document.getElementsByClassName("btn-send-reply")[0];
submitBtn.addEventListener("click", function(){
document.getElementsByName("message")[0].value = "";
});
});
or in jQuery
$(document).ready(function(){
$('.btn-send-reply').click(function(){
$( "input[name*='message']" ).val("");
})
})

Executing a Php Mysql function from Onclick NO POST

I have a php Mysql interaction and i wish to trigger the Mysql Search through an ONCLICK event.
iv thought about using a JS function or JQ and parsing the ID of selected through JS function but then im unsure as how i would re-execute the php to re-search the database with the new JS Veriable...
The code below is accurate and is what im working with...
How would i re execute the php with the new ID.. Much appreciated..
<div class="contentheader">
<header> Welcome Please Choose a Catagory</strong></header>
</div>
<div id='smallpagination' class='smallpagination'>
<?php
//search according to chosen search critera NOT LIMITED//
include("conect.php");
$startit = 0;
$startfrom = rand(0, 20);
$displayto = $startfrom + 10;
$search = "";
$startedfrom = $startfrom;
$sql = "SELECT * FROM testdata
WHERE title LIKE '%%$search%%'
LIMIT $startfrom , $displayto";
// check how many results //
$result = $conn->query($sql);
$row_cnt = $result->num_rows;
while ($row = mysqli_fetch_assoc($result)) {
$videos = $row['videos'];
$v_id = $row['id']; //<!---important is Video ID and needed for video click selection---->
$id = $row['id'];
$Name = $row['Name'];
if (empty($Name)) {
$Name = 'Annonymous';
}
$image = $row['image'];
$info = $row['info'];
if (empty($info)) {
$info = 'Contact Listee (if Provided) , No Item Information Given';
}
$phone = $row['phone'];
if (empty($phone)) {
$phone = 'See Listing';
}
$title = $row['title'];
$locate = $row['locate'];
if (empty($locate)) {
$locate = 'Not Provided';
}
$postcoded = $row['postcode'];
if (empty($postcoded)) {
$postcoded = '???';
}
$price = $row['price'];
if (empty($price)) {
$price = '?';
}
if ($price == '0') {
$price = '?';
}
$date = $row['stamp'];
if (empty($date)) {
$date = '';
}
if ($startit < 1) {
$gotid = $row['id'];
$startit = $startit + 1;
};
$vidd = $row['id'] - 0.01;
$pidd = $row['id'] - 0.02;
$type = $row['type'];
$showinglocate = $row['id'] - 0.03;
$showingphone = $row['id'] - 0.04;
$displaytype = "minlist";
//Thumbnails sized listings
if ($displaytype == "minlist") {
echo "
<div class='floaterminhomepage'>
<div class='innerfloaterminhomepage' >";
if (!empty($videos)) {
echo "
<video id='$v_id' style='position:absolute; top:0%; left:0%; width:100%; height:100%; background-size: cover; object-fit:fill;' preload='metadata' onclick='showdata({$v_id});'>
<source src='vid/{$row['videos']}.mp4' type='video/mp4'>
<source src='vid/{$row['videos']}.mp4' type='video/ogg'>
<source src='vid/{$row['videos']}.mp4' type='video/webm'>
</video >";
}
if (empty($videos)) {
echo "<img id='$vidd' src='pageimages/blank.png' style='position:absolute; top:0%; left:0%; width:100%; height:100%;'>";
}
echo "
</div>
</div>
";
}
};
?>
</div> <!---smallpagination--->
<script>
------ > SHOWDATA
RETRIEVE
ID
SCRIPT
HERE < -----
</script>
Then re-execute the folling php
----HOW WOULD I GO ABOUT THIS RE_EXECUTION.
<?php
$displayto = $startfrom;
$sql = "SELECT * FROM testdata
WHERE id={$gotid};
";
// check how many results //
$result = $conn->query($sql);
$row_cnt = $result->num_rows;
while ($row = mysqli_fetch_assoc($result)) {
$videos = $row['videos'];
$v_id = $row['id']; //<!---important is Video ID and needed for video click selection---->
$Name = $row['Name'];
if (empty($Name)) {
$Name = 'Annonymous';
}
$image = $row['image'];
$info = $row['info'];
if (empty($info)) {
$info = 'Contact Listee (if Provided) , No Item Information Given';
}
$phone = $row['phone'];
if (empty($phone)) {
$phone = 'See Listing';
}
$title = $row['title'];
$locate = $row['locate'];
if (empty($locate)) {
$locate = 'Not Provided';
}
$postcoded = $row['postcode'];
if (empty($postcoded)) {
$postcoded = '???';
}
$price = $row['price'];
if (empty($price)) {
$price = '?';
}
if ($price == '0') {
$price = '?';
}
$date = $row['stamp'];
if (empty($date)) {
$date = '';
}
$type = $row['type'];
};
echo "<div id='smallpagdata' class='smallpagdata'>
ID={$v_id}<br>
NAME={$Name}<br>
TITLE={$title}<br>
INFO={$info}<br>
PHONE={$phone}<br>
LOCATION={$locate}<br>
PRICE={$price}<br>
Listed={$date}<br>
</div>";
?>
Does "NO POST" mean "no GET" as well? Otherwise you could put your retrieval script in a different file and call that with jQuery.get or XMLHttpRequest.

HTML5 Video pause with Javascript when starting to play another video

I was just wondering is there any option to create a Javascript that pauses a video that is currently playing when You click play on another video.
I've got about 30-40 HTML5 video tags on one page.
Code that I'm using to put videos on page:
function pobierz_klipy($typ) {
$result = mysql_query("SELECT * FROM Klipy WHERE typ = $typ ORDER BY id")
or die("Zapytanie niepoprawne");
//ilosc zwroconych wierszy
$num_rows = mysql_num_rows($result);
$i = 0;
while ($i < $num_rows) {
$id = mysql_result($result, $i, "id");
$nazwa = mysql_result($result, $i, "nazwa");
$nazwa_rob = mysql_result($result, $i, "nazwa_rob");
$typ = mysql_result($result, $i, "typ");
$sprawdzian_hq = $sciezka = "../video/data/video/" . $nazwa_rob . "_fb.mp4";
if (file_exists($sprawdzian_hq)) {
$sciezka = "../video/data/video/" . $nazwa_rob . "_fb.mp4";
} else {
$sciezka = "../video/data/video/" . $nazwa_rob . ".mp4";
}
if (file_exists($sprawdzian_hq)) {
$poster = "../video/data/thumbnails/" . $nazwa_rob . "_fb.mp4.jpg";
} else {
$poster = "../video/data/thumbnails/" . $nazwa_rob . ".mp4.jpg";
}
if (file_exists($sprawdzian_hq)) {
$hq = "../video/data/video/" . $nazwa_rob . ".mp4";
} else {
$hq = null;
}
$i = $i + 1;
echo "<div class=\"klip\">";
echo '<video id="' . $nazwa_rob . '" width="320" height="180" controls poster= "' . $poster . '" preload ="none">';
echo ' <source id="source_' . $nazwa_rob . '" src="' . $sciezka . '" type="video/mp4">';
echo 'Twoja przeglądarka nie obsługuje HTML5.';
echo '</video>';
echo '<br />';
if ($hq != null) {
echo '<button id="videolink' . $i . '" type="button" class="btn btn-danger active" style=" font-size: 10px; padding: 5px; position: absolute; bottom: 2px; left: 11px;">HQ</button>';
}
echo '<div class="nazwa">'.$nazwa.'</div>';
//skrypt zmiany jakosci JS
if (file_exists($sprawdzian_hq)) {
echo '
<script type = "text/javascript">
var videobutton = document.getElementById("videolink' . $i . '");
videobutton.addEventListener("click", function (event) {
';
echo "
var videocontainer$i = document.getElementById('$nazwa_rob');
var videosource$i = document.getElementById('source_$nazwa_rob');
var newmp4$i = '$hq';
var old_mp4$i = '$sciezka';
var aktywne$i = 'btn btn-success active';
var nieaktywne$i = 'btn btn-danger active';
var przycikstatus$i = document.getElementById('videolink$i');
var obecny_klip$i = videosource$i.getAttribute('src');
var czas_klipu$i = videocontainer$i.currentTime;
console.log(czas_klipu$i);
if (obecny_klip$i != newmp4$i) {
var videosource$i = document.getElementById('source_$nazwa_rob');
videocontainer$i.pause();
videosource$i.setAttribute('src', newmp4$i);
videocontainer$i.load();
videocontainer$i.pause();
videocontainer$i.currentTime = czas_klipu$i;
przycikstatus$i.setAttribute('class', aktywne$i);
videocontainer$i.play();
} else {
var videosource$i = document . getElementById('source_$nazwa_rob');
videocontainer$i.pause();
videosource$i.setAttribute('src',old_mp4$i);
videocontainer$i.load();
videocontainer$i.pause();
videocontainer$i.currentTime = czas_klipu$i;
przycikstatus$i.setAttribute('class', nieaktywne$i);
videocontainer$i.play();
}
}, false);
</script>
";
}
you can also use this javascript code.
//external.js
video = document.getElementsByClassName("video");
for (i = 0; i < video.length; i++) {
video[i].onplay = function () {
var currentIndex = index("video", this);
for (k = 0; k < video.length; k++) {
if (k == currenIndex) { continue }
video[k].pause();
}
}
}
function index(className, id) {
nodes = document.getElementsByClassName(className);
return [].indexOf.call(nodes, id);
}
<html>
<head>
</head>
<body>
<video class="video" src="video1.mp4" controls></video>
<video class="video" src="video2.mp4" controls></video>
<video class="video" src="video3.mp4" controls></video>
<video class="video" src="video4.mp4" controls></video>
<script src="external.js"></script>
</body>
</html>
Now i've got another issue with this code :
<script> video = document.getElementsByClassName("video");
for (i = 0; i < video.length; i++) {
video[i].onplay = function () {
var currentIndex = index("video", this);
for (k = 0; k < video.length; k++) {
if (k == currentIndex) { continue }
video[k].pause();
}
}
}
function index(className, id) {
nodes = document.getElementsByClassName("video");
return [].indexOf.call(nodes, id);
}
</script>
I've got about 30 video tags on one page. When i try to play 6 videos one after another, the playback of 7th video doesn't run.
Excuse, i have not been notified. I used them same code to play one after another 30 videos without a problem. try to see if you have not limited the i value to 7 or something like that.
you may have only 7 tags that have 'video' class. if all's right, try to replace. document.getElementsByClassName by document.getElementsByTagName and try again. sorry not to have responded at time.

Not getting a response from php in ajax handleResponse

I am trying to execute a search on database. My goal is to take a search form and use ajax to request PHP to return a result. Problem is, I am not getting a response in ajax handleRequest function. Also, how do I send back a xml response from php. Here is my code. Sorry for the clutter.
index.php
<!doctype>
<html lang="en">
<head>
<title>Test Form</title>
<script src="js/validate.js"></script>
</head>
<body onload="setfocus();">
<span id="error"></span>
<form id ="searchForm" method="POST" action="/php/validate.php"
onsubmit="event.preventDefault(); process();">
<input type="text" placeholder="Eg. Canada" name="country" id="country_id"
onblur="validate(this.id, this.value);" required/>
<br />
<input type="text" placeholder="Eg. Toronto" name="city" id="city_id"
onblur="validate(this.id, this.value);" required/>
<br />
<label for="featues">Features</label>
WiFi<input type="checkbox" name="wifi" value="wifi" />
TV<input type="checkbox" name="tv" value="tv" />
Breakfast<input type="checkbox" name="breakfast" value="breakfast" />
<br />
<label>Room Type</label>
<select name="roomtype">
<option name="mastersuite" value="mastersuite">Master Suite</option>
<option name="suite" value="suite">Suite</option>
<option name="largeroom" value="largeroom">Large Room</option>
<option name="smallroom" name="smallroom">Small Room</option>
</select>
<br />
<label>Price Range</label>
<input type="text" name="minrange" id="price_min_range_id"
onblur="validate(this.id, this.value);" />
<input type="text" name="maxrange" id="price_max_range_id"
onblur="validate(this.id, this.value);" />
<br />
<label>Stay date</label>
<br />
<label>Arrival Date</label>
<input type="date" name="arrival" id="arrival" placeholder="MM/DD/YYYY"
onblur="validate(this.id, this.value);" required/>
<label>departure Date</label>
<input type="date" name="departure" id="departure" placeholder="MM/DD/YYYY"
onblur="validate(this.id, this.value);" />
<br />
<input type="submit" name="search" value="search">
</form>
<div id="responseDiv"></div>
</body>
</html>
validate.js
var xmlHttp;
//var serverAddr;
//var error;
var response;
function createHttpRequestObject(){
var responseObj;
//for IE
if(window.ActiveX){
var vers = new Array("MSXML2.XML.Http.6.0",
"MSXML2.XML.Http.5.0",
"MSXML2.XML.Http.4.0",
"MSXML2.XML.Http.3.0",
"MSXML2.XML.Http.2.0",
"Microsoft.XMLHttp");
for(var i=0; i<vers.length && !responseObj; i++){
try{
responseObj = new ActiveXObject(vers[i]);
}catch(e){
responseObj = false;
}
}
}
else{ //for all other browser
try{
responseObj = new XMLHttpRequest();
}catch(e){
responseObj = false;
}
}
if(!responseObj || responseObj === false){
alert("Failed to create response object");
}
else{
return responseObj;
}
}
function process(){
xmlHttp = createHttpRequestObject();
if(xmlHttp){
var firstname = encodeURIComponent(
document.getElementById("firstname").value);
var roomtype = encodeURIComponent(
document.getElementById("roomtype").options[
document.getElementById("roomtype").selectedIndex].value);
var minrange = encodeURIComponent(
document.getElementById("price_min_range_id").firstChild.value);
var maxrange = encodeURIComponent(
document.getElementById("price_max_range_id").firstChild.value);
var city = encodeURIComponent(document.getElementById("city_id").firstChild.value);
var country = encodeURIComponent(
document.getElementById("country_id").firsChild.value);
var arrivalDate = encodeURIComponent(
document.getElementById("arrivalDate").value);
var departureDate = encodeURIComponent(
document.getElementById("departureDate").value);
var amenity_breakfast = encodeURIComponent(
document.getElementByName("Breakfast").checked);
var amenity_tv = encodeURIComponent(
document.getElementByName("TV").checked);
var amenity_wifi = encodeURIComponent(
document.getElementByName("wifi").checked);
//get other filed values
xmlHttp.open("POST", "php/validate.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = handleResponse;
xmlHttp.send("firstname=" + firstname + "&roomtype="+ roomtype + "&country="+ country + "&city=" + city + "&minrange=" + minrange + "&maxrange=" + maxrange + "&arrivalDate="+arrivalDate + "&departureDate="+ departureDate + "&breakfast="+
amenity_breakfast + "&tv="+amenity_tv + "&wifi="+ amenity_wifi);
}
else{
alert("Error connecting to server");
}
}
function handleResponse(){
var docdiv = document.getElementById("responsediv");
var table = "";
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//the search info as xml
//var response = xmlHttp.responseXML;
response = xmlHttp.responseXml;
if(!response || response.documentElement){//catching errors with IE, Opera
alert('Invalide Xml Structure:\n'+ response.responseText);
}
var rootNodeName = response.documentElement.nodeName;
if(rootNodeName=="parseerror"){//catching error with firefox
alert('Invalid Xml Structure:\n');
}
var docroot = response.documentElement;
var responseroot = docroot.getElementByTagName("response");
//extracting all hotel values from search
var hotels = new Array(responseroot.getElementByTagName("hotels"));
table = "<table border='1px solid' margin='2px' padding='5px'>";
//docdiv.appendChild(table);
for(var i=0; i<hotels.legnth; i++){
var hotelroot = hotels[i].getElementTagName("name");
var hotelname = hotelroot.firstChild.data;
var hoteladd = hotels[i].getElementByTagName("hoteladd").firstChild.data;
var reqRoomNum = hotels[i].getElementTagName("reqroom").firsChild.data;
table +="<tr>";
//row = table.append(row);
//name column
table += "<td>";
table += hotelname + "</td>";
//address column
table += "<td>";
table += hoteladd + "</td>";
//desired roomttype
table += "<td>";
table += reqRoomNum + "</td>";
//docdiv.createElement("</tr>");
table += "</tr>";
}
table += "</table>";
}
docdiv.innerHTML= table;
}
}
function validate(fieldId, value){
//var error = 0;
//var errortext = '';
switch(fieldId){
/*case 'name':
var chk_name_regex = /^[A-Za-z ]{3,30}$/;
if(value.length<4 &&!chk_name_regex.test(value)){
print_error('Name format wrong',fiedlId);
}
break;*/
case 'country_id':
var chk_country_regex = /^[A-Za-z- ]{4,50}$/;
if(value.length<4 && !chk_country_regex.test(value)){
print_error('Country name format wrong',fieldId);
}
break;
case 'city_id':
var chk_city_regex = /^[A-Za-z- ]{4,50}$/;
if(value.length<4 && !chk_city_regex.test(value)){
print_error('City name format wrong',fieldId);
}
break;
case 'price_min_range_id':
var r = value;
if(r<0){
print_error('Min range must be zero atleast',fieldId);
}
break;
case 'price_max_range_id':
r = value;
if(!(r>=0 && r>=document.getElementById('price_min_range_id').firstChild.value)){
print_error('Max index must be atleast zero or greater than min',fieldId);
}
break;
case 'arrival':
var arrival = value;
var datecomp = arrival.explode("/");
var monthOk = parseInt(datecomp[0])>=1 && parseInt(datecomp[0])<=12;
var getleapday = parseInt(datecomp[2]) % 4===0 &&
parseInt(datecomp[2])%100===0 && parseInt(datecomp[2])%400===0;
var dayOk = parseInt(datecomp[1])>=1 && parseInt(datecomp[2])<=31;
var yearOk = parseInt(datecomp[2])>2015;
if(monthOk && dayOk && yearOk){
print_error('Date format is wrong',fieldId);
}
break;
}
}
function print_error(msg, fieldId){
var errorSpan = document.getElementById('error');
errorSpan.innerHTML = "<p text-color='red'>" + msg + "</p>";
document.getElementById(fieldId).focus();
}
function setfocus(){
document.getElementById('country_id').focus();
}
validate.php
<?php
function just_check(){
print_r($_POST);
}
just_check();
//config script
require_once('config.php');
//vars for all the fileds
$country = $city = $wifi = $tv = $breakfast = $minrange = $maxrange
= $arrival = $departure = $roomtype = '';
//server side input validation
if($_SERVER['REQUEST_METHOD']=='POST'){
$country = inputValidation($_POST['country']);
$city = inputValidation($_POST['city']);
$minrange = inputValidation($_POST['minrange']);
$maxrange = inputValidation($_POST['maxrange']);
$arrival = inputValidation($_POST['arrivalDate']);
$departure = inputValidation($_POST['departureDate']);
$roomtype = $_POST['roomtype'];
if(isset($_POST['wifi'])){
$wifi = true;
}
if(isset($_POST['tv'])){
$tv = true;
}
if(isset($_POST['breakfast'])){
$breakfast = true;
}
}
//echo $country . " " . $city . '<br >';
//connect to mysql
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME)
or die('Could not connect to db');
//query the database matching fields;
$query = "SELECT hotel_id, hotel_name FROM allhotels WHERE ";
//echo $query . '<br />';
if(isset($country)){
$query .= "(hotel_country='$country') AND";
}
//echo $query . '<br />';
if(isset($city)){
$query .= " (hotel_city='$city') AND";
}
$query = substr($query,0, -4);
// echo $query . '<br />';
$res = $db->query($query);
//echo $query . '<br />';
if(!$res){
echo $db->errno . '->' . $db->error;
}
//setting header to XML
header('ContentType: text/xml');
//creating XML response string"
$dom = new DOMDocument();
$response = $dom->createElement("response");
$dom->appendChild($response);
while($row = $res->fetch_array(MYSQLI_ASSOC)){
//matching room field value for query
$roomfield='';
if($roomtype == 'mastersuite'){
$roomfield = 'hotel_master_suites';
}
else if($roomtype == 'suite'){
$roomfield = 'hotel_suite';
}
else if($roomtype == 'largeroom'){
$roomfield = 'hotel_large_rooms';
}
else{
$roomfield = 'hotel_small_rooms';
}
//query with the roomfield and hotel_id value
$htl_id = $row['hotel_id'];
$subquery = "SELECT hotel_add, $roomfield FROM spechotel WHERE ".
"(hotel_id = $htl_id) AND ($roomfield > 0) AND";
if(isset($wifi)){
$subquery .= " (wifi=1) AND";
}
//echo $subquery . '<br />';
if(isset($tv)){
$query .= " (tv=1) AND";
}
//echo $query . '<br />';
if(isset($breakfast)){
$query .= " (breakfast=1) AND";
}
//echo $query . '<br />';
$subquery = substr($subquery,0, -4);
// echo $query . '<br />';
//echo $subquery . '<br />';
$subrow = $db->query($subquery);
$subrow = $subrow->fetch_array(MYSQLI_ASSOC);
$hotel_header = $dom->createElement("hotels");
$hotel_name = $dom->createElement("name");
$hotel_name->appendChild($dom->createTextNode($row['hotel_name']));
$hotel_add = $dom->createElement("hoteladd");
$hotel_add->appendChild($dom->createTextNode($subrow['hotel_add']));
//$hotel_postal = $hotel_header->apppendChild("hotelpostal");
//$hotel_postal->createTextNode($subrow['']);
$hotel_req_room = $dom->createElement("reqroom");
$hotel_req_room->appendChild($dom->createTextNode($subrow[$roomfield]));
$hotel_header->appendChild($hotel_name);
$hotel_header->appendChild($hotel_add);
$hotel_header->appendChild($hotel_req_room);
}
$xmlString = $dom->saveXML();
//print table
$db->close();
//close connection
//return search
function print_search_result(){
global $xmlString;
echo $xmlString;
}
print_search_result();
function inputValidation($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

Custom Advance Find view in Iframe in CRM 2011 does not load gird in Firefox AND IE

To load a grid in Iframe of a form, in the form load event, I added this this script :
var gContext;
function loadIFrame(context) {
gContext=context.getContext();
window.fetchActivtities = new FetchViewer("IFRAME_casebysedrialno");
fetchActivtities.FetchXml = getFetchXml(null,null);
fetchActivtities.LayoutXml = getLayoutXml();
fetchActivtities.Entity = "incident";
fetchActivtities.QueryId = "{B34A5382-F6B7-E311-B5B1-000C2964D6D6}"; // view GUID
fetchActivtities.RegisterOnTab(2); //IFRAME TAB INDEX
}
function getFetchXml(itemtoSelect,itemValue) {
// FetchXML Query
return '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">'+
'<entity name="incident">'+
'<attribute name="title" />'+
'<attribute name="ticketnumber" />'+
'<attribute name="createdon" />'+
'<attribute name="incidentid" />'+
'<order attribute="title" descending="false" />'+
'</entity>'+
'</fetch>';
}
function getLayoutXml() {
// grid layout, you can get easily from Customization.xml file
return '<grid name="resultset" object="112" jump="title" select="1" preview="1" icon="1">'+
'<row name="result" id="incidentid">'+
'<cell name="title" width="150" />'+
'<cell name="incidentstagecode" width="100" />'+
'<cell name="casetypecode" width="100" />'+
'<cell name="prioritycode" width="100" />'+
'<cell name="productserialnumber" width="100" />'+
'<cell name="severitycode" width="100" />'+
'<cell name="statecode" width="100" />'+
'</row>'+
'</grid>';
}
function FetchViewer(iframeId) {
var Instance = this;
var vDynamicForm;
var m_iframeTab;
var m_iframeDoc;
Instance.Entity = "";
Instance.Iframe = null;
Instance.FetchXml = "";
Instance.QueryId = "";
Instance.LayoutXml = "";
Instance.RegisterOnTab = function (tabIndex) {
Instance.Iframe = document.getElementById(iframeId);
if (!Instance.Iframe)
return alert("Iframe " + iframeId + " is undefined");
m_iframeDoc = getIframeDocument();
var loadingGifHTML = "<table height='100%' width='100%' style='cursor:wait'>";
loadingGifHTML += "<tr>";
loadingGifHTML += "<td valign='middle' align='center'>";
loadingGifHTML += "<img alt='' src='/_imgs/AdvFind/progress.gif'/>";
loadingGifHTML += "<div/><b>Loading View...</b>";
loadingGifHTML += "</td></tr></table>";
m_iframeDoc.body.innerHTML = loadingGifHTML;
Instance.Refresh();
}
function RefreshOnReadyStateChange() {
if (Instance.Iframe.readyState != 'complete')
{
return;
}
Instance.Refresh();
}
Instance.Refresh = function () {
if (!Instance.Iframe)
{
return alert("Iframe " + iframeId + " is undefined");
}
m_iframeDoc = getIframeDocument();
Instance.Iframe.removeEventListener("onreadystatechange", RefreshOnReadyStateChange);
vDynamicForm = m_iframeDoc.createElement("FORM");
vDynamicForm.setAttribute("name","vDynamicForm");
vDynamicForm.setAttribute("method","post");
createTwoAttElem(m_iframeDoc,vDynamicForm,"INPUT","type","hidden","name","FetchXml");
createTwoAttElem(m_iframeDoc,vDynamicForm,"INPUT","type","hidden","name","LayoutXml");
createTwoAttElem(m_iframeDoc,vDynamicForm,"INPUT","type","hidden","name","EntityName");
createTwoAttElem(m_iframeDoc,vDynamicForm,"INPUT","type","hidden","name","DefaultAdvFindViewId");
createTwoAttElem(m_iframeDoc,vDynamicForm,"INPUT","type","hidden","name","ViewType");
vDynamicForm.action = gContext.getServerUrl()+("/AdvancedFind/fetchData.aspx");
vDynamicForm.FetchXml.value = Instance.FetchXml;
vDynamicForm.LayoutXml.value = Instance.LayoutXml;
vDynamicForm.EntityName.value = Instance.Entity;
vDynamicForm.DefaultAdvFindViewId.value = Instance.QueryId;
vDynamicForm.ViewType.value = 1039;
vDynamicForm.submit();
//Instance.Iframe.attachEvent("onreadystatechange", OnViewReady);
Instance.Iframe.addEventListener("onreadystatechange", OnViewReady);
}
function OnViewReady() {
if (Instance.Iframe.readyState != 'complete') return;
Instance.Iframe.style.border = 0;
Instance.Iframe.removeEventListener("onreadystatechange", OnViewReady);
m_iframeDoc = getIframeDocument();
m_iframeDoc.body.scroll = "no";
m_iframeDoc.body.style.padding = "0px";
}
function getIframeDocument() {
myFrame = Instance.Iframe;
myWindow = myFrame.contentWindow;
myDoc = myWindow.document;
return myDoc;
}
}
function createTwoAttElem(doc,eletoAppend,elemname,att1,att1val,att2,att2val)
{
var newelem = doc.createElement(elemname);
newelem.setAttribute(att1,att1val);
newelem.setAttribute(att2,att2val);
eletoAppend.appendChild(newelem);
}
it works prefectly in Chrome but in IE and Firefox, it only shows "Loading View ...". I inspected network requestes in all three browsers, and saw that in Chrome there is a post request to "fetchData.aspx" but there is not such request in firefox or IE.
Just found a solution.
Instead of creating the form using document.Createelement and ... I created the form by string and put it into Innerhtml of Iframe and it worked
http://social.microsoft.com/Forums/en-US/f375d23c-8867-4296-9775-3df995420579/custom-advance-find-view-in-iframe-in-crm-2011-does-not-load-gird-in-firefox-and-ie?

Categories

Resources