I'm sending an JS object via $.post() and I want to get an array back.
JS
var ajaxData = {action:"createuser"}
$("input[required]").each(function(){
var attr = $(this).attr("name");
ajaxData[attr] = $(this).val();
});
$.post(
daten.ajaxurl,
ajaxData,
function(data){
alert(data[0])
}
)
PHP
//Create a User
add_action('wp_ajax_nopriv_createuser','createuser');
function createuser () {
foreach ($_POST as $key => $value) {
if(empty($value)) {
$type = "error";
$content = "$key is empty";
echo array($type,$content);
wp_die();
}
}
}
What I get as a response is always a string, so it works well if I echo $content.
I've read about that you can use JSON and get it automatically encode if you add DataTaype: "JSON".
But I have no idea how to properly decode it in PHP, tho
I would use the wp_send_json(); function. This is exactly the thing you look for.
And don't forget to put wp_die() at the end.
wp_send_json(): https://codex.wordpress.org/Function_Reference/wp_send_json
wp_die(): https://codex.wordpress.org/Function_Reference/wp_die
You can't just echo an array. In AJAX it's considered default to return JSON objects in requests. What you want to do is make an JSON object from the array. You can use json_encode for that.
http://php.net/json_encode
After that you can use the JSON object in JS/jQuery to do whatever you want to do with it.
Related
I have this jquery function
function updateStatus(){
$.getJSON("<?php echo $_SESSION['filnavn']; ?>", function(data){
var items = [];
pbvalue = 0;
if(data){
var total = data['total'];
var current = data['current'];
var pbvalue = Math.floor((current / total) * 100);
if(pbvalue>0){
$("#progressbar").progressbar({
value:pbvalue
});
}
}
if(pbvalue < 100){
t = setTimeout("updateStatus()", 500);
}
});
}
Is it possible to get the JSON from a PHP session variable instead of a json file?
As I have understood I can get the session data from the session like this:
//json test
var jsonstr = $_SESSION['json_status'];
//parse json
var data = JSON.parse(jsonstr);
But I do not know how I can do that with out the getJSON function?
You're reading too much into it. .getjson is just a $.ajax() call that EXPECTS to get a json reponse from the server. That's all.
It doesn't matter WHERE PHP gets data from, as long as it spits out json text.
Whether that json text was just retrieved from a file/db, or dynamically generated with json_encode(), as long as the browser receives json text, things will "work".
Your best bet here is to create a php file that can act as the target of getJSON that returns the json from your session.
<?php
session_start();
if (isset($_SESSION["filnavn"])){
echo $_SESSION["filnavn"];
// Or, if the key contains an object instead of a json string, use
// echo json_encode($_SESSION["filavn"]);
} else {
// echo the json you want here if the session variable is not set
echo "{}";
}
?>
Then in your jquery code change the getJSON to this
$.getJSON("/path/to/php/file.php", function(data){...});
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
I'm working on a jQuery .get that will send a value to the server to compare against an array which will then get encoded into a json format as the responses. Below is the code (jQuery and PHP zend). I'm not sure if my problem is with identifying the keys and values or if it is the syntax. Is there away to view the raw json data echoed by my php controller?
$.get(
"/ed/macro",
{value: singleValues},
function(data) {
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
$('#stage').html("data");;
});
});
},"json");
$select = $this->getDbTable()->select();
$select->from('sub');
$resultSet = $this->getDbTable()->fetchall($select);
$data = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Subdiscipline();
$entry->setIdSub($row->idsubdiscipline)
->setSub($row->subdiscipline)
->setDescription($row->description);
$data[] = $entry;
}
return $data;
}
public function macAction()
{
$request = $this->getRequest()->getParam('value');
// acti
$sub = new Application_Model_Sub();
$fetch = $sub->fetchAll($request);
$jsonObject = Zend_Json::encode($fetch);
echo $jsonObject;
// action body
}
To view the object print_rin PHP and console.log in Javascript. Or as Sam said, after the JS has called it, look in Net to see what was sent.
Assuming that you are echoing a json string after telling your server to tell the browser it is json with header("Content-type: application/json"); your problem is probably here
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
data.value1 isn't what you're dealing with there, it's value1. I'm assuming value1 IS an array, and you're picking the first element in it value1[0] to then iterate?
$.each(data, function(key,value1){
$.each(value1[0], function(key,value2){
Or maybe you're after
$.each(data, function(key,value1){
$.each(value1, function(key,value2){
Please echo the object and show it to us.
JavaScript/JQuery
var arr=[];
$('.element').each(function(i)
{
arr.push({"id":i,"value":$(this).attr('data-value')});
});
$.get('/json.php?arr='+arr,function(result)
{
alert(result);
});
PHP
<?php
$j = json_decode($_GET['arr'], true);
foreach($j as $k => $v)
{
echo $v['id'].':'.$v['value'].'<br />';
}
?>
Problem
But the problem is that the URL looks like /json.php?arr=[object Object],[object Object] instead of /json.php?arr=[{"id":1,"value":"value 1"},{"id":2,"value":"value 2"}]. Do I need to convert the object to a string? But I don't want to use another library other than JQuery. Is this possible? :/
Try JSON.stringify
$.get('/json.php?arr='+JSON.stringify(arr),function(result)
If you aren't tied to the idea of passing if via JSON, you can provide it in the data part of the jQuery request:
$.get( url, data, callback );
And then retrieve it later:
foreach( $_POST as $key => $value ){
//....
}
i try to send data to my php scripts but i think i miss something.
First of all,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2', JSON.stringify({'artistIds': artistIds}),function(response){
if(response=='ok')
alert(artistIds);
});
}
Above code is my js file. i have artistIds in var artistIds. My goal is sending this array to my php script.In order to that, i make it json , i mean encode it with JSON.stringify
then in php side, i use below code.However, $array is always null. What might be the reason ?
public function deleteDataAjax2() {
$array=json_decode($_POST['artistIds']);
if (isset($array))
$this->sendJSONResponse('ok');
}
You are passing the data as a raw string of JSON, but your PHP is trying to find that string by parsing the data as application/x-www-form-urlencoded and then looking at the artistIds key.
Assuming the array is flat: Forget JSON. You don't need it.
$.post('/json/crewonly/deleteDataAjax2', {'artistIds': artistIds},function(response){
And:
$array = $_POST['artistIds'];
If the array isn't flat, then:
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
And (with suitable error checking added):
$json = $_POST['json'];
$data = json_decode($json);
$artists = $data['artistIds'];