Echoing Variables within a JSON array - javascript

I'm trying to access and display a variable within a json object on my page. Can anyone tell me why the variable gets displayed three times?
my_array.php
<?php
$my_data=array(name=>"john",age=>"30", city=>"copenhagen");
// sending output
header('Content-Type: text/json');
echo json_encode($my_data,true);
?>
My_page.php
<script>
$(document).ready(function() {
$("button").click(function() {
$.getJSON("my_array.php", function(data) {
$.each(data, function(key) {
$("#showdata").append(data.city);
});
});
});
});
</script>
//Show the data further down the page.
<div id="showdata"></div>
This displays
copenhagencopenhagencopenhagen

That's because you're iterating over 'each' data item from the json response that you receive and there are 3 key=>value pairs in my_array.php
Removing "$.each(data, function(key) {} " will return the value 'city' only once
$(document).ready(function(){
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
});

use this
my_array.php
<?php
$my_data = array(
name => "john",
age => "30",
city => "copenhagen"
);
// sending output
header('Content-Type: application/json');
echo json_encode($my_data, true);
?>
My_page.php
<div id="showdata"></div>
<button>Click Me!</button>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(e){
$.getJSON("test.php", function(data){
console.log(data);
$("#showdata").append(data.city);
});
});
});
</script>
this will give you only one copenhagen.
hope it helps...

First things first:
Set either:
header("Content-Type: application/json");
Above:
echo json_encode($my_data,true);
On your php file.
Or use the following snippet on your javascript:
$.getJSON("my_array.php",function(data)
{
data=JSON.stringify(data);
$.each(data, function(key)
{
$("#showdata").append(data.city);
});
});
Furthermore either in both ways above the returned data is an Object so in order to return correctly on your php file the data must be:
$my_data=array(array(name=>"john",age=>"30", city=>"copenhagen"));
Note: Associative arrays on php's json_encode turned into Objects. Non associative arrays on json_encode still remain an array

Im guessing because you have got three buttons on the page and the $.each takes the selector try:
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});

you're iterating 3 times because of the three keys you have within the JSON object,
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
console.log( "key + " " + val" );
});
take a look at the JQuery documentation for further info.
http://api.jquery.com/jquery.getjson/

Related

How to get a multidimensional array after submitting my form from javascript into PHP?

One php file with php and javascript inside. I have a multidimensional array defined in the javascript part. I can see the proper output of "key" and "value" in the console but I do no get the array into php after submitting my form.
What I am doing wrong?
<?php
echo "Postcmd: ".$_POST["postcmd"];
print_r($_POST["postcmd"]);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var postcmd =[];
var key;
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd.hasOwnProperty(key)) {
console.log(postcmd[key])
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd
});
}
</script>
Not even this simple and often found script example works for me - what else might be the issue? Are there other (basic) things to know about js->PHP?
<?php
// index.php
?>
<html>
<head>
<title>Pass JS array to PHP.</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var arrayfromjs = "123";
$.ajax({
type: "POST",
url: "index.php",
data: { testArray : arrayfromjs},
success: function() {
alert("Success");
}
});
</script>
</head>
<body>
<?php
echo "<br>Pass JS array to PHP.<br>";
$myArray = $_POST['testArray'];
print_r($myArray);
?>
</body>
</html>
Per the jQuery documentation,
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Thus, your data field must contain an object (such as {foo: bar, foo_again: bar_again}; in PHP, this would read as $_POST['foo'] == "bar"). However, your code submits an array with one element: the object specified. In addition, PHP does not magically turn your JS array/object into a PHP array. You have to parse the string passed into PHP and turn it into the array you need.
If you print $_POST, you can see what exactly is being passed into your PHP. That might help you see what is happening.
You are creating the following structure using the push method:
[
{
"key":"first_name",
"value": "Bob"
}
]
Using your code, all you need to do is index the postcmd variable to the object. You also had some indexing issues with your loop. The key variable would just be index 0. So you would need to set it to postcmd[key] to check for the key named "key".
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd[0]
});
}
Using the above snippet, jQuery will then parse the data into the correct key value pairs. Without specifying the index, the data would be posted as undefined=Bob
On the PHP side you should be able to grab those values as such:
<?php
echo $_POST['key'].PHP_EOL;
echo $_POST['value'];
?>
Alternative Method - JSON Submission
You could make the following modification to post the data as JSON:
function formsubmitplus(ele) {
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
contentType: 'application/json',
data: JSON.stringify(postcmd)
});
}
Then on the PHP side you can grab the POST body using the following:
<?php
echo "<pre>";
$json_data = json_decode(file_get_contents('php://input'), true);
print_r($json_data);
?>
If you would rather work with a PHP Object vs an Associative array. Just change true to false.
Ad the end I found a solution without jquery which works for me the best.
It is "playing" with HIDDEN form fields.
Maybe someone finds it helpful:
function submitform() {
Object.getOwnPropertyNames(postcmd).forEach(function(val, idx, array) {
var outarrayoutput = val + ' ==== ' + postcmd[val];
console.log(outarrayoutput);
var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'outArray[]';
newHidInp.value = outarrayoutput;
maintable.appendChild(newHidInp);
});
document.maintable.submit();
}

Can't send the value from Jquery to PHP

Each time I run this code, I get "VALUE IS EMPTY" message. Means the variable won't pass from Jquery to PHP variable $value. I need to pass it to PHP. Help me!
(#popup is a div which show up when a table tr is clicked. )
HTML+PHP Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup">
<?php
if (isset($_POST['val']) && !empty($_POST['val']))
{
$value = $_POST['val'];
echo $value;
}
else{
echo "VALUE IS EMPTY";
//each time I get this msg.. means it won't take the variable value to PHP
}
?>
</div>
JQuery/Javascript Code:
$(document).ready(function(){
$('#tableview tbody tr').click(function(){
var a=[];
$(this).find('td').each(function(){
a.push($(this).text());
});
$('#popup').show();
$.ajax({
url:'addfile.php',
data:{'val': a[1] },
type:'post',
success:function(res){
//Is there an error due to this function? or what?
}
});
});
});
-->There is no need to insert the code for the table.. hope this clarifies my question
ok, so here's a quick, basic guide:
Your html page, let's name it index.html (different to the php script!):
// index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup"></div>
<script>
$(document).ready(function(){
$('#tableview tbody tr').click(function(){
var a=[];
$(this).find('td').each(function(){
a.push($(this).text());
});
$('#popup').show();
$.ajax({
url:'addfile.php',
// HERE's A CRITICAL CHANGE:
// val MUST NOT be in quotes. You're creating a plain object here
data:{ val: a[1] },
// you can change that from type to method (default is get) - though type is an alias for method, so both should work.
method:'post',
success:function(res){
// here you have your data back from php, do with that what ever you need.
console.log(res); // will show value of a[1] in console
// my guess is, you want to show it in #popup
$('#popup').html(res);
},
error: function(error, status, errorString) {
// allways check for possible errors!
console.log(error);
console.log(errorString);
}
});
});
});
</script>
Your php script
<?php
// adfile.php
if (isset($_POST['val']) && !empty($_POST['val'])) {
$value = $_POST['val'];
echo $value;
} else {
echo "VALUE IS EMPTY";
}
// don't add a closing tag....
Finally: Please read about how ajax is proposed to work and read the manuals!

Manage json data outside ajaxform

I am using the well known ajaxForm Jquery Form Plugin (http://jquery.malsup.com/form/). I 'll present to you my code:
HTML code:
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
}
</script>
PHP code:
...
$result=$db->query($query);
if ($result->num_rows>=1)
{
$counter=0;
while ($row = $result->fetch_assoc()) {
$counter++;
$data1=$row["req_created"];
$data2=$row["subject"];
$temp[$counter] = array(
'elem1' => $data1,
'elem2' => $data2,
);
}
echo json_encode($temp);
}
As you may see from the above code, $temp is passed to var data inside function processJson. I'd like to know if array $temp is accessible outside processJson? For example, I want to choose $temp[3]["elem2"] upon a button click, however is it possible to get this data without searching again the database? If yes, how?
Thank you very much
You can have the data in variable, this will be like temporary storage.
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
var tem_data;
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
tem_data = data;
}
// Use tem_data anywhere;
</script>
But only last requested data will be the tem_data.
If you want all data then do it in array with array push method

jquery ajax() issue while printing array with each()

In my code I am returning an php array containing records of 7 Students. With jquery ajax() I want to print these records on success function.
DB table Students
+---------------------------+
| name | fathername | Email |
+---------------------------+
submit.php
$query=mysql_query("SELECT * from Students LIMIT 0,6");
$row= array();
$row=mysql_fetch_array($query);
return json_encode($row);
index.php
<script>
$(function(){
$("#form1").submit(function(event){
event.preventDefault();
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
$('.FatherName').text(result["fathername"]);
$('.Email').text(result["email"]);
});
}
});
});
});
</script>
<div class="StudentName"></div>
<div class="FatherName"></div>
<div class="Email"></div>
EDIT
I tried to return only 1 result from php and it works i.e.
echo json_encode(mysql_fetch_array($query));
When I return all 6 records the jquery function dont execute i.e.
while($result=mysql_fetch_array($query))
{
echo json_encode($result);
}
There's difference between PHP arrays and JS arrays, you can't simply pass the PHP array to your javascript, so instead you should first json_encode it and send it to js.
This will convert your PHP array to JSON array, eg:
array(3) {
[0]=>
string(3) "foo"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
to
string(33) "{"0":"foo","2":"baz","3":"blong"}"
So try -
return json_encode($row);
and then when you catch the response, use parseJSON:
result = jQuery.parseJSON(result);
$.each(result,function(){
$('.StudentName').text(result.name);
$('.FatherName').text(result.fathername);
$('.Email').text(result.email);
});
Edit:
Another thing, instead of return json_encode($row); write echo json_encode($row);
Edit 2
(to send all 6 records)
$final = array();
while($result=mysql_fetch_array($query))
{
array_push($final,$result);
}
echo $final;
function success(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
looks problematic. There doesn't really seem to be a reason to loop over the result, as you assign all of its contents to the same elements in the page.
However, assuming that result is an array of objects (like SQL queries usually produce it), then it should be
function(result){
$.each(result,function(obj) {
// missing parameter!!! ^^^
$('.StudentName').text(obj["name"]);
// access that here: ^^^
Also do a console.log(result) or simply browse the request URL to check whether the PHP scripts yields the expected response.
Here is an example of parsing JSON that may help you - http://jsfiddle.net/Su6QR/
Given that example, change your AJAX function -
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
var members = $.parseJSON(result);
$.each(members, function() {
var newStudent = '<span>' + this['name'] + '</span>';
var newFather = '<span>' + this['father'] + '</span>';
var newEmail = '<span>' + this['email'] + '</span>';
$('.StudentName').append(newStudent);
$('.FatherName').append(newFather);
$('.Email').append(newEmail);
});
}
});
This should return all of the data and place them into the divs that you have created. The formatting will not be what you want, but you should be able to fix that pretty easily.
This might help you.
Your AJAX
$("#form1").click( function(e){
var Somename = { };
$.each($('#form1').serializeArray(), function() {
Somename [this.name] = this.value;
});
e.preventDefault();
$.ajax({
type: "GET",
url: "submit.php",
data: { upddt_empID: upddt_empID, somevariable: "YES" },
success: function(data) {
alert('Successfull');
}
});
Your PHP
if(isset( $_REQUEST['somevariable'] ) )
{
$selItem = YourFunctionName( $_REQUEST['Somename ']['here your textbox id'], $_REQUEST['Somename ']['here your textbox id'],'yourtablename');
}
Your Query
function YourFunctionName(tablename)
{
$qry = "SELECT * FROM $tablename";
$result = mysql_query($qry);
return $result;
}

ajax recive variable value from php page

Through ajax I ask for a php page which will get some information from database. When data are processed I echo them to some tag and through JS I target those tags and get their content. This is the only way how I can pass data between php and JS but I feel it's not quite right. Whats the best way to get value of php variable:
$var1 = 24515875;
into JS variable?
When calling between PHP and JavaScript using AJAX, I suggest you always encode using JSON (Javascript Object Notation).
<?php
// Set Header (Always should be first commands just in case of thrown errors)
header('Content-type: application/json');
$data = array(
'message' => 'Hello World',
'error' => false
);
echo json_encode($data);
?>
For the javascript, you can use XMLHttpRequest. I don't suggest using jQuery unless you need it for other aspects of your script.
function request(url,callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var json = JSON.parse(req.responseText);
if(typeof callback === "function") {
callback(json);
}
}else{
// Handle Error
}
}
req.open("GET",url,true);
req.send();
}
function callback_func(json) {
// Function gets called when Ajax is finished
console.dir(json);
}
request("ajax.php",callback_func);
I don't know if the following suggestion is too complex, but:
you could use jQuery Ajax Get for requesting JSON data from PHP.
This is good for passing arrays, like results sets from a database to the client-side.
On PHP side you would do a simple:
<?php
header('Content-type: application/json');
echo json_encode($myData);
?>
On JS side you would access this with:
$.getJSON( "getjsondata.php", function( data ) {
alert(data);
// do whatever, like appending to html element
// next code section is the answer to your question from the comment:
// how to iterate over the data result set?
// create new DomElement for insertion: here foreach row a new list item
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
// then insert the list items into a UL and append that to the body
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
// to access the individual properties you would do
alert(data.property);
});
http://api.jquery.com/jquery.getjson/

Categories