Take html and variable with AJAX - php

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

Related

Passing Back multiple PHP variables after a ajax Form Call

I am passing a file to a php file via ajax and i am returning only 1 $ variable using die($var) in the php file after a sucsessfull run...
the problem i am now facing is passing more than 1 variable back to the ajax sucess function . i have tried using json encode but it has failed to work. im thinking maybe to do with the ajax being form data.
im hoping there is a simple way top pass multiple varibles back to the sucess function.
Any help is greatly appreciated
var form_data = new FormData(); // Creating object of FormData class
form_data.append("image", file , newimagesrc) // Appending parameter named file with properties of file_field to form_data
form_data.append("oldimagesrc", oldimagesrc) // to re-write over with new image
form_data.append("email", email)
form_data.append("imagext", fileNameSub)
$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(newimagesrc){
//how do i pass back from php these variables
var out1=out1;
var out2=out2;
alert(out1 , out2);
//help appreciated
var newimagesrc = newimagesrc;
//alert(newimagesrc); alert recieved message
imagename=input.files[0].name;
$('#imageupdate').css('color','green');
$('#imageupdate').text(newimagesrc);
var refreshimage = "Profileimagerefresh.php?avatar="+newimagesrc+"&email="+email;
$('#imagerefresh').load(refreshimage);
}//success 1 messagereturn1
});//ajax1
PHP FILE ('UploadProfileImage.php')
if(file_exists($oldimagelocation) && is_readable($oldimagelocation)){
$new=$rnd.$accountname.".".$extension;
if ($stat->execute(array("$new","$email"))){
unlink($oldimagelocation);
die($oldimagesrc); //HERE I PASS 1 $ BACK - I NEED TO RETURN MORE
exit();
}
else{
die("Failed replace image with image and rename");
exit();
}
}
Using JSON encode is the best choice. I would recommend something like this:
if (file_exists($oldimagelocation) && is_readable($oldimagelocation)) {
$new = $rnd.$accountname.".".$extension;
if ($stat->execute([$new, $email])) {
unlink($oldimagelocation);
echo json_encode([
'out1' => $oldimagelocation,
'out2' => $oldimagesrc,
], JSON_FORCE_OBJECT);
} else {
die("Failed replace image with image and rename");
}
}
Then in JS just parse the response as JSON
$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(newimagesrc){
let jsonObj = JSON.parse(newimagesrc);
console.log(jsonObj.out1);
}
});
I have encountered a similar issue recently and solved this using JSON.
With PHP you can put the variables into an array and then use json_encode: and then return that onto the webpage.
Now, using your jQuery, you can use $.parseJSON which then makes it an array in jQuery.
Here's an example:
PHP:
die(json_encode(array('Hello', 'world!')));
jQuery:
$.ajax({
type: 'POST',
url: 'test.php',
}).done(function(result){
var array = $.parseJSON(result);
alert(array[0]);
});

$_GET the variable of javascript to php

my ajax is:
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: full_val+'='+add,
success: function(data)
{
}
});
if the javascript variable value changes depending on the conditions, then how will i $_GET[] the variable full_val? I want it to be something like:
$_GET[full_val]
is there a way to pass the variables of javascript to php?
If you want the literal index full_val, then use it in the query string:
data: 'full_val='+add,
So that in PHP, you'd be able to use $_GET['full_val']
Alternatively, you could also put an object in that field:
data: {full_val: full_val, add: add},
Here is the description:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
Your data just has the values and does not have the keys. See below for how to pass the keys and values.
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: {full_val:full_val,add:add},
success: function(data)
{
}
});
In your PHP use $_GET['full_val'];
send your values with data parameter correctly and add type:get to define GET method
add = 'request';
full_val = 'barrack obama';
$.ajax({
type: "get",
url: 'plugins/add_friend.php',
data: {'full_val':full_val,'add':add},
success: function(data) {
}
});
Then you will get values on php :-
use $_GET['full_val'] rather $_GET[full_val]
Try Using this
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'add.php',
data: 'full_val='+add,
success: function(data)
{
alert(data);
}
});
You can use the .get() method. The variables you can set using an object literal. For example:
$.get("/plugins/add_friend.php", {
add: "request",
full: "Barrack Obama"
}).done(function(data) {
console.log("Status:", data.status);
console.log("Received:", data.received);
});
And the PHP could be done something like this:
$add = filter_input(INPUT_GET, 'add', FILTER_SANITIZE_STRING);
$full = filter_input(INPUT_GET, 'full', FILTER_SANITIZE_STRING);
echo json_encode(array(
'status': 'OK',
'received': "{$add} and {$full}",
));

Access php function data via ajax

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).

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";

Jquery, reading JSON variables received from PHP

Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...

Categories