Calling a javascript function with ajax - php

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>

Related

jquery will not work in file retrieved by java select include

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);
}
}
}

How to fetch data from mysql database while scrolling

I have a database and it contains more than 1000 records. I have to display it in front end php page, if I display all it will take more time to load so if user scrolls the information should be fetched after scrolling. Just like Facebook and Pinterest. How to achieve this...
My DB :- mysql
Server :- wamp
step 1] Take a help of little bit jquery as....
var countScroll= 0;
$(window).scroll(function()
{
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
loadData();
}
countScroll++;
});
step 2] Take the help of ajax to call the loadData() function
function loadData()
{
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 res = xmlhttp.responseText;
document.getElementById("respDiv").innerHTML=res;
}
}
xmlhttp.open("GET","loadPageData.php?loadLimit="+countScroll,true);
xmlhttp.send();
}
step 3] your php page i.e. loadPageData.php is as...
$loadLimit= $_GET['loadLimit'];
$result = mysql_query("SELECT * FROM tableName limit $loadLimit");
if(mysql_num_rows($result)>0)
{
while($row = mysql_fetch_array($result))
{
echo $yourVariable= $row['fieldName'];
}
}
Your question is generic and difficult to answer with snippet of code.
This could be a solution in pseudo-language
Fetch a default number of element (say 50) by doing a query like this SELECT * FROM yourTable WHERE ..... ORDER BY .... LIMIT 50
Use jQuery to detect scroll event
Make an AJAX call once you detect scroll event
Make a new query where you fetch 50 elements again, but this time take into account that you have scrolled (so, add a delta or offset)
Render elements returned from AJAX
Use jQuery (or your favourite library) to detect when the user gets to the end of the page, then just trigger an AJAX request to the server for the next N results.
For example:
JavaScript part:
var n = 0;
$(document).ready(function() {
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
$.ajax({
url: "my_page.php",
data: {'n' : n},
context: document.body
}).done(function(data) {
n += 1;
console.log(data); // <--- do stuff with received data here
});
}
});
});
PHP part:
$n = $_POST['n'];
$n = 10 * $n;
$sql = "SELECT * FROM mytable LIMIT $n, 10"; // get 10 new entries each request.

Auto-save textarea every so many seconds

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

Display Multiple Records From SQL Query Using AJAX with Timer

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()">

PHP Javascript AJAX fill and calculate several input fields - only one function fills?

I am trying to fill in a form using Javascript/ajax/php but the problem is that my function only fills in one of the needed forms and stops even tho I have gotten the second response from the server.
Code:
The function that starts filling stuff
function luePankkiviivakoodi(str) {
if (str==null) { //are we NOT injecting variables directly into the code, if not - Prompt for the barcode, and set the variable
var str = prompt("Valmis vastaanottamaan", "");
}
if (str==null) { //someone pressed abort on the prompt, we return
return;
}
newstr = str.split(' ').join(''); // remove spaces
if (str=="") { //is the string empty? -> return
return;
}
if (window.XMLHttpRequest) { //AJAX code
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
//we set some fields, no problem
document.getElementById('P_VII').value = viite;
document.getElementById('IBAN').value = saajatili;
document.getElementById('laskun_summa').value = summa;
document.getElementById('eräpäivä').value = eräpäivä;
//trigger other functions
getKassasumma(summa); //AJAX for accesing the database and calculating the sale price
DevideIntoCells(); //AJAX for accessing the database and dividing a sum into different cells
validateSumma(); //Validates the sum, and tells the user if it's OK
}
}
xmlhttp.open("GET","dataminer.php?question=pankkiviivakoodi&q="+newstr,true);//open AJAX connecttion
xmlhttp.send();//send stuff by AJAX
}
getKassasumma:
function getKassasumma(str) {
if (str=="") {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
}
}
kale = document.getElementById("TOS_K_ale").value;
xmlhttp.open("GET","dataminer.php?question=kassasumma&q="+str+"&kale="+kale.replace("%", "p")+"&nro="+document.getElementById("S_NRO").value,true);
xmlhttp.send();
}
DevideIntoCells:
function DevideIntoCells() {
str = document.getElementById('tiliöintitapa').value;
if (str==null) {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
document.getElementById("spinwheel3").style.visibility = "visible";
}
xmlhttp.onreadystatechange=function() {
//alert('OK! val= '+xmlhttp.readyState);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//alert('OK!');
eval(xmlhttp.responseText);
//alert('OK2!');
document.getElementById("spinwheel3").style.visibility = "hidden";
//alert('OK3!');
calculateSumma();
}
}
xmlhttp.open("GET","dataminer.php?question=percentages&q="+str+"&nro="+document.getElementById('S_NRO').value,true);
xmlhttp.send();
}
validateSumma (just some math):
function validateSumma() {
float = document.getElementById('summabox').value;
float = float.replace(",",".");
summa = parseFloat(float);
if (summa < 0) {
summa = 0
};
kassasummaunp = document.getElementById('laskun_summa').value;
kassasummafloat = kassasummaunp.replace(",",".");
kassasumma = parseFloat(kassasummafloat);
if (kassasumma < 0) {
kassasumma = 0
};
if (kassasumma == 0 || summa == 0) {
prosentti = "0%";
}
else {
prosentti = summa / kassasumma * 100;
prosentti = Math.round(prosentti*Math.pow(10,2))/Math.pow(10,2);
prosentti = prosentti+"%";
};
if (prosentti == "100%") {
is100 = 1;
}else {
is100 = 0;
}
document.getElementById('prosentti').innerHTML = prosentti;
if (is100 == 1) {
document.getElementById('prosentti').setAttribute("style", "color:green");
} else {
document.getElementById('prosentti').setAttribute("style", "color:red");
}
puuttuvaEuro();
}
The problem code here is getKassasumma(summa); and DevideIntoCells();. I disable one of them, and the other one works, I enable both of them, DevideIntoCells stops somewhere before document.getElementById("spinwheel3").style.visibility = "hidden";, probably at the eval(response) because getKassasumma already finished the ajax request and killed this one. same the other way around.
AJAX answers: DevideIntoCells:
var KP_osuus = parseFloat('40');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box1.5').value = newvalue;
var KP_osuus = parseFloat('60');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box2.5').value = newvalue;
AJAX answer: getKassasumma
var kassasumma = '477.99€';
document.getElementById('kassasumma').value = kassasumma;
Please ask if you need clarification!
EDIT: Just to be clear, this is NOT an AJAX problem, rather javascript.
I think you are 'swimming in it', how we say. If you begin with AJAX, I'd recommend you use a framework like jQuery and it's $.get() or $.post() functions. It will accomplish all the needed AJAX logic for you.
Try to make xmlhttp local, i.e.
var xmlhttp;
Because you are overwriting you xmlhttp you refer to in the event listeners, so when the listeners get called, they both see the same response.
at the beginning of every of your functions. For compatibility, also use send(null) instead of send().

Categories