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.
Related
I need to load data from a database table using an ID that is sent to a modal window.
Basically, when the grid loads, there are multiple columns. Two in particular are called CONTAINER_ID and WORKFLOW.
Whatever is returned for WORKFLOW will be a link that opens up a MODAL popup called #mySVCModal. Here is the sample code:
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE)
{
echo "<tr";
echo "<td style=\"width: 50px;\">{$Row[CONTAINER_ID]}</td>";
echo "<td style=\"width: 50px;\"><a class=\"open-container\"
data-toggle=\"modal\" href="#mySVCModal\"
data-cont=\"{$Row[CONTAINER_ID]}\">{$Row[WORKFLOW]}</a></td>";
echo "</tr>";
}
When the user clicks on {$Row[WORKFLOW]}, a modal window opens up with the CONTAINER_ID from the same row.
Here is the javascript that makes that happen:
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
});
</script>";
At this point, the modal window is open, and I can display the CONTAINER_ID. Here is the code that displays the CONTAINER_ID:
<div id="mySVCModal">
<form action="" method="POST">
<input type="text" name="containerID" id="containerID" class="containerID" />
*** more code here ***
</form>
</div>
So no problem. The CONTAINER_ID is displayed in an INPUT field called "containerID".
What I need to make happen now is when the modal window opens, "containerID" is sent to a PHP variable that will retrieve the WORKFLOW information from a database table called WORKFLOW_TABLE.
When I try to convert containerID into a PHP variable and echo it out, nothing is displayed:
<?php
$containerID = $_POST['containerID'];
echo "this is containerID " . $containerID; // only displays the text, not the $containerID
?>
I know that once I can get the code directly above to display the containerID in an ECHO, I can run a query off of it.
So basically, what I need to do is when the modal window opens, PHP will take containerID and run a " SELECT * FROM WORKFLOW_TABLE where CONTAINER_ID = 'containerID' ";
The contents from WORKFLOW_TABLE should automatically be displayed in various INPUT fields. I'm just using INPUT fields for now. That's beside the point.
So all in all, I need the modal to open up with the contents from WORKFLOW_TABLE displayed using the containerID.
I hope I worded this clearly.
Please help.
Sounds like you need an AJAX query.
<script>
function loadData()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "db_query.php?containerID = " + document.getElementById('containerID').getAttribute('value'), true);
xmlhttp.send();
}
window.onload = loadData;
</script>
<div id="myDiv"></div>
Sorry in advance for any possible flaws, I didn't actually run this.
It looks like you're not actually submitting your form to the server when you're loading the modal.
Since you probably don't want to reload the entire page to display the modal, you should request the modal content on demand using an asynchronous request. Since your sample code uses jQuery, I've used the same here. (see the jQuery.load() documentation for more info)
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
$('.modal-body').load(
'yourPHPscript.php',
{ containerID: $('#containerID').val()}
);
});
</script>";
Then your PHP script should resemble this (notice the change from POST to GET):
<?php
$containerID = $_GET['containerID'];
echo "this is containerID " . $containerID;
?>
I'm just starting out with AJAX. I'm trying to create a test where I enter some text into a text input box, click a submit button on a form, and have that text display on my page. The immediate error that I am getting is a 404 error ( www.mysite.com/ajaxFunction() ), but I'm sure that there are others yet to be discovered. Can anyone please help me correct this to get me started out with AJAX? I'm spinning my wheels trying to get started. Also, please realize that I am calling a php script since this is what my ultimate goal will require, which is why I'm not just using JavaScript itself. Thanks!
Here is the html:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.action = getFeedback();
}
function getFeedback() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("feedback").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","scripts/handle_feedback.php",true);
xmlhttp.send();
}
//-->
</script>
<div id="leftsidebox"></div>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
</body>
</html>
handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
return $mytext;
?>
EDIT: Here is my latest html code. I made the change to the php (switching 'return' to 'echo')
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.onsubmit = getFeedback;
}
function getFeedback() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("feedback").innerHTML=xmlhttp.responseText;
}
}
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textbox,true);
xmlhttp.send();
}
//-->
</script>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
scripts/handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
This won't do what you're expecting it to do:
document.myform.action = getFeedback();
You're probably expecting it to make it call getFeedback when the form is submitted. That's not actually what happens. When the browser tries to run that code, it will realize: “oh, hey, we're assigning action. But wait, on the right hand side, there's a function call! I've got to evaluate that function call in order to find the return value to set action to!” And so your browser dutifully calls getFeedback immediately. Since getFeedback doesn't return anything, it sets action to undefined. Boy, that was helpful.
If we want a JavaScript function to be called when the form is submitted, setting action is not the right way to do it. So what is the right way? An event listener. The most common way of attaching an event listener is using addEventListener, but since your use case is rather simple, we're going to use a simpler, often neglected way: setting onsubmit:
document.myform.onsubmit = getFeedback;
Note that we do not have parentheses after getFeedback. This is intentional. We want to set onsubmit to the getFeedback function itself, not its return value.
You're also using textbox without defining it. Sure, it exists in the document, but that doesn't mean it's a variable available in the script. To access it, you'll need to first get the element and then get that element's value:
document.getElementById('name').value
Another thing that might be getting you is the same origin policy. Rather than using a complete URL to open, just pass a relative URL:
xmlhttp.open("GET", "something.php" /* ... */, true);
It should be echo not return. return is used in function to return the data.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
Also you have to send the parameter to php file
xmlhttp.open("GET","scripts/handle_feedback.php?textbox=your_value",true);
First point : you missed request parameters from client end.
Send parameters in querystring for GET request.
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textvalue ,true);
for more reference read here.
And second point is :
'return' statement is used with functions/methods. Since you don't have any function here, so instead of that use 'echo' or 'print' statement.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
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';
}
}
?>
I am loading a .php file into a div I created.
I can successfully load the file into the div and everything works except javascript.
When i test the file in my browser, the javascript works, but not when it's injected into my div.
index.php
<?php
$filename = $_GET["filename"];
if($filename != ""){
$fileData = file_get_contents($filename);
$fileData = trim($fileData);
$fileData = str_replace("\n", "", $fileData);
$fileData = str_replace("\r", "", $fileData);
echo $fileData;
die;
}?>
<body>
<script>
function LoadFile(filename, javascriptDiv){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
javascriptDiv.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.php?filename="+filename,true);
xmlhttp.send();
}
var javascriptDiv = document.createElement('div');
javascriptDiv.setAttribute('id', 'javascriptDiv');
javascriptDiv.style.position = 'absolute';
javascriptDiv.style.top = 50;
javascriptDiv.style.left = 50;
javascriptDiv.style.height = 200;
javascriptDiv.style.width = 300;
javascriptDiv.style.background = '#CCCCCC'; //so we can see that the DIV was created
LoadFile('http://127.0.0.1/Debug/test.php', javascriptDiv);
document.body.appendChild(javascriptDiv); //Display the Window
</script>
</body>
test.php <--the file i'm loading into the div
Plain text works
<?php echo "<br>php works <br>"; ?>
<a>html works</a><br>
<script>
function Test(){
alert('javascript works');
}
</script>
<input type="button" value="Test Javascript" onclick="Test()"/>
Here's what it looks like on my site.
index.php
And here is a direct link to the test.php file
test.php
I need to get this working without altering the test.php file.
No, you can't evaluate tags with lazy loading.
Generally speaking, I think the idea of allowing users to run custom javascript is a door open to exploits. I don't know exactly what you are trying to achieve and why, but you'd better create a set of functions yourself and publish a simple public API (for example, to get a lightbox, add a 'lightbox' class to your element, or that kind of thing).
Alternatively, you could fetch the content of the tag and run an eval(). But again, it's dangerous.
This page explains quite well the different methods you can use to achieve this. Of course, all assume you are running your own code and not some user code.
When you pull in content from AJAX, it's up to the browser whether or not to parse any script tags you include [From my experience it's very rare that they do]
Rather than fetching plaintext/html with AJAX, i would recommend fetching JSON encoded info, and then parsing the returned JSON appropriately, e.g.
new test.php
$html=<<<EOT
<input type="button" value="Test Javascript" onclick="Test()"/>
EOT;
$js=<<<EOT
function Test(){
alert('javascript works');
}
EOT;
echo json_encode(array('html'=>$html,'js'=>$js));
new readystatechange function
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
try{
respJSON = new Object(xmlhttp.responseText);
javascriptDiv.innerHTML=respJSON.html;
eval(respJSON.js);
}catch (e){
//!!!
}
}
}
I think you can either define Test function in the parent document or just go like this:
<input type="button" value="Test Javascript" onclick="alert('javascript works');"/>
In your child document.
Append any HTML tag with display none which is created by using document.createElement or create hidden tag and append it to your file first.
Like this:
var d = document.createElement("hidden");
div.innerHTML = d + content;
It will work fine I tested.
I have the following code generating content on my site:
<div class="content" id="links">
<?php displayTitle("Links"); ?>
<?php displayContent("Links", $isLoggedIn); ?>
</div>
The content has a button that calls a Javascript function 'addLink()' to edit itself. Here is the Javascript with an Ajax call to change the content:
function addLink(){
var ajaxRequest; // The variable that makes Ajax possible!
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send(null);
}
'addLink.php' adds things to a table, theoretically allowing the content function 'displayContent()' to show the new entries in the table ('displayContent()' queries a table).
The PHP call works fine, but I have to refresh the page to see the changes.
Is there some problem with how I am doing this? Possibly because there are already PHP calls in the inner HTML when the page is loaded in the first place?
Any help is appreciated, I'm a bit of a beginner with Ajax.
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
Sorry a little correction. You are attempting to access the pre-ajax php scripts inside ajax callback function. That's not how it works. You want the data that is retrived after-ajax call. Ajax retrives the output from the GET request, and store in ajaxRequest.responseText. Try replacing that and then see what you get.
In your addLink.php you should add the link and then echo out the data that you wish to display as the responseText. What had happened is that you inject the data VIA addLink but you never actually display it on the client side VIA ajax correctly. However, when you refresh the page, the script retrives what has been injected and display it accordingly.