Passing javascript array to php to print values does not work - php

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 !

Related

ajax to php $variable

I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.

Trying to extract information throught a PHP file Undefined

I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>

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);

$.post function is not returning the correct data

I'm using $.post to deliver data to my main page from droppable elements. Yet when I echo out the the data I'm getting my toolbar echoed out to me as well as the data I fetched.
if (isset($_POST['data'])){
$data = $_POST['data'];
echo $data;
The javascript containing the $.post is below
if(dropbox && dropbox1 !== ''){
$.post("account_main.php",
{data: $(this).text()},
function(data) {
$('#demo').html(data);
});
}
And a visual for the script using the droppable elements is HERE, but the problem is not shown here, can't duplicate it. I am open to any suggestions.
if (isset($_POST['data'])) {
echo $_POST['data'];
# Other stuff
exit; # Kill the script
}
If I understand your problem correctly, that should sort it :)
Just try :
if (dropbox && dropbox1 !== "") {
var url, params, callback;
url = "account_main.php";
params = {
"data": $(this).text()
};
callback = function(data) {
$("#demo").html(data);
}
$.post(url, params, callback, "html");
}
Please note that I would strongly advise you to use JSON for your response instead of HTML.
header("Content-type: application/json");
echo json_encode($my_result);
data: $(this).text()
$(this) refers to the $.post, I think that's not the data you want.

Sending JSON jQuery Ajax to PHP and back

I'm having problems sending a JSON jQuery array via Ajax to a PHP script. What is the problem here:
var tee = $('#voting_image img').attr('id');
var vote = 1;
var thing = {tee: tee, vote: vote};
var encoded = $.toJSON(thing);
$.ajax({
url: '/vote_save.php',
type: 'POST',
dataType: 'json',
data: 'vote='+encoded,
success: function(data)
{
var back = $.evalJSON(data).name;
$('#voting_hint_name').html(back);
$('#voting_buttons').html('<div id="voting_buttons">PRINT ITDON\'T PRINT IT</div>');
},
error:function ()
{
$('#voting_buttons').html('<div id="voting_buttons">PRINT ITDON\'T PRINT IT</div>');
alert("There was a problem, your vote was not saved, please try again!");
}
});
This is the PHP
if (isset($_POST['vote'])&&isset($_SESSION['user']))
{
$tee_data = json_decode($_POST['vote']);
$the_tee = $tee_data['tee'];
$responce = array('name'=> 'Alex Wow', 'test'=> '1');
echo json_encode($responce);
}
else {
echo "error";
}
The error I am getting in Firebug is:
Error: JSON.parse
AFAIK, there is no $.toJSON method in jQuery, you are probably looking for $.parseJSON and by the way you are already creating JSON here:
var thing = {tee: tee, vote: vote};
I think the problem is that you send data as object, try to send as array
var thing = {tee: tee, vote: vote}; to array
Check out this question: Serializing to JSON in jQuery
The accepted answer links to a JSON serialization plug-in recommended by John Resig (the creator of jQuery). It doesn't really address your specific bug, but perhaps using that plug-in will help you arrive at a stable solution.
From looking at it briefly, if you use that plug-in, it appears you would then replace this line:
var encoded = $.toJSON(thing);
with this:
var encoded = JSON.stringify(thing);
Hope that helps!
Thanks for your responces, I went with:
$.getJSON(
'/vote_save.php?vote='+encoded,
function(data)
{
$('#voting_hint_name').html(data.bob);
$('#voting_buttons').html('<div id="voting_buttons">PRINT ITDON\'T PRINT IT</div>');
}
);
instead of $.ajax and it worked.

Categories