I have page that has a text input and a button
the user must fill a URL which is referring to a playable media file(mp4) in the text field and click the button
when the button is clicked the a script is running and ajax is passing the url value to PHP file which do some verifications and send the response back
if every thing is ok it should replace the DIV tag with JW player and the user can play the media
I test the whole process by replacing the DIV tag with a plain text or image and it worked smoothly
and when I tried to replace it with the jw player component it is not showing any thing
I tested the jw by inserting it directly in the HTML code and it worked smoothly
here is the full index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/ajax4/jwplayer.js"></script>
<script type="text/javascript">jwplayer.key="RXVe0CXFsIS8pAar5ezgSLJqb9jfx7rDOBxkVw==";</script>
<script type="text/javascript"><!--
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var hiturl = document.getElementById('hit').value;
var the_data = 'hiturl='+hiturl;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<form action="test_form.php" method="post" name="form1" onsubmit="ajaxrequest('hitphp.php', 'myDiv'); return false;">
<label for="name" id="name_label">hit URL: </label>
<input type="text" name="hit" id="hit" size="100" />
<input type="submit" value="Enter hit UrL" />
</form>
<div id="myDiv"></div>
</body>
</html>
and the hitphp.php file
<?php
// if data are received via POST
if (isset($_POST['hiturl'])) {
// get data into variables, deleting the html tags
$hiturl = strip_tags($_POST['hiturl']);
// if the form fields are completed
if (true) {
if (true) {
echo'<div id="myElement">nnnnn.....</div><script type="text/javascript">
jwplayer("myElement").setup({
type:"mp4",
bufferlength: "60",
file: "mediaurl",
});
</script>';
}else{
echo 'sorry not a valid url';
}
}
else {
echo 'Fill in all form fields';
}
}
?>
Related
I am having problems with a really basic request to a php file from AJAX. I am running all this stuff through XAMPP. What I'm trying to do with this code is to echo the name typed into the textbox once the submit button is clicked and the results to be posted in the div "results". I am doing this to try and weed out errors in another script and so far it hasn't gone too well.
<html>
<head>
<script type="text/javascript">
function go() {
var request;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var uname = document.getElementById("name").value;
request.onreadystatechange= function() {
if(request.readyState == 4) {
document.getElementById("result").innerHTML = response.Text;
}
}
url = "win.php?name="+uname;
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body>
Name:<input type="textbox" name="jesus" id="name" />
<input type="button" value="Submit" onlick="go()" />
<div id ="result"> Result:</div>
</body>
</html>
<?php
$name = $_GET['name'];
echo $name;
?>
You don't have an object called response, you are looking for the responseText property on the request object.
document.getElementById("result").innerHTML = request.responseText;
Also:
avoid using globals
don't send your HTTP request before the target div exists, you run the risk of it still not existing when the response comes back
you probably should check that the HTTP status of the response is 200 (OK) as well as being finished (readyState 4).
Don't put raw user input in URLs, escape it with encodeURIComponent first
Use that
document.getElementById("result").innerHTML = response.responseText;
All happens in one php file
HTML code
<td>
<input type="text" name="date_day1" id="date_day1"
value="<?php echo $_POST['date_day1']?>" size="1">
</td>
<td>
<input type="text" name="amount1" id="amount1"
value="<?php echo $_POST['amount1']?>" size="5"></td>
Then javascript
<script type="text/javascript">
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp; // The variable that makes Ajax possible!
//Global XMLHTTP Request object
//Creating object of XMLHTTP in Internet Explorer
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
XmlHttp = null;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
// Set var the new request Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}//try {
catch (e) {//if it fails move onto the next
xmlhttp = false;
}//catch (e) {
}//if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
return xmlhttp;
}//function getHTTPObject() {
function init(){
window.setInterval(autoSave,3000); // 15000=15 seconds
}
function autoSave(){
var date_day1 = document.getElementById("date_day1").value;
var amount1 = document.getElementById("amount1").value;
var params = "date_day1="+date_day1+"&amount1="+amount1;
var http = getHTTPObject();
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
</script>
And php
$date_day1 = $_POST['date_day1'];
$amount1 = $_POST['amount1'];
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($_SERVER["REQUEST_METHOD"]=="POST"){
if ($stmt = mysqli_prepare($mysqli,
"UPDATE 2_1_journal SET Amount = ? WHERE RecordDay = ? ") ) {
$stmt->bind_param( 'ds', $amount1 , $date_day1 );
$stmt->execute();
echo $date_day1 .' date_day1 from update<br>';
echo $amount1 .' amount1<br>';
}
}
So what happens. Javascript (ajax) without clicking button takes user input, send to php code. Php code updates mysql. That means that somehow without clicking submit button are created php variables to update ($amount1 , $date_day1)?
But why these variables do not exist latter? I want without page refresh (without clicking submit button) use variables. For example in input form as value=""
How to do that? As I understand need to use json? but from information I have found can not understand.... Can someon write step by step how with json pass user input (or value from mysql) to input value=""
Or may be some book/tutorial how all works (book/tutorial for dummies to understand)?
Your php script should echo a json. For example, i have ajax.php:
<?php
$myVariable = $_POST['myVar'];
//Do something with database here
//Here goes whatever you want to pass back to your page
echo json_encode(array('result' => 'Done doing things', 'data' => $someData)).
// This outputs a json
// {"result" : "Done doing things", "data" : "Contents of $someData"}
And then jQuery will process this. Where your html file is something like
<html><head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.myButton').click(function(e) {
e.preventDefault(); //Prevent the page from reloading
$.post('ajax.php', function(data) {
$('#myContent').html(data.result); //Put the result into the div
}, 'json');
});
});
</script></head>
<body>
<div id="myContent">This text will be replaced</div>
Click Me
</body>
</html>
Read here about jQuery post function.
http://api.jquery.com/jQuery.post/
Don't forget to include the jQuery library (read the documentation thoroughly).
If you need the data to be not erased between calls, you can :
Pass it back in your json and store it in a javascript variable,
Store it in the session or cookie
Store it in the database
I'm learning AJAX and created this simple code. I type in something in the text box and it should return with the word something pop up on screen. This was able to work when I clicked on a button but now that I changed it to a text box it no longer works. Here is the first file that contains the XML HTTP Request data and HTML code.
<html>
<head>
<script type="text/javascript">
function load() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('results').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'test_ajax_return.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="search" name="search">Type a name:
<br>
<input type="text" name="search_text" onkeydown="load();">
</form>
<div id="results"></div>
</body>
</html>
And here is the second file that I want to open when the user types in something in the text box.
<?php
echo 'something';
?>
[SOLVED] : Thanks to Matt for Javascript Console. Found out some comments that I edited out effected the code after all. I didn't think HTML comments could do that. Lesson learned.
Open up your javascript console (F12 in Chrome) and see if there are any errors (indicated by a red X on the bottom of the popup).
You most likely have javascript errors that you're not catching.
I just copied the code to my machine, it works perfectly.
As an idea though, maybe your browser's being funny about onkeydown. Try onKeyDown instead.
I am calling a contacts list from a MySQL database using AJAX in PHP page. The data is called correctly, but when I call the PHP page in the browser, I can see the contacts list (data from DB) is being displayed in the top of the page before the meta data. The list should be displayed in the defined DIV, but for some reason it is not. Below is my code:
Ajax Code:
function getUserList(){
var ajaxDisplay = myform.getElementById('displayList'); // HTML Div where data should be displayed
try{ //for Firefox, Chrome, Opera, Safari, IE7+
var activeX = new XMLHttpRequest(); //initializing object
}catch(e){
try{// for IE5 , IE6
var activeX = new ActiveXObject(Msxml2.XMLHTTP);
}
catch(e){
alert("Dude your browser is in Jurassic era!");
}
}
activeX.readystatechange = function{
if(activeX.readyState == 4){
var queryResult = activeX.responseText;
if(!queryResult){
ajaxDisplay.innerHTML = 'Error in populating list';
}else{
ajaxDisplay.innerHTML = queryResult;
}
}
}
activeX.open("GET", "?action=contactsandgroups", true);
activeX.send(null);
}
PHP/HTML code:
<div class="contacts_list_data_contacts" id="displayList"></div>
MySQL Function:
while($row=mysql_fetch_assoc($res_info)){
print '<div class="contacts_headings_01">
<div class="contacts_checkbox_01"><input name="contact_id[]" id="contact_id" type="checkbox" value="'.$row['contact_id'].'" style="margin-top:0px ; margin-left:-3px;" /></div>
<div class="contacts_firstname_01_contacts">'.$row['firstname'].'</div>
<div class="contacts_firstname_01">'.$row['lastname'].'</div>
<div class="contacts_firstname_01">'.$row['company'].'</div>
</div>';
}
When I view the page source, it shows that it prints the data at the top of the page. This happens in Firefox, Chrome, and Internet Explorer.
What I see is, you want this output of ?action=contactsandgroups to be populated inside div#displayList. If that is the case, please try the following:
Add this in your <head> part:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function getUserList()
{
ajaxDisplay = $("#displayList");
ajaxDisplay.load('?action=contactsandgroups');
}
</script>
Try it out and see if it works. If not, send me the HTML Code, where you call the function.
Ajax responds with an empty string when triggered via form onsubmit in Firefox, but it is working fine in Internet Explorer and Opera (works in Firefox if sent by a submit button instead of form onsubmit).
I am simply calling a php file with the ajax GET and the php file response with - echo $response = "something";. Then the response value is alerted. I am getting it work in IE but in Firefox the response is an empty string (checked by typeof()).
code is 4 files: index.php, ajax-connect.js, cbb.js, cbb.php
index.php
<html> <head> <script src="ajax-connect.js"></script> <script src="cbb.js"></script>
</head> <body>
<form name="condtactform1" method="get" action="" onSubmit="contactfunction()">
<input type="submit" name="hissubmit" id="hissubmit" value="submit"> </form>
</body> </html>
ajax-connect.php
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*#cc_on #*/
/*#
if (#_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
#end
#*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
cbb.js
function contactfunction() {
var url = "cbb.php";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var responsae = xmlHttp.responseText;
alert(responsae);
}
}
cbb.php
<?php $response = "something"; echo $response; ?>
If i trigger ajax by submit button instead of the form submit then it works fine in firefox like:
<form name="condtactform1" method="get" action="">
<input type="submit" name="hissubmit" id="hissubmit" value="submit" onFocus="contactfunction()"> </form>
Any idea why it is doing this?
Thanks.
I think part of the problem is that you aren't stopping the normal action of the submit. That it is working at all is probably based on how the return values of the last function executed is handled, though its hard to tell. Try adding a "return false" to your contactFunction();
If that doesn't work, I'd invest some time in retrofitting it to use a javascript framework for the AJAX (jQuery, MooTools, Prototype, etc.) rather than going down the route of debugging the cross browser differences. A jQuery solution would look like:
<form name="condtactform1" method="get" action="cbb-full.php">
<input type="submit" name="hissubmit" id="hissubmit" value="submit">
</form>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
<script>
<script type="text/javascript">
$(function() {
$('#hissubmit').click( function() {
$.get( 'cbb.php', function(response) {
alert(response);
});
return false;
});
});
</script>
Note that the form ought to post to a url that will generate a full response if javascript isn't enabled.