How to call a PHP class method from a JavaScript function [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Call php function from javascript
I understand that php is server side and JavaScript is client side. But I would like to know how to run a PHP method when a JavaScript function is called. Below is my code, I know the error is but how can I perform the php method?
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
<?php Category::addCategory($inCatName)?>
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
Thanks for your help.

Using the Prototype library (www.prototypejs.org):
Javascript:
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var options={
method: 'get',
parameters: 'inCatName='+ele.value,
onSuccess: function(xhr) {
// TODO: Whatever needs to happen on success
alert('it worked');
},
onFailure: function(xhr) {
// TODO: Whatever needs to happen on failure
alert('it failed');
}
};
new Ajax.Request('addCategory.php', options);
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
addCategory.php:
<?php
$inCatName=isset($_REQUEST["inCatName"]) ? $_REQUEST["inCatName"] : null;
Category::addCategory($inCatName);
?>
The idea is that the Javascript sends a GET (or it could be POST) request to the addCategory.php page behind the scenes, passing it whatever info it needs to create the category.
Hopefully this is enough to get you going. There's a lot missing from my code - you'll need to validate the variables addCategory.php receives and perform any other pertinent security checks before letting it anywhere near the database. addCategory.php will also require any include files, etc so that it knows about your Category class. Finally, addCategory.php should really return some form of variable back to the Javascript code that called it so that it knows what the outcome was.

You can use an Ajax request to an endpoint that triggers your PHP and then perform Category::addCategory($inCatName)
With Jquery:
$.ajax({
url: "addCategory.php",
context: document.body,
success: function(){
// whatever you need to do
}
});

This might help. Use ajax to call you php file (categories.php was used in the example). Send a parameter called "function" and set it as "addCategory". In your php file write code to detect if $_GET['function'] is set and also to detect if it is set as "addCategory". If it is, have the code call the function. I also saw that you were trying to pass the $inCatName parameter to the php function. To send this just add it into the url below.
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","categories.php?function=addCategory",true);
xmlhttp.send();
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>

Related

how can I constantly refresh an individual div conserving the id of the post?

I am doing a blog with PHP, AJAX, MySQL, etc. As usual, each post has its ID and inside the posts you can see the comments.
What I am trying to do is refresh the comment's div by calling the comments.php document with AJAX and putting it in the div with $('#comments').html(data);.
Doing this every 5 seconds for maintaining the comments like in real time, but the problem is that when the div does the first refreshing, the div loses the ID of the post and say that is undefined.
How can I refresh any div without losing the ID of the post?
If I call the comments.php file with the typical include(file.php) inside of the post file, I have no problem, but using this way I just can't refresh the content.
Here's the code:
post.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'support/comments.php',
success: function(data) {
$('#comments').html(data);
}
});
});
</script>
div where the result is going to be showed:
<div id="comments">
</div>
Script for refreshing the div:
<script language="Javascript" type="text/javascript">
function refreshDivs(divid, secs, url) {
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("your browser doesn't support ajax.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function () {
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
window.onload = function startrefresh () {
//update content on real time
refreshDivs('comments',10,'support/comments.php');
}
</script>
You can pass the post id in the URL, like so:
url: 'support/comments.php?id=<?= $post_id ?>'
Then wrap the call with a setTimeout, like so:
window.setInterval(function(){
$.ajax({
url: 'support/comments.php?id=<?= $post_id ?>',
success: function(data) {
$('#comments').html(data);
}
});
}, 5000);
And discard refreshDiv.
This is assuming that comments.php retrieves the comments, and some other code posts them.
ok guys I solved it... I am gonna leave the code here in case of somebody could has the same problem... what I did was build a hidden input and put this input to use its value like the id of the post, then I sent the value of this input to the script with #('div').val and finally I sent that value to the comments.php file, once there.... I used the value in the query sentence for doing the comparative and finally can get the comments in the right post
Here's the code
<script>
$(document).ready(function() {
window.setInterval(function(){
//Comentarios
var id = $("#idcomment").val();
$.get("support/comments.php", { idpost: id }, function(LoadPage){
$("#comment").html(LoadPage);
});
}, 5000);
});
</script>

script within a php page not executed when called using ajax

Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}

PHP & MySql and Ajax auto-suggest issue

I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>

Javascript in a Included PHP File

I have a php file (a form) that includes javascript to check if all inputs are filled. When I view the php file directly the js works perfectly, but when I include the PHP file in another page the javascript no longer works.
My javascript code:
<script type="text/javascript" src="../js/modernizr.js"></script>
<script type="text/javascript">
window.onload = function(){
document.getElementById("topField").setAttribute("autocomplete","off");
}
window.onload = function() {
// get the form and its input elements
var form = document.forms[0],
inputs = form.elements;
// if no autofocus, put the focus in the first field
if (!Modernizr.input.autofocus) {
inputs[0].focus();
}
// if required not supported, emulate it
if (!Modernizr.input.required) {
form.onsubmit = function() {
var required = [], att, val;
// loop through input elements looking for required
for (var i = 0; i < inputs.length; i++) {
att = inputs[i].getAttribute('required');
// if required, get the value and trim whitespace
if (att != null) {
val = inputs[i].value;
// if the value is empty, add to required array
if (val.replace(/^\s+|\s+$/g, '') == '') {
required.push(inputs[i].name);
}
}
}
// show alert if required array contains any elements
if (required.length > 0) {
alert('The following fields are required: ' +
required.join(', '));
// prevent the form from being submitted
return false;
}
};
}
}
</script>
This is an explanation to anyone who finds this question later. In javascript you can only attach a single function to an event handler. If you want to attach more, you need to chain them. Pretty much all javascript framework/libraries has some sort of method to handle event chaining.
Javascript allows you to treat functions like variables. So you can assign an old onload function to a variable, then call it later within the new onload function.
If you are not using a framework, you can do something like this to handle event chaining.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
You would call this with the following:
addLoadEvent(function(){
// Some code here
});

How to call multiple AJAX functions (to PHP) without repeating code

I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.

Categories