Access php function data via ajax - php

I have this php function inside a class the returns json data
function getPhotoDetails( $photoId ) {
$url = $this::APP_URL . 'media/' . $photoId . $this::APP_ID;
return $this->connectToApi($url);
}
and this ajax request
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php',
success: function (data) {
console.log(data);
}
});
}
The question is how I can call the php function to get the json data.
Solution:
A big thanks to all of you guys and thanks to Poonam
The right code
PHP:
I created a new object instance in php file
$photoDetail = new MyClass;
if(isset($_REQUEST['image_id'])){
$id = $_REQUEST['image_id'];
echo (($photoDetail->getPhotoDetails($id)));
}
JavaScript
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: './instagram.php?image_id=' + photoId,
success: function (data) {
var data = $.parseJSON(data);
console.log(data);
}
});
}

Try with setting some parameter to identify that details needs to send for e.g assuming photoid params needed for function
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php?sendPhoto=1&photoid=23',
success: function (data) {
console.log(data);
}
});
}
and then on index.php check (You can make check for photoid whatever you need as per requirement)
if(isset($_REQUEST['sendPhoto'])){
$id = $_REQUEST['photoid'];
return getPhotoDetails($id);
}

setup a switch-case. Pass the function name as GET or POST variable such that it calls the php function

You need a file which calls the PHP function. You can't just call PHP functions from Ajax. And as pointed out by Tim G, it needs to use the proper header, format the code as JSON, and echo the return value (if the function is not already doing these things).

Related

Yii2 how to access POST data that's been sent using AJAX

I want to create a variable within my controller function that equals the POST value however I am unsure on how to access the POST value.
An answer would be great but any tips for debugging would be great too.
I have tried $_POST['save_id'] as well as $_POST[0]['save_id']
$('#save-file').click(function() {
var fileid = $(this).data('fileid');
$.ajax({
type: "POST",
url: "/files/save",
data: { 'save_id' : fileid },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//do something
console.log(fileid);
alert("working");
},
error: function (errormessage) {
//do something else
alert("not working");
}
});
});
for your url if the code is inside a PHP file i suggest you a proper path eg :
url: <?=Url::to(['/files/save']) ?>,
(Remenber of add use use yii\helpers\Url;)
If not a php refer to the absolute path properly
inside your FilesController in save Action
public function actionSave()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
//data: { 'save_id' : fileid },
$mySaveId = $data['save_id']
// your logic;
......
}
}

Serialize() form in an existing ajax function

Actually the following function works fine, but now I need to add other variable in order to return from the php file the right statement.
function sssssss1(page) {
loading_show();
$.ajax({
type: "GET",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
$("#search").ajaxComplete(function (event, request, settings) {
loading_hide();
$("#search").html(msg);
});
}
});
}
I need to add the following two variable to be read by my php file. I have tried different solution, but nothing seem working
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
How to add those variable in my existing function? Any idea?
You can send object as data,
this line:
data: "page="+page,
could be
data: {mypage:"page="+page, form2:document.myform2, dataString1:$(form2).serialize()}
and your PHP can get it like:
$page = $_GET['mypage'];
$form2 = $_GET['form2'];
$dataString = $_GET['dataString1'];
Hope it Help.

Take html and variable with AJAX

I have this ajax code
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(html)
{
LastDiv.after(html);
}
});
I am new with this Ajax thing.
This code is to load getData.php file and send variables through type POST.
The variables are in this var ValueToPass = "lastid="+LastId+"&br="+br;.
Other thing this code does is return the getData.php's HTML after loading.
Probably with this. success: function(html)
How can I return this $br variable from getData.php after loading, so I can use it again through the next cycle. Cuz what happens here is that I can put the variable in the getData.php with the Ajax and working with it, but when the file getData.php is loaded, outside this file, the variable is not known(not declared). And I'm losing the counting :S
I want to return the HTML and the variable.
You can return json data in your php file like
$response = array ('br'=> $br, 'html'=> $html);
echo json_encode($response);
Here both html and data are returned.
And this to use it in your ajax callback :
success: function(data)
{
br = data.br;
LastDiv.after(data.html);
}
I'd consider setting a Session variable with the value from the $br variable passed via AJAX. Then when you call getData.php from another file or location, you can use the Session variable since session variables retain their value anywhere in the session.
You can try this to get the data from your `getData.php' :
$.ajax(
{
type: "POST",
url: "getData.php",
data: { ValueToPass: ValueToPass},
cache: false,
success: function(data)
{
LastDiv.html(data);
}
});
and in your getData.php you have to pass ValueToPass
maybe like this:
$ValueToPass = mysqli_real_escape_string($db, $_POST['ValueToPass']);
If I understand your question correctly, and if you want to return the $br variable then include it in a JSON object in the successs callback function. So, something like this (I'm not familiar enough with PHP so my PHP syntax might be incorrect):
// create JSON object
<?php
$result = array('br' => $br, 'html' => 'htmlContent);
echo json_encode($result);
?>
// return JSON object
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(result)
{
var $br = result.br;
LastDiv.after(result.html);
}
});

Returning the fetched data from a ajax call to another function

So I have this javascript function, it sends an ajax requests to fetch a value from a php variable.
The function looks like so:
function get_cart_limit() {
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
success: function(output) {
var cartlimit = output;
alert(cartlimit); // this gives me the correct value.
return cartlimit;
},
error: function(output){
}
});
}
When I call this function from another function like this:
var cartlimit = get_cart_limit();
my variable "cartlimit" is undefined.
So the ajax call is working, but why can't I return the value to another function?
To early for me, my brain isn't working properly! :)
Cheers!
If you change the scope of the cartlimit variable and disable Asynchronous request, get_cart_limit() should return the correct value
function get_cart_limit() {
var cartlimit;
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
async: false,
success: function(output) {
cartlimit = output;
},
error: function(output){
}
});
return cartlimit;
}
The variable cart_limit is only set once the AJAX request successfully terminates.
Why?
The AJAX call is asynchronous, i.e. get_cart_limit() ends before the actual answer comes back from the server
The anonymous function that you specified as success: function(output) { /*...*/ } is called when the answer comes back from the server.
If you call another function that tries to access cart_limit before the success function has been executed, you will get an undefined value.
Even if you execute a return statement in the success function, it is a different function from get_cart_limit() and it gets executed at a different time, so you will not obtain the desired effect of assigning the return value to whatever variable.
One to solve this problem is to have the function that needs cart_limit be called by the anonymous success function.
function get_cart_limit() {
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
success: function(output) {
var cartlimit = output;
alert(cartlimit); // this gives me the correct value.
function_that_needs_cart_limit();
},
error: function(output){
}
});
}
Declare this cartlimit with a global scope. Decalre this before the function starts
var cartlimit;
function get_cart_limit() {
$.ajax({
...................
Here your cartlimit will be declared only after the ajax function get success .
But execution of another scripts may take before this success. So it will get undefined
Your can pass your output data to the specified function like this
var cartlimit = get_cart_limit(output);

JQuery + Json - first steps with an example

I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";

Categories