I have a simple form that that when changed includes a php file in a div. For some reason jquery will not load when placed in that included file? Can someone tell me why this doesnt work.
<select name='make' onChange='show(this.value)'>
<option value='some-file.php'>the file</option>
</select>
<div id="make">Where the file is loaded and where jquery wont work</div>
<script type="text/javascript">
function show(str)
{
if (str=="")
{
document.getElementById("make").innerHTML="";
return;
}
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("make").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","include/some-file.php?q="+str,true);
xmlhttp.send();
}
</script>
Then some-file.php
$models = mysql_query("SELECT model, id FROM model where make like '%".$q."%' order by model asc") or die(mysql_error());
//Puts it into an array
$count = 1;
$max = 3;
while($model = mysql_fetch_array( $models ))
{
if($count%20==1)
echo '</ul><ul style="float:left; padding:0; margin-right:10px;" class="makesModels">';
echo "<li style='padding-right:5px; display:block;'><font color='#fe9000'>".$count.".</font> ".$model['model']." <a class='delete-model".$model['id']."'>x</a></li>";
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.1.min.js'></script>
<script type='text/javascript'>
$(docuument).ready(function() {
$(".delete-model<? echo $model['id'];?>").click(function() {
alert("delete");
});
});
</script>
$count++;
}
?>
i've had the same exact problem ...
to solve this all you need to do is edit the ajax from using normal JavaScript to $.ajax so use jQuery to handle it .. and it will work ..
$.ajax({
url: "include/some-file.php?q="+str,
type: "GET",
datatype: 'html',
success: function(e){
$('#make').html(e);
}
});
I'm not sure about it, because the code is not complete, my guess would be that on someotherphpfile that you are importing you use document.ready function which is not calling because you load the file using ajax.
scripts loaded with ajax or in general a script string injected in the DOM will not execute for security reasons
you can use eval to get it working although i must warn you that you could be opening a can of worms..
after document.getElementById("make").innerHTML=xmlhttp.responseText; add this..
var parent = document.getElementById('make');
var myScript = parent.getElementsByTagName('script');
for(var i=0,len=myScript.length; i<len; i++){
executeScrpt(myScript[i]);
}
then the execute function...
function executeScrpt(scrpt){
if(scrpt.innerHTML != ""){
eval("("+script.innerHTML+")");
} else {
if(scrpt.src != ""){
var myScrpt = document.createElement("script");
myScrpt.src = scrpt.src;
document.head.appendChild(myScrpt);
}
}
}
Related
I'm using a multiselect dropdown to filter images stored in my db. The results are paginated, however the pagination fails once the results are filtered. The filter uss ajax to make a php call to the database.
What I think is happening is that the once the results are loaded in the div the paginate javascript function has already fired and wont a second time. Is there a way to call the function everytime the results are filtered?
I believe I just need to recall this each time:
<script type="text/javascript">
jQuery(function($){
$('ul#items').easyPaginate({
step:6
});
});
</script>
Ajax call:
<script>
function filterResults(sel)
{
var selectedOptions = [];
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected) {
selectedOptions.push("'" + sel.options[i].value + "'");
}
}
if (selectedOptions.length == 0) {
document.getElementById("divResults").innerHTML="";
return;
}
str = selectedOptions.join(",");
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("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter_ajax.php?filter="+str,true);
xmlhttp.send();
}
</script>
ajax_filter.php:
<?php
include ("connect.php");
$filter = $_GET["filter"];
$filterIn = $filter;
$result = mysql_query("SELECT * FROM edt_images
WHERE category1 IN ($filterIn)
OR category2 IN ($filterIn)
OR category3 IN ($filterIn)
OR category4 IN ($filterIn)
OR category5 IN ($filterIn)
OR category6 IN ($filterIn)")
or die(mysql_error());
echo "<div id='results_container'>";
echo "<ul id='items'>";
while ($row = mysql_fetch_array($result)) {
echo "<li><img src='files/300x200/thumb2_".$row['item_name'].".".$row['file_extension']."' class='filtered_images' border='0'/></li>";
}
echo "</ul>";
echo "</div>";
?>
If you are using jQuery you can simplify the code within the filterResults function greatly by utilizing the framework it provides. I would read up a bit here as you will be amazed by the extensive functionality.
This code is the jQuery equivalent of your previous code,
function filterResults(sel) {
var selectedOptions = [];
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected) {
selectedOptions.push("'" + sel.options[i].value + "'");
}
}
if (selectedOptions.length == 0) {
$("divResults").html("");
return;
}
filteStr = selectedOptions.join(",");
$.ajax({
url: "http://www.google.com",
type: "get",
dataType: "html",
data: {
filter: filteStr
},
success: function (responseHtml) {
$("divResults").html(responseHtml);
//You can put your code here
$('ul#items').easyPaginate({
step: 6
});
},
error: function (responseHtml) {
//Handle error
}
});
}
To answer the question the code within the success callback of the ajax call will be executed upon a receiving the data back from the server. This code above should work as expected.
Almost everything to know lies here and here. ;)
Well
According to the comments I'll have to study up on javascript and jquery, never really was to concerned with it before.
Anyways by recalling the javascript function
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
RESTATING HERE
}
I was able to get it working.
Put javascript call into your php-ajax echo, example:
<?
$msg = "hello";
?>
<script type="text/javascript">alert("<?=$msg?>"></script>
I am trying to retrieve an xml file from the server via ajax, but cannot get it to parse. I do not know what I am doing wrong. When I call the getFriends.php, it prints the xml fine. here is the ajax code:
<!DOCTYPE>
<html>
<head>
<title>Ajax Sample</title>
<script type="text/javascript">
function getFriendsList(MemberId) {
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) {
var xmlDoc = xmlhttp.responseXML;
var friendElements = xmlDoc.getElementsByTagName('friend');
for (var x=0; x<friendElements.length; x++) {
// We know that the first child of show is title, and the second is rating
var id = showElements[x].childNodes[0].value;
var name = showElements[x].childNodes[1].value;
// Now do whatever you want with the show title and ratings
document.write("hi");
}
}
}
xmlhttp.open("POST","getFriends.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("id=" + MemberId);
}
</script>
</head>
<body>
<input name="ajax" type="button" onClick="getFriendsList(1)" value="Click for AJAX">
<div style="background-color:#00FF99;" id="placehere">Here is where the update will occur.</div>
</body>
</html>
and here is the getFriends.php code (user class works fine):
<?php
include('lib.php');
//$id = $_POST['id'];
$id=1;
$user = new User($id);
echo $user->getFriendsList();
?>
You have undefined variable 'showElements' in your for loop. These two lines:
var id = showElements[x].childNodes[0].value;
var name = showElements[x].childNodes[1].value;
should be replaced with:
var id = friendElements[x].childNodes[0].value;
var name = friendElements[x].childNodes[1].value;
using jquery to perform ajax calls is easy and hassle free see http://api.jquery.com/jQuery.ajax/ for more info
I need help with "auto-saving" a textarea. Basically, whenever a user is typing in the textarea, I would like to save a "draft" in our database. So for example, a user is typing a blog post. Every 15 seconds I would like for the script to update the database with all text input that was typed into the textarea.
I would like for this to be accomplished thru jQuery/Ajax but I cannot seem to finding anything that is meeting my needs.
Any help on this matter is greatly appreciated!
UPDATE:
Here is my PHP code:
<?php
$q=$_GET["q"];
$answer=$_GET["a"];
//Connect to the database
require_once('mysql_connect.php') ;
$sql="UPDATE english_backup SET q".$q."='".$answer."' WHERE student_id = {$_COOKIE['student']} LIMIT 1";
$result = mysqli_query($dbc, $sql);
?>
Here is my javascript code:
<script type="text/javascript">
function showUser(str, answer)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser_english.php?q="+str+"&a="+answer,true);
xmlhttp.send();
}
</script>
function saveText() {
var text = $("#myTextArea").val();
// ajax call to save the text variable
// call this function again in 15 seconds
setTimeout(saveText, 15000);
}();
I think you want something like ajax... I'm using ajax jQuery so you will need jQuery Library for it to work. Download it. You can find tutorials on the documentation tab of the website.
//in your javascript file or part
$("textarea#myTextArea").bind("keydown", function() {
myAjaxFunction(this.value) //the same as myAjaxFunction($("textarea#myTextArea").val())
});
function myAjaxFunction(value) {
$.ajax({
url: "yoururl.php",
type: "POST",
data: "textareaname=" + value,
success: function(data) {
if (!data) {
alert("unable to save file!");
}
}
});
}
//in your php part
$text = $_POST["textareaname"];
//$user_id is the id of the person typing
$sql = "UPDATE draft set text='".$text."' where user_id='".$user_id."'"; //Try another type of query not like this. This is only an example
mysql_query($sql);
if (mysql_affected_rows()==1) {
echo true;
} else echo false;
Hey everyone I'm still having a problem please see here https://stackoverflow.com/questions/10050785/php-parse-html-using-querypath-to-plain-html-characters-like-facebook-twitter
I'm trying to find a good example on how to retrieve records using PHP from a table and refresh it say every 2 minutes using Ajax.
Anyone can point me to that tutorial?
I don't think you'll find a tutorial that specific, but you just need to learn AJAX and then make the AJAX call every two minutes using JavaScript's setInterval method.
EDIT
Meh, I'm bored enough to write this example. This isn't tested, but I don't think it has errors.
<html>
<head>
<script type="text/JavaScript">
window.onload = function()
{
// call your AJAX function every 2 minutes (120000 milliseconds)
setInterval("getRecords()", 120000);
};
function getRecords()
{
// create the AJAX variable
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// set up the response function
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
/*
Your code goes here. 'xmlhttp.responseText' has the output from getRecords.php
*/
document.getElementById("txaRecords").innerHTML = xmlhttp.responseText;
}
}
// make the AJAX call
xmlhttp.open("GET", "getRecords.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<textarea id="txaRecords"></textArea>
</body>
</html>
This is a bit of code that I wrote for this exact purpose. Adapt as appropriate.
AJAX code:
function timer()
{
var t=setTimeout("check()",2000);
// At an appropriate interval
}
function check(){
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)
{
if (xmlhttp.responseText!=""){
var output = xmlhttp.responseText;
// Do what you need to do with this variable
}
}
}
xmlhttp.open("GET","backend.php",true);
// Set file name as appropriate.
xmlhttp.send();
timer();
}
PHP code:
<?php
// This assumes you have already done mysql_connect() somewhere.
// Replace as appropriate
$query = "SELECT * FROM table_name";
// Perform the query
$result = mysql_query($query);
// Get the results in an array
while($row = mysql_fetch_array( $result )) {
// Echo the message in an appropriate format.
echo "<br />" . $row['column_name'];
}
?>
Remember to initiate one of the JS functions as you load the page:
<body onload="timer()">
I have a page called getvalues.php, I need to call a function which is written in a different php page(fileclass.php) in a class from this page(getvalues.php), but the issue is i need to pass a variable also which is $i, and the value of $i passed should be 1 if we are selecting option B, and $i=2 if option=c, and $i=3 if option=D given in dropdown. I had simply wiritten an onchange event but had not written any code in javascript. Please help Thanks. Here is the code for getvalues.php
<html>
<select id="s" onchange="callsome();">
<option value='B' selected>B</option>
<option value='c'>c</option>
<option value='D'>D</option>
</select></html>
<?php include("fileclass.php")
$obj=new file;
echo $obj->func($i);?>
You could implement this using JQuery or Javascript (I use JQuery in the example because it is shorter and easier to make Ajax calls) :
<html>
<select id="s" onchange="callsome();">
<option value='1' selected="selected">B<option>
<option value='2'>C</option>
<option value='3'>D</option>
</select>
<script>
function callsome() {
var selected = $('select#s option:selected').val();
$.ajax({
type: "POST",
url: "fileclass.php",
data: ({selectedvalue : selected}),
success: function(data) {
alert(data);
}
});
}
</script>
</html>
After that the callsome returns the output of the fileclass.php script and you can use that however you like in your code. From your explanation it was not really clear what is happening in fileclass.php and what you want to do with it, so I hope it helps you.
If you want the function in Javascript only:
<script type="text/javascript">
function callsome() {
var e = document.getElementById("s");
var strVal = e.options[e.selectedIndex].value;
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) {
var data = xmlhttp.responseText;
//use the data as you wish
}
}
xmlhttp.open("GET","fileclass.php?selectedvalue=strVal",true);
xmlhttp.send();
}
</script>
This isn't the way PHP and HTML work.
PHP is rendered on the server. HTML is rendered on the client, after the PHP is completely done. To do what you want to do, you need to have the HTML (possibly Javascript) make a request to the PHP page at fileclass.php.