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);
}
}
Related
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.
I'm sure this has been asked many times but I couldn't find the answer after quite a bit of searching.
I have a simple jquery ajax request to get some data for a particular string as follows:
$.ajax(
{ url: "/getval.php?title="+encodeURIComponent(title),
dataType:"json",
success: function(data) { console.log(data) }
});
The php script is using:
$title = urldecode($_GET["title"]);
to get the value from the get request.
It doesn't need to work for every conceivable string but I do need it to work for a string with a single quote. What is the safest (and easiest) way to do this request and handle the request in php?
Thanks in advance,
Steve
Why hard way?
jQuery:
$.get("/getval.php", { title: 'your title' },
function(data){
console.log(data);
}
);
PHP:
<?php
$title = $_GET['title'];
Please always read manual first:
http://api.jquery.com/jQuery.get/
You just need to set the data attribute, and PHP will get the value from the $_GET array:
$.ajax(
{ url: "/getval.php",
dataType:"json",
data: { title: 'the title' },
success: function(data) { console.log(data) }
});
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}
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";
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)...