How do I pass a JSON array into the URL? - php

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 ){
//....
}

Related

Return PHP array after AJAX call

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.

Passing javascript array to php to print values does not work

I want to pass a javascript array to php to print the values, but it is not working. What am I doing wrong?
javascript
$('#Enviar0').click(function() {
var buttons0 = [];
for(var i=0;i<4;i++){
buttons0[i]+= $('butEnv'+i).val();
alert($('butEnv'+i).val());
}
var array=buttons0.toJSONString();
$.ajax({
type:"POST",
url:"pintaParte.php",
data: {encapsulado:array},
success: function(data) {
$("#pinta").html(data);
}
});
});
php
$buttons0=parseJSON($_POST['encapsulado']);
foreach ($buttons0 as $value) {
echo $value.'<br>';
}
use JSON.stringify() on the client side:
$.ajax({
type:"POST",
url:"pintaParte.php",
data: JSON.stringify({encapsulado:array}),
success: function(data) {
$("#pinta").html(data);
}
});
Do you check if your array is ok in the php side (after the ajax call) ?
If you can't get your array in the php side, maybe in your javascript try to simply use...
data : "encapsulado=" + array
And in your php code, try to put all values of the array in one string and just make only one echo and then a return.
$str = "";
foreach ($buttons0 as $value) {
$str = $str.$value.'<br>';
}
echo $str;
return;
Try to use a tool like firebug or the Chrome dev tool to see parameters and responses in your http requests and be abble to localize the error (in the client side or in the server side).
Hope this helps !

Could use some advice on jQuery each function on a associative multidimensional array

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.

How to access all elements in an array from php that is passed by an ajax call?

I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);

jQuery ajax call errors with sendToValue is not defined, what is wrong with this jquery code ?

I'm kind of new to jquery/ajax calls, I have this code below to pull from php page json values.
$(function(){
$('#search').keyup(function() {
sendValue($(this).val);
});
});
function sendValue(str)
{
$.post(
"back/search.php",
{ sendToValue: str },
function(data) {
if(!data.empty){
//Put the result in the suggest div
$("#suggest").html(data.returnedFromValue);
}
},"json"
);
}
and here is the search.php file
$values = $database->get_by_name($_POST['sendToValue']);
if( !$values ) {
echo json_encode(array("returnedFromValue" => "ERROR"));
}
else
{
foreach($values as $value) {
echo json_encode(array("returnedFromValue" => $value));
}
}
The problem that that the value doesn't appear in the suggest div, the only output there is "error", when I check the ajax request in firebug under post section it gives me the message that sendToValue is not defined any ideas? Thanks!
The first thing that leaps out at me (there may be other problems, but this is the one I noticed first) is that you're missing the parentheses after val in the call to sendValue:
sendValue($(this).val);
should be:
sendValue($(this).val());
Currently, you're passing the val method itself into the sendValue function, rather than the result of calling that method.
$(this).valprobably needs to be $(this).val()
When programming JavaScript Firebug and console.log()are your friends.

Categories