AJAX request and PHP class functions
Then in my ajax.php file I have an ajax request, need to get values from getName function How to do that getName() function can I do like this?
What you’ve started with looks fine, now you just need a page that echo es getName() when the URL animal/getName is requested.
9 Answers 9
My answer is the same as Surreal Dreams answer, but with the code.
First. Class animal is OK. Leave it like that:
Next. Create a new animalHandler.php file.
Finally. Change your Javascript.
thanks guys but my problem is if i have to use 50 ajax requests i have to use 50 php files for outputting those results. my doubt is whether i can use all those functions in to a single class called ajax then it will be great for me. but i have been using the same in codeigniter framework. if i can do the same in normal php with classes that would be great. just i want to know if that possible in php.
You can use one ajax.php file to handle all the ajax calls, but beware: It will be big and unmaintenable.
Make a function that works for multiple cases, and use some parameter to access the one you want to retrieve.
It’be so awesome if in jquery 3.4.. it could become like $.post ( ajaxurl, < 'action': 'classname/foomethod', 'data': . ))
You need one additional script, because your animal class can’t do anything on its own.
First, in another script file, include animal.php. Then make an object of the animal class — let’s call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.
Use this new script as the target of your Ajax request instead of targeting animal.php.
ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)
OOP Currently with DotNet:
ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)
My real-life solution: Do OOA, do not OOP.
So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).
; //modify if($_POST["mode"]=="modify") < $cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'"; $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); >; //erase if($_POST["mode"]=="erase") < $cadena="delete from mytable where code='".$_POST['txtmytablecode']."'"; $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); >; // comma delimited file if($_POST["mode"]=="get") < $rpta=""; $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); while($row = mysql_fetch_array($rs)) < $rowCount = mysql_num_fields($rs); for ($columna = 0; $columna < $rowCount; $columna++) < $rpta.=str_replace($row[$columna],",","").","; >$rpta.=$row[$columna]."\r\n"; > echo $rpta; >; //report if($_POST["mode"]=="report_a") < $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); while ($row=mysql_fetch_array($rs)) < echo $row['code']." ".$row['name']."
"; // colud be a json, html >; >; //json if($_POST["mode"]=="json_a") < $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); $result = array(); while ($row=mysql_fetch_array($rs)) < array_push($result, array("id"=>$row['code'],"value" => $row['name'])); >; echo json_encode($result); >; ?>
Can you please mention which are you using any Framework? You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don’t use return, in *success: function(data) * data will contain only the output. so use Echo rather then return
For what it is worth, I have used a PHP proxy file that accepts an object as a post — I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.
class; // class: String - the name of the class (filename must = classname) and file must be in the include path $method = $data->method; // method: String - the name of the function within the class (method) @$params = $data->params; // params: Array - optional - an array of parameter values in the order the function expects them @$type = $data->returntype; // returntype: String - optional - return data type, default: json || values can be: json, text, html // set type to json if not specified if(!$type) < $type = "json"; >// set params to empty array if not specified if(!$params) < $params = array(); >// check that the specified class is in the allowed classes array if(!in_array($class,$allowedClasses)) < die("Class " . $class . " is unavailable."); >$classFile = $class . ".php"; // check that the classfile exists if(stream_resolve_include_path($classFile)) < include $class . ".php"; >else < die("Class file " . $classFile . " not found."); >$v = new $class; // check that the function exists within the class if(!method_exists($v, $method)) < die("Method " . $method . " not found on class " . $class . "."); >// execute the function with the provided parameters $cl = call_user_func_array(array($v,$method), $params ); // return the results with the content type based on the $type parameter if($type == "json") < header("Content-Type:application/json"); echo json_encode($cl); exit(); >if($type == "html") < header("Content-Type:text/html"); echo $cl; exit(); >if($type == "text") < header("Content-Type:text/plain"); echo $cl; exit(); >> else < die("Invalid request."); exit(); >> else < die("Nothing posted"); exit(); >?>
To call this from jQuery you would then do:
var req = <>; var params = []; params.push("param1"); params.push("param2"); req.class="MyClassName"; req.method = "MyMethodName"; req.params = params; var request = $.ajax(< url: "proxy.php", type: "POST", data: JSON.stringify(req), processData: false, dataType: "json" >);
Can I call the function from php class using jquery ajax?
I begin with an object-oriented programming in php. I want to do the logging — using ajax and jquery. EDIT: Can I call the function ajax from file jquery.php — using jquery AJAX?
//FILE jquery.php class jquery < public function ajax() < echo "result"; >>
You cannot call a PHP class with AJAX — but you can get the result of an execution. For the AJAX part the programming paradigm is irrelevant.
Yes, you could make this work, but I suggest to first learn the basics about Ajax and PHP before you implement any critical code.
@FelixKling Check please my edit. Can you give me example? how can i call the function from php class using jquery ajax?
You can not do this directly. You’ll have to parse an incoming ajax request and according to the data within the request you can call the php function.
3 Answers 3
If you make an ajax call similar to this :
Within your ajax.php file you can do something like this :
This is a very stripped down example. In a real world case you would have to take security into account and sanitize any information you are getting from outside your server (i.e. from a user).
The names I have given are only place holders — you can change the function/variable names to whatever you feel comfortable with.
I hope this sheds some light on your conundrum.
Not sure if you completely understand what AJAX is, but it’s an acronym for Asynchronous JavaScript and XML. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behaviour of the existing page. That’s it.
This I believe is what you’re looking for (though its not OOP, but im not writing an entire OOP login to try answer your question)
prepare('SELECT user_id, user_activated FROM users WHERE ( username = AND user_password = ? LIMIT 1'); $stmt->execute( array( $_POST['u'], $_POST['p'] ) ); if( $stmt->rowCount() == 1 ) < // Authentication session storage stuff here echo 'Logged in'; >else < echo 'bad login'; >?>
So you could have a HTML page with something like:
Also, keep in mind this code is un-tested and written it as replying to this, so don’t treat this as a solution to what you’re wanting, but rather a resource to help you to implement what it is you’re asking for.
Ajax call method from class php
Can i use ajax to call a class method (myMetod(2,3)) and with the return to do someting? Can i use it like this?
$.ajax( < url : 'myClass.php', data : < someData: '2,3', >type : 'POST' , success : function(output) < alert(output) >>);
2 Answers 2
You need to create php script that calls this class method and can be called as ajax request. Create a file like:
myMethod( $_POST['field1'], $_POST['field2'] ); $obj->myMethod2( $_POST['field1'] ); ?>
And change your jQuery code to:
$.ajax(< url : 'path/to/myfile.php', data : < someData: '2,3' >, type : 'POST' , success : function( output ) < alert(output) >>);
Can I use ajax to call a class method (myMetod(2,3)) and with the return to do something?
since calling the class method needs the initialization of the object in your myClass.php you need to instantiate the class and pass the proper input, and if the class method is to return some output just echo it.
for example. from your ajax call if you want to call myMethod then in your myClass.php
//Check for ajax request to instantiate the class. if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') < $object = new MyClass(); //hold the return value in a variable to send output back to ajax request or just echo this method. $result = $object->myMethod($_POST['value'], $_POST['value2']); echo $result; >
call javascript/ajax function from php
i have a little problem here!! after i submit my form, based on php response i want to execute another javascript or ajax function! this is my form:
Enter video title:
Enter video description:
Enter some tags to describe your video (separated by spaces):
ytVideoApp.prepareSyndicatedUpload = function(videoTitle, videoDescription, videoCategory, videoTags)
ytVideoApp.sendRequest = function(filePath, params, resultDivName) < if (window.XMLHttpRequest) < var xmlhr = new XMLHttpRequest(); >else < var xmlhr = new ActiveXObject('MSXML2.XMLHTTP.3.0'); >xmlhr.open('POST', filePath); xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhr.onreadystatechange = function() < var resultDiv = document.getElementById(resultDivName); if (xmlhr.readyState == 1) < resultDiv.innerHTML = 'Loading. '; > else if (xmlhr.readyState == 4 && xmlhr.status == 200) < if (xmlhr.responseText) < resultDiv.innerHTML = xmlhr.responseText; >> else if (xmlhr.readyState == 4) < alert('Invalid response received - Status: ' + xmlhr.status); >> xmlhr.send(params); >
I tried with: echo «» not working print «alert(‘something’);»; not working any 1 can help me? thanks!