I've got a PHP array...
<?php
$tweets = array(
'1' => array(
"title" => "title",
"challenge" => "challenge",
"answer" => "answer",
"type" => "type",
"class" => "class",
),
/* .... */
)
?>
That I need to go fetch data from using AJAX and for the life of me, I can't get the data that I need.
What I've got right now is...
var challenge = 10;
var tweets = <?php echo json_encode($tweets); ?>;
$('.cur_race_title').html(tweets[challenge]['title']);
$('.cur_race_challenge').html(tweets[challenge]['challenge']).addClass(tweets[challenge]['class']);
$('.cur_race_answer').html(tweets[challenge]['answer']);
$('.tweet-submission').addClass(tweets[challenge]['type']);
(Note: the challenge number is a variable that changes)
Using PHP's json_encode, I get an array of all of the values in the PHP file (which is included earlier on the file) and then use the challenge ID to populate the data.
The downside is that this shows the data for the entire array - I'd like to only show the data for the single challenge defined by the ID above.
Any help would be greatly appreciated.
Thanks!
I wouldn't recommend generating JavaScript variables with PHP tags.
Use: http://api.jquery.com/jquery.getjson/
$.getJSON("myurl.php", function(JSON){
//do something
});
PHP Side: Returning JSON from PHP to JavaScript?
header('Content-type: application/json');
echo json_encode( $myArray[ $myId ] );
Related
So I have the following JSON:
[{"username":"User1","password":"Password"},
{"username":"User5","password":"passWord"},]
Generated from:
<?php $username = $_POST["username"]; ?><br>
<?php $password = $_POST["password"]; ?><br>
<?php
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
$extra = array(
'username' => $username,
'password' => $password
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
print("working");
}
?>
After the user logs in they have the ability to make a post, how would I go about creating a post array for each user and how would I add to it dynamically ?
This is all I have and I have tried many different ways, but cant seem to figure out how to make it dynamic.
<?php
$urlText = $_REQUEST["urlText"];
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
//for loop
$array_data[i]['Posts'] = $urlText;
//end for loop
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
}
?>
In this situation though, posts is not an array, it just simply overwrites what already there.
[{"username":"User1","password":"Password","Posts:{"This is a post"}},
{"username":"User5","password":"passWord"},"Posts:{"This is a post2"}}]
Therefore, how do I add a posts array and how do I add to it dynamically ? I have not been able to figure such a simple thing out for a very long time
File get contents from like "posts/useridhere.txt", or allposts.txt
You will also need to use unique post IDs.
Json decode your posts JSON
Add post content to array
Json encode array
Write new json to the users post file
Ultimately I do not recommend this. If you want a paid internship I'll teach you how to use MySQL. We make websites :) but if you want to do it this way, you'll need a JSON file to store unique post IDs or even store all posts in one file. The problem is that you'll have a limit of how many posts can be stored in that single JSON array. I hope this answer is enough to help you. It's all the steps needed
$posts = file_get_contents($postsFile);
$posts = json_decode($posts);
$newPost = array(
"user"=>$user,
"postTitle"=>$string,
"text"=>$content
);
$posts[] = $newPost;
$newPostID = count($posts); // will not work properly (for linking posts) once you delete a post - you need unique post ids generated!
$posts = json_encode($posts);
// Overwrite your posts file with $posts. It will have all posts you need :)
The idea here is to automatically load (or load at all) my index page with some products out of a MySQL database table.
Firstly, my PHP.
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
echo json_encode($itemsJSON);
}
This seems to be working great, and gives me two properly encoded JSON objects of my Item class.
{"name":"Slippers","quantity":"3","cost":"4.00"}
{"name":"Gloves","quantity":"5","cost":"9.00"}
My JavaScript looks like this(and many other similar variations)
$(document).ready(function () {
$.post( "productloader.php", function( data ) {
$( "#result" ).html( data );
});
});
I'm not sure why it is not working. I did not want to use $.getJSON() because there is no query string to work with, so I'd assume I would need $.post().
It seems like this is a pretty common issue, but I've not found a solution yet. Any help would be appreciated. Thank you.
You can't json_encode() each item separately. The data you're sending to the browser is not valid JSON, just many little chunks of valid JSON one after the other. Build an array inside your loop and then encode the whole thing. See also http://jsonlint.com/
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON[] = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
}
echo json_encode($itemsJSON);
In your method of AJAX, you're outputting multiple JSON strings while the js side is expecting 1 string (data). Try removing your for loop to just:
echo json_encode($items);
You are creating JSON for each row, so you are getting separate JSON objects for each row in front end.
You should put all row in to and array and create the JSON object outside the loop, and echo the encoded JSON string.
<?php
$allitem = $db->getRows('SELECT * FROM products');
$itemArr=array();
foreach($allitem as $item){
array_push( $itemArr , new Item($item->product_name, $item->product_quantity, $item->product_cost) );
}
echo json_encode($itemArr);
?>
or
$allitem = $db->getRows('SELECT * FROM products');
echo json_encode($allitem );
PHP to Javascript with values from Wordpress
I hope the following code explains what i want.
<?php
$title = array();
$i=0;
if ( have_posts() ) : while ( have_posts() ) : the_post();
$title[i]=the_title();
$link[i]=the_permalink();
$i++;
endwhile; else:
$title[0]="Welcome to my website.";
$link[0]="/index.php";
endif;
?>
<script>
var list=new Array();
list[0]='<?php echo $title[0] ?>';
list[1]='<?php echo $title[1] ?>';
list[2]='<?php echo $title[2] ?>';
list[3]='<?php echo $title[3] ?>';
list[4]='<?php echo $title[4] ?>';
</script>
My need is to
get the latest/popular 5 post title and its permalink
then assign it to the javascript variable like in the above code or better
Why I need this
Iam creating a simple & working news website wordpress template. And I used a javascript code(got from the web) that will display any text i put inside a specific array variable like a scrolling text( in a flash news/breaking news style).
Now I want the scrolling text to be dynamically updated with the latest blog/news post instead being static like now.
...
var list=new Array();
list[0]='<a href="This is manually typed news one.';
list[1]='<a href="This is manually typed news two.';
list[2]='This is manually typed news three.';
list[3]='This is manually typed news four.';
list[4]='This is manually typed news five.';
...
Reference
The website iam creating currently is temporarily available on this address
www.iamone.in/todaynewstv.
Look at the Flash News section - that is what iam talking about.
I got the complete javascript code from http://javascripts.vbarsan.com/
In short, The Output Iam expecting is
To display the latest 5 or 10 blog posts in a scrolling text style without manually updating.
[Sorry for any wrong communication on my side. Hope you people understand my question. ]
Thanks. :)
Just json_encode the array. Here is an example:
First you get your posts:
$args = array(
'posts_per_page' => 5,
'offset' => 0,
'post_status' => 'publish'
);
$posts_array = get_posts( $args );
Then you json_encode it in a script tag.
<script type="text/javascript">
jQuery(function(){
var postArray = <?php echo json_encode($posts_array); ?>;
console.log(postArray);
for (e in postArray) {
var postInfo = postArray[e];
console.log(postInfo);
//how to get the title:
var postTitle = postInfo.post_title;
}
});
</script>
The console log will show you which data you can access. Here is a screenshot:
I'm trying to send php array data using ajax.
Maybe this is not the correct method, so if there is a better one, I will be happy to know.
Anyway, I do not want to use JQuery, but a pure ajax.
I convert the php array to a string (in order to create an array back in the destination php)
$aData = array(
"Function" => "runRequestedFunction",
"ReqFunctionName" => "Lomba",
"ReqFunctionData" => 74
);
$sendvar = "data=".serialize($aData);
Then I send it using ajax
cAjax = new XMLHttpRequest();
--- there is some code here for callback ---
cAjax.open("POST","doSomthing.php",true);
cAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
cAjax.send("<?php echo $sendvar; ?>");
The problem is that the string $sendvar contains double quote (") which break the data received in the doSomthing.php file.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$aData= $_POST;
echo "Postinput: "; print_r($aData);echo "</br>";
}
?>
The echo output the follow
Postinput: Array ( [data] => a:3:{s:8: )
This is because the string is
a:3:s:8:"Function";s:20:"runRequestedFunction";s:15:"ReqFunctionName";s:5:"Lomba";s:15:"ReqFunctionData";i:74;}
so the first double quote breaks the data.
Try using single quotes:
cAjax.send('<?php echo $sendvar; ?>');
I am sending data from PHP to jQuery. Everything works fine except I want to sent the total rows from the DB.
I have stripped a lot of other things to put onlu the essential problem.
PHP code:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array with the data; That is working fine
$total=mysql_num_rows($RSList);
$total_data=array("total"=>$total);
array_push($data,$total_data,$rows);
echo json_encode($data);
jQuery code:
$.getJSON("..url..", function( data ) {
var data_array = eval(data);
$.each(data_array[0], function(i, item ) {
console.log(item)
});
});
The result showing in the browser is:
[{"total":532},[{"product_id":"1",.... }]]
532 is the correct value from the mysql_num_rows()
Console:
An empty string
I tried the following:
If I set the value manually of total in PHP:
$total=100;
The result showing in the browser is:
[{"total":100},[{"product_id":"1",.... }]]
Console of java:
100
If I convert the value in string in PHP:
$total="(".$totalRows_RSList.")";
The result showing in the browser is:
[{"total":"(532)"},[{"product_id":"1",.... }]]
Console:
()
I have also tried intval, number_format and strval with no success.
Very, very strange or ?
Update:
I have modified as suggested the code and still the same problem:
PHP:
echo json_encode(array('total' => $total, 'rows' => $rows));
javscript:
$.getJSON( "..url..", function( data ) {
console.log( data )
$.each( data.rows, function(i, item ) {...}
})
Browser:
{"total":532,"rows":[{"product_id":"567",...}]}
Console:
Object { rows=[99], total=""}
You don't need to pass the total rows, just get the length of the parsed JSON object.
jQuery code:
$.getJSON('...url...', function(data){
console.log(data.length);
}
PHP Code:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array_with_the_data; //That is working fine
echo json_encode($rows);
Note: This answer explains what is wrong with your code. Learn from it, then look at #ojovirtual's answer which shows what I think is the best way for you to accomplish what you were intending to do in the first place. End Note
Remove the eval statement from your code. jQuery will have already parsed the incoming JSON (if it is valid) and your success function will receive your array as the data param. Just use that data param instead of data_array.
$.getJSON('..url..', function (data) {
// if your PHP is sending proper JSON in the format you describe, `data` is now
// an array containing two items. The first (`data[0]`) is an object which has
// one property, `total`. The second (`data[1]`) is your array of row data, each
// of which is an object.
// your code in modified form, though I don't understand why you would use `each`
$.each(data[0], function (i, item) {
console.log(item);
});
// just use:
console.log(data[0].total);
});
Be sure to read the comments in the above code.