response from php to javascript via json - javascript

I have this function in php
public function get_updated_session_value()
{
$sql = "SELECT IF(Session = 12345678 , 1,0) AS login FROM `psf_users` WHERE id = 236";
$var = $this->addDb($sql)->execute();
$Session = $var['login'];
return json_encode('2');
}
and the javascript code to fetch this value,
function check() {
$.ajax({
url : 'auctions.php',
type : 'get',
// dataType: 'json',
data : {page:'__request', module:'PSF_auctions', action:'get_updated_session_value'},
success: function(data) {
console.log(data);
}
});
}
also, this function runs every 5 seconds via
setInterval(check, 5000);
the problem is, console.log(data); prints nothing, i believe that means it is not getting any data (or json response) from the php function. am i missing something?

It can't work as you're returning the value. The difference between returning a value and emitting a response is that the latter writes a response on the HTTP stream whilst the first one merely returns the control to the parent with a specific value.
Sanjay has spotted it very well, and I'd recommend that you use a very simple function to wrap up your responses:
function emit_response( $status_code, $data ) {
http_response_code( $status_code ); // 200 is it's success. find more http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
die( json_encode( array(
"status_code" => $status_code,
"data" => $data )));
}
Then modify that echo (though it's fine as well) with
emit_response( 2 );
and since the response is valid JSON, JavaScript will love it; in your callback, you can simple do this:
success: function(res) {
var response = JSON.parse( res );
// response.data will be 2. :)
// ... rest of the code ...

Replace return with echo like this:
public function get_updated_session_value()
{
$sql="SELECT IF(Session = 12345678 , 1,0) as login FROM `psf_users` WHERE id=236";
$var= $this->addDb($sql)->execute();
$Session= $var['login'];
echo json_encode('2');
}

Related

How return array in function() to javascript on wordpress ajax.php with following code:

it may seem stupid, but i'm in it for a week, help me ...
the "response" in xhr dev-tools chrome does not leave "0", it never returns the array I need ...
Javascript code to get data from wordpress
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
$.post("wp-admin/admin-ajax.php", { getHomeSliderSeries: id }, function (html) {
var data = jQuery.parseJSON(html);
if (data.status == "success") {
var listing = data.list;
var lister = [];
for (var i = 0; i < 20; i++) {
var row = listing[i];
lister.push(seriePoster(row.url, row.rating, row.poster, row.title, row.cat, row.episode));
}
$list.parent(".itemsList").addClass("fadingOut");
setTimeout(function () {
$list.html(lister.join(""));
$list.trigger("destroy.owl.carousel");
createItemSlider();
$list.parent(".itemsList").removeClass("fadingOut");
}, 200);
} else {
return false;
}
});
});
PHP file to return data in array json to javascript show results in html.
wp-admin/admin-ajax.php (theme/inc/core/ajax.php)
function getHomeSliderSeries(){
// i Want see that bellow in xhr response to javascript:
//{"status":"success","list":{}}
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );
My language is not very good, i hope you undestand, thanks atentiton!!
Try ajax callback function in functions.php
function swt_ajax_data() {
$id = isset($_POST['id']) ? $_POST['id'] : '';
// Create an associative array for the response.
$responsedata = array(
'id' => $id,
);
$result = array();
// if need featch the data from the template un comment the bellow five lines and commented the sixth line
//ob_start();
//include('templatepatj');
//$opr_html .= ob_get_contents();
//ob_get_clean();
// $result['data'] = $opr_html;
$result['data'] = $responsedata;// POST array data.
}
return wp_send_json_success($result);
}
}
add_action('wp_ajax_swt_ajax_data', 'swt_ajax_data');
add_action('wp_ajax_nopriv_swt_ajax_data', 'swt_ajax_data');
Localize your script and pass the admin ajax url
// Register the script
wp_register_script( 'ajax-script', 'path/to/myscript.js' );
// Localize the script with new data
$js_array = array(
'ajaxurl' => admin_url('admin-ajax.php'),
);
wp_localize_script( 'ajax-script', 'swtobj', $js_array );
// Enqueued script with localized data.
wp_enqueue_script( 'ajax-script' );
Try Js as like below.
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
var data = {
'action': 'swt_ajax_data', 'id': id
};
$.ajax({
url: swtobj.ajaxurl,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function (response, textStatus, jqXHR) {
var response_data = response.data.data;
if (response_data != "" || response_data.length != 0) {
console.log(response_data);
// write your code here
} else {
// write your code here
}
},
});
});
The data you send in $.post is missing an action property. This property is responsible for telling the admin-ajax.php which function that is registered with a wp_ajax_{function_name} hook should be called.
The value in the action property should match the function_name in wp_ajax_{function_name} and wp_ajax_nopriv_{function_name} to be called properly.
Combine the action property with other properties that you want to send to the backend to pass the data that you need to send.
// Set the action and get the id.
var action = 'getHomeSliderSeries';
var id = $(this).attr("data-show-home-list-series");
// Create object to send data to backend.
// This must include an action property with
// the name of the function on the backend.
var postData = {
action: action,
id: id,
example: 'Send any data as a property. You can also nest objects and arrays.'
};
$.post("wp-admin/admin-ajax.php", postData, function(response) {
if (response.status == "success") {
console.log(response);
}
}, 'json'); // Expect JSON from the backend. Now you don't need to parse.
Now on the server side your getHomeSliderSeries should be called. All the other properties (action included) can now be accessed through the global $_POST variable with their corresponding keys.
For a response, create an associative array with the data you want to return. This is the equivalent of an object in JavaScript. Encode the array to JSON and send it back. Now the frontend should see an object as a response.
function getHomeSliderSeries(){
// Get the id from the post request.
$id = isset($_POST['id']) ? $_POST['id'] : null;
$example_string = isset($_POST['example_string']) ? $_POST['example_string'] : null;
// Create an associative array for the response.
$response = array(
'status' => 'success',
'id' => $id,
'example' => $example_string
);
// Return the array as a JSON string.
return json_encode($response);
// Cuts connection by stopping the function.
die();
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );

how do i send javascript variables to PHP and return the results

I have a form with inputs (each with ID param,param1,param3 respectively) and an external php file with a function called getform() that takes three parameters from the form (param, param1, param3 respectively).
A text feild with id results to display the response from php file.
I have placed onclick function on param3.
I need whenever a user types something in param3 it should be sent to php file and the results displayed in the text filed of id results.
here is my code
<script>
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.post('curencyconvert.php', {
postparam: param,
postparam2: param2,
postparam3:param3
}, function(data){
$('#results').html(data);
});
}
</script>
my php function in the php file
function Conv($param,$param2,$param3){
//my code here
return $output;
}
if(isset($_POST)){
//Calling the defined function here
Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Add these line below your function code.. and better echo the output in your function instead of returning it.
jQuery(document).ready(function($) {
$('#param3').change(function() {
// put here the code //
} );
})
What errors you get in Console(firbug)?
As stated by other answers $_POST should be used.
What your php code returns if it returns an array or returns an object It can not be put into the Input. Return value must be a
string
PHP code must be :
function Conv($param,$param2,$param3){
//my code here
// take particular field of the DB results or resultset that you want to show in the input.
return $output['name'];
}
I know answer is incomplete because your question is incomplete.
Please let me know errors from the console so that i can help you further
echo instead of return.
if(isset($_POST)){
echo Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Do something like this, it is more clean:
Conv($param, $param2, $param3){
// your code here
return $output;
}
As for the javascript part, jquery ajax is your friend
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.ajax({
url: '/path/to/file',
type: 'POST',
data : { postparam: param, postparam2: param2, postparam3: param3 },
}).done(function(data) {
$('#results').html(data);
});
}

How to iterate with javascript a json response from symfony2

i want to itarate a json response from symfony and put it in a table td>
my action :
$search = $this->getDoctrine->...;
$serializer = $this->get('serializer');
foreach ($search as $key => $value) {
$search[$key] = $serializer->serialize($value, "json");
}
$reponse = new JsonResponse($search);
return $reponse;
this is what i have in my twig ( i examine it with Firebug ):
i have a to display at least something but sometimes i have undefined or nothing ... this my javascript function
$(document).ready(function () {
var dataString = $("form").serialize();
var typerequest = $("form").find('input[name="typerequest"]').val();
$('#filtreperseance').ajaxForm({
type: "POST",
url: Routing.generate('myroute'),
data: dataString,
success: function (response) {
$.each(response, function (cle, valeur) {
$("#test").html(valeur);
});
}
});
});
EDIT 1 : Console.log
EDIT 2 :
I'd try to cut down the problem. First make sure, the JSON is valid and looks the way you expect. Don't use jQuery at this point. Call the symfony controller in your browser directly. Then check the json. http://jsonviewer.stack.hu might be of use.
Once you verfified that the JSON itself is valid and contains what you need, we can look at the jQuery part. Then we'd need the code and the errors you get.
i have done a mistake when i returned the JSOn from Controller . its Ok now

Cant get PHP variables using AJAX

I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).
main.php
include ('databaseQueries.php');
if (isset($_POST["points"])){
$points = json_decode($_POST["points"]);
if($_POST["execute"] == 1){
}
}
$advert= array(
'Hello' => 'Hello world!',
'bye' => 'Why bye?',
);
echo json_encode($advert, $another);
pageJs.js
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
databaseQueries.php
$another = "another string";
If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.
What I'm doing wrong and how can I get both the $test array and $another variable?
Thank's in advance!
You are using json_encode incorrectly. From the documentation:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
You are trying to send $another to the function as the options parameter.
You could do something like this:
$ret = array($advert, $another);
echo json_encode($ret);
Unless I'm completely wrong, I can't see where you're sending anything TO your post
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json'
// I would expect a data call here, something like:
data: $(form).serialize(), // OR { points: 3, execute: 1 }
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
I assume that you want to spit back some results with the format of result->key;
So Keeleon's answer above is good:
$ret = array($advert, $another);
echo json_encode($ret);
But you can also do:
//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);
Hopefully, this answers your questions.

Prototype believes JSON from PHP is string

I have the following code in JS:
new Ajax.Request('http://www.some_random_url.com',
{
parameters: { start : this.start, stop : this.stop },
method: 'post',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response.posts);
$(response.posts).each( function(item) {
alert(item.title);
}
},
onFailure: function(){ alert('Something went wrong...') }
});
and then I have the following code in PHP. The function takes an array as an argument, and is meant to output JSON.
function view_api($array) {
header('Content-type: application/json');
echo json_encode(array('posts'=>$array));
}
Still, it seems to be treated by prototypejs as a string. When response is alerted, everything is fine. But the each loop in JS says response.posts is undefined.
Do you know why?
If it's returning the JSON as a string then you should parse it first.
var data = JSON.parse(payload);
use evalJSON() to typecast the response in JSON object as
var response = transport.responseText.evalJSON() || "no response text";
set evalJSON: 'force' in the prototype ajax request options. then use var response = transport.responseJSON
A neat trick with prototype.js is that you can pass the following headers and it will automatically be converted to json.
header('X-JSON: (' . json_encode($data) . ')');
header('Content-type: application/x-json');

Categories

Resources