how to write url in ajax request in codeigniter php? - php

i'm new to codeigniter i can't not get data from the controller using the ajax request i think i do mistake in writing the url of the controller function in ajax call
here is the code of my ajax call
$(document).ready(function(){
$("#fname").focusout(function(){
// alert();
$.ajax({
url: "<?php echo base_url();?>/proposal/ajax_load",
type: 'POST',
success: function(result){
$("#div1").html(result);
}
});
});
});
Here is my controller
class Proposal extends CI_Controller {
public function ajax_load()
{
return ("Hello");
}
}

You are confuse between the meaning of [Return, Echo] in PHP,
Echo
echo — Output one or more strings
Return
return returns program control to the calling module. Execution
resumes at the expression following the called module's invocation.
and as long as the Ajax response callback is reading a server response [output], you must send an output to the server.
public function ajax_load()
{
echo "Hello";
}
Further reading :-
What is the difference between PHP echo and PHP return in plain English?
Difference between php echo and return in terms of a jQuery ajax call
a short and simple answer

in ajax_load() - Should be echo not return if you're getting a response via ajax.

Related

Calling php function with ajax and passing return value to div

I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}

How do i get a php return value via Ajax?

Im creating a validation form in Ajax and PHP. But i don't have a clue how i should get the value from PHP??
For example:
The validation form is in index.php And the page with the function is checkUser.php.
In checkUser i have a global file included with my classes initialized. The checkUser.php look like this:
<?php
$requser = false;
require "core/rules/glb.php";
$user->checkUser($_GET['username']);
The get function comes from the Ajax call i do in the index file. But how do i know that PHP said that the username already exist så that i can make a if statement and paus the script?
Im a beginner, thanks.
And sorry for my english
$.ajax({
type: "GET",
url: "user_add.php",
data: 'username='+$("#jusername").val()+'&email='+$("#jemail").val()+'&password='+$("#jpassword").val()+'&secureSession=23265s"',
success: function()
{
location.href='register.php';
}
});
Jus print out the data, for better help also post the ajax script
<?php
$requser = false;
require "core/rules/glb.php";
print $user->checkUser($_GET['username']);
If you are trying to give a response to the ajax call from php, then you can do it via normal output. Just like
echo json_encode(array("status"=>"FAIL"));
exit();
will send a json response to the ajax call from the php script. like
{"status":"FAIL"}
which you can parse it at the ajax callback and check the status. like
var data = JSON.parse(response);
if(data.status == "FAIL") {
alert("Ajax call returned failed");
}

Contao 2.11 call to module via ajax

I have question about call to my module action via ajax.
I'd like call to class in my module via ajax. But best solution for me is call to clean class. Not extends Module.
I don't know hot can I make url without add article to database and add module to him.
I use JQuery instead mooTools but js framework is not important. Most important is call to php class by ajax.
I have ajax module. But if I call to ajax.php required is module id from tl_module table. I don't want use this table. (Ajax will be very often calling, I prefer to don't load all contao mechanism. It should be very fast).
Thanks in advance for answers.
I found the answer for Contao >3.x in a GitHub issuse(german)
At first do in your Front-end Template:
<script type="text/javascript">
var data = {};
data["REQUEST_TOKEN"] = "<?php echo REQUEST_TOKEN ?>";
$(document).ready(function(){
$("#trigger").click(function(event){
$.post(
'<?php echo \Contao\Environment::get('requestUri')?>',
data,
function(responseText) {
alert(responseText);
}
).fail(function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown )});
event.preventDefault();
});
});</script>
Important is the
- data["REQUEST_TOKEN"] -> if you do not add it, the POST-request will not reach your module:
public function generate()
{
if ($_SERVER['REQUEST_METHOD']=="POST" && \Environment::get('isAjaxRequest')) {
$this->myGenerateAjax();
exit;
}
return parent::generate();
}
//do in frontend
protected function compile()
{
...
}
public function myGenerateAjax()
{
// Ajax Requests verarbeiten
if(\Environment::get('isAjaxRequest')) {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array(1, 2, 3));
exit;
}
}
If you want to do the ajax via GET you do not need the reqest token but the jquery funktion $get();
I would suggest you to use Simple_Ajax extension.
In this case you dont need to use Database and you can do pretty much anything you can do normally with Jquery ajax calls.
It works with Contao 2.11 and you can call your php class with it.
I find it much easier to use than ajax.php .
You can get it from : https://contao.org/de/extension-list/view/simple_ajax.de.html
Copy SimpleAjax.php to Contao's root folder.
Go to [CONTAO ROOT FOLDER]/system/modules and create a php file like following :
class AjaxRequestClass extends System
{
public function AjaxRequestMethod()
{
if ($this->Input->post('type') == 'ajaxsimple' )
{
// DO YOUR STUFF HERE
exit; // YOU SHOULD exit; OTHERWISE YOU GET ERRORS
}
}
}
Create a folder called config with a php file like following ( You can hook you class to TL_HOOKS with class name - class method, simple_ajax will execute you method whenever a ajax call is made ):
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('AjaxRequestClass','AjaxRequestMethod'); // Klassenname - Methodenname
Now you can easily make ajax calls with simply posting data to SimpleAjax.php:
$.ajax({
type: "POST",
url: "SimpleAjax.php",
data: { type: "ajaxsimple" },
success: function(result)
{
//DO YOUR STUFF HERE
}

how to make ajax request from javascript for core php function

i am working on a core php project in which i want to call php function from javascript using ajax call request.i tried this but its not work.
js file:
$.ajax({
type: "POST",
data: data,
url:"/rootfolder/subfolder/action.php/test",
success:function(response)
{
if(response == 'true')
{
window.location.assign("home.html");
}
else
{
alert("wrong credencials");
}
},
failure:function(response)
{
alert("there is an error.");
}
});
php file:
<?php
include("../connection.php");
function test()
{
//some stuff
}
?>
please suggest some solution or provide any refrence.thanx in advance.
You can't call a PHP function from JavaScript. You can only make an HTTP request. That HTTP request might be handled by a PHP program. There is no built-in PHP feature that will let you specify a particular function to call.
You can examine $_SERVER['PATH_INFO'] to determine what data is in the URL after the script name and use that to determine what the PHP program should do.
if ($_SERVER['PATH_INFO'] === "test") {
test();
}
you have declared the test function but haven't called it, I think the error is from the php side.
<?php
include("../connection.php");
test();//call the function
function test()//this is just function decleration
{
//some stuff
}
?>
Just use a URL variable called method
/subfolder/action.php?method=test
And then in your PHP use that variable to call the function
<?php
$function = $_GET['method'];
$function();
function test()
{
//some stuff
}
......
?>
There could be other solutions too...

jquery ajax calling a method

I am using a class to do some CRUD stuff on a database, this one (http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql) I am going to use jquery to check the if the username has been registered already.
I could just create a php file specifically for that task, but would just like to extend the class and create a method callled checkname().
How can I call this in jquery?
You can use jQuery to make ajax call to a php file following:
PHP [suppose, test.php]
<?php
class ABC extends XYZ {
public function checkname() {
if(isset($_POST) && !empty($_POST['name'])) {
echo json_encode(array('status' => 'done'));
}
}
}
$ins = new ABC();
$ins->checkname(); // calling the function checkname
?>
jQuery:
$.ajax({
url: 'test.php', // write the url correctly
type: 'post',
data: "name=XYZ&location=PQR"
}).done(function(response) {
console.log(response.status); // will log done
}).fail(function(jqXHR, textStatus) {
console.log("Failed: " + textStatus);
});
It is just an example.
You'll need to use jQuery's Ajax functionality to access a PHP page that calls that function. You can't directly call a PHP function via Ajax, something on the backend has to be set up.

Categories