Jquery, reading JSON variables received from PHP - 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)...

Related

Pass Boolean Values from Ajax to PHP

I've read a tonne of questions on the subject but none of them seam to solve my particular issue – I guess there's something wrong with the way I've formatted my array of objects in JS. Here's my Ajax function:
var marketing_prefs = [];
$('#save-marketing-prefs input').each(function() {
var tmp_array = {};
tmp_array['marketing_permission_id'] = $(this).val();
if ($(this).prop('checked')) {
tmp_array['enabled'] = 1;
} else {
tmp_array['enabled'] = 0;
}
marketing_prefs.push(tmp_array);
})
console.log(marketing_prefs);
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: marketing_prefs
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
What I'm doing is looping through a simple form with three checkboxes and creating an array of objects which will then go off to Mailchimp. My data arrives intact but the problem is that my boolean values come over to PHP as strings. I've switched from using true and false which was coming over as "true" and "false", to using 1 an 0 but those come over as strings too.
I suppose I could loop through the data and build a new array in PHP but the data is so close to being correct when it arrives that it seems like it must be unnecessary.
How can I get my data over as non-strings?
POST data is sent as simple name=value pairs, there's no syntax to specify datatypes, and everything is parsed as strings.
You can call intval($_POST['marketing_prefs'][$i]['enabled']) to convert it to an integer.
Another option is to convert the marketing_prefs array to JSON.
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: JSON.stringify(marketing_prefs)
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
Then in the PHP you can do:
$marketing_prefs = json_decode($_POST['marketing_prefs'], true);
Since, as Barmar stated, GET/POST can't specify data types (that's a rant in and of itself), one way would t be to cast it.
Very rough example:
var_dump((bool) <variable>);
The issue is if it's anything but 'true', 'empty' or I believe 0 it will return true. I'm in a hurry else I'd flush it out for you better.

How to access members of associative array from AJAX Response

I have a shorthand ajax call that triggers on a selection box change.
<script type'text/javascript'>
$('#selection_project').change(function(event) {
$.post('info.php', { selected: $('#selection_project option:selected').val()},
function(data) {
$('#CTN').html(data);
}
);
});
</script>
It works, but the response from the server is this:
if (isset($_POST['selected']))
$selected = $_POST['selected'];
$results['selected'] = $selected;
$response = json_encode($results);
echo $response;
$results is an associative array with many values from a SQL query.
My question is how do I access any particular element?
I've tried things like
data.selected
or,
data['selected']
I also understand that somewhere in the .post method there should be a statement defining the alternative dataType, such as
'json',
or a
datatype: 'json',
but after lots of searching, not a single example I could find could provide the actual syntax of using alternative dataTypes in the .post method.
I would have just used the .ajax method but after pulling my hair out I cannot figure out why that one isn't working, and .post was, so I just stuck with it.
If someone could give me a little push in the right direction I would appreciate it so much!!
EDIT: Here is my .ajax attempt, can't figure out why it's not working. Maybe i've been staring at it too long.
<script type'text/javascript'>
$('#selection_project').change(function(event) {
$.ajax({
type: 'POST',
url : 'pvnresult.php',
data: { selected: $('#selection_project option:selected').val()},
dataType: 'json',
success: function(data){
$('#CTN').html(data);
}
});
});
</script>
Try to log what exactly returned from info.php. Possible there are no data at all&
$('#selection_project').change(function(event) {
$.post('info.php', {
selected: $('#selection_project option:selected').val()},
function(data) {
console.log(data);
$('#CTN').html(data);
}
);
});
--- Update. Sorry, I can't leave comments
You shold parse your json with JSON.parse before use:
$('#selection_project').change(function(event) {
$.post('info.php', {
selected: $('#selection_project option:selected').val()},
success: function(data){
var result = JSON.parse(data);
$('#CTN').html(data);
}
});
});
Point to note: In your Javascript, you were doing:
dataType: 'json',
success: function(data){
$('#CTN').html(data);
}
This implies, you expect JSON Data - not just plain HTML. Now in your to get your JSON Data as an Object in Javascript you could do:
success: function(data){
if(data){
// GET THAT selected KEY
// HOWEVER, BE AWARE THAT data.selected
// MAY CONTAIN OTHER DATA-STRUCTURES LIKE ARRAYS AND/OR OBJECTS
// IN THAT CASE, TO GET THE EXACT DATA, YOU MAY JUST DO SOMETHING LIKE:
// IF OBJECT:
// $('#CTN').html(data.selected.THE_KEY_YOU_WANT_HERE);
// OR IF ARRAY:
// $('#CTN').html(data.selected['THE_KEY_YOU_WANT_HERE']);
$('#CTN').html(data.selected);
}
}

$_POST not being set with AJAX call

This should be a fairly simple call but I just can't seem to make it work. Basically, I'm trying to pass a set of search parameters to a PHP script but $_POST is coming up empty. The call (via jQuery)...
self.search = function () {
var data = {
'year': 2013,
'month': 10,
'day': 1
};
$.ajax({
dataType: 'json',
type: 'POST',
url: 'repositories/blogposts.php',
data: { 'search': data },
success: function(results) {
// populate knockout vm with results...
}
});
};
The PHP code waiting to do something with the incoming json object...
if (isset($_POST['search'])) {
echo find_blogposts(json_decode($_POST['search']));
}
I've tried this many ways but no matter what, print_r($_POST) gives me an empty array. What's missing?
PHP is probably choking on the object you are trying to send.
You should either send the data object directly:
data: data,
(to get $_POST['year'], etc. in php)
or convert the object to a json string you can decode on the php side:
data: { 'search': JSON.stringify(data) },
What does happen inside of find_blogposts()?
Alternatively you could try .post().
$.post( "repositories/blogposts.php", { year: "2013", month:"10", day:"1" }, function( data ){
// do something here
});
In your php just receive $_POST['year'] which will be 2013.
Hope it helps.
Here is api doc for .post()

jQuery ajax request with json response, how to?

I am sending an ajax request with two post values, the first is "action" which defines what actions my php script has to parse, the other is "id" which is the id of the user it has to parse the script for.
The server returns 6 values inside an array() and is then encoded to JSON with the PHP function: json_encode();
Some of my responses are HTML, but when I encode it to JSON, it escapes "/" so it becomes "\/"
How do I disable that?
Also when I don't know how to display this in jQuery when I get the server response, I just thought that putting it all into a div would just display the numbers and HTML codes I had requested, but it displays the array as it is encoded in PHP.
PHP
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo json_encode($response);
jQuery:
$.ajax({
type: "POST",
dataType: "json",
url: "main.php",
data: "action=loadall&id=" + id,
complete: function(data) {
$('#main').html(data.responseText);
}
});
How do I make this into working JSON?
You need to call the
$.parseJSON();
For example:
...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...
see this in
http://api.jquery.com/jQuery.parseJSON/
if you still have the problem of slashes:
search for security.magicquotes.disabling.php
or:
function.stripslashes.php
Note:
This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.
Firstly, it will help if you set the headers of your PHP to serve JSON:
header('Content-type: application/json');
Secondly, it will help to adjust your ajax call:
$.ajax({
url: "main.php",
type: "POST",
dataType: "json",
data: {"action": "loadall", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.
NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.
$.ajax({
url : base_url+"Login/submit",
type: "POST",
dataType: "json",
data : {
'username': username,
'password': password
},
success: function(data)
{
alert(data.status);
}
});

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