I have an array in my index.php which is created by a foreach:
foreach ($events as $eventkey =>$event)
{
echo "<li class='desktop-2 tablet-1 mobile-1'>".$event->title."<span class='eventLetter'>A</span><br/><span class='eventLocation'>".$event->city."</span></li>";
$LocationArray[]= $event->latlng;
}
json_encode($LocationArray);
Now I want to use this array, in my javascript ( which is written in a different file..). But CAN I do this? and if so, how? (I'm new to php, and I'm really bad at AJAX stuff etc.. I've been looking around here and other sites but I can't really find the solution.)
The plan is to be able to loop over the array in my javascript and place markers at a google map which I have on my site.
The simplest solution would be to insert a new script tag with a javascript variable, and then assign the php array to that variable with json_encode. JSON (JavaScript Object Notation) is a text format for data-interchange between programming languages. Because JSON is based on the JavaScript decoding is not needed on the client side.
echo '<script>var myarray = '.json_encode($LocationArray).'</script>';
You would ideally use AJAX and fetch the output of json_encode($LocationArray)...
so your last line needs to be
echo json_encode($LocationArray);
Once this is taken back by the JS function that initiated the AJAX call, you can convert it into an array and loop it around. (expecting you are using jQuery, the code would look something like this...)
$.ajax({
url: 'index.php',
success: function(response) {
var resData = $.parseJSON(response);
for (var i = 0; i < resData.length; i++)
{
alert(resData[i]);
}
}
});
The easiest way I can think of is to do an echo before you link to the JS file.
echo"<script type='text/javascript'>\n var array={";
for($i=0;$i<sizeof($array);$i++){
echo "'".$item."'";
if($i<(sizeof($array)-1)){
echo",";
}
}
echo"};\n</script>"
That has not been debugged or tested, but it should give you the idea.
You are expecting a valid json output right?
<?php
foreach ($events as $eventkey =>$event)
{
echo "<li class='desktop-2 tablet-1 mobile-1'>".$event->title."<span class='eventLetter'>A</span><br/><span class='eventLocation'>".$event->city."</span></li>";// remove this thing or maybe place it in a variable. do not echo it.
$LocationArray[]= $event->latlng;
}
echo json_encode($LocationArray);
on your script
$.ajax({
url:"",
success: function(data){
var json = jQuery.parseJSON( data );
for (var i = 0; i < json.length; i++) {
alert(json[i]);
//Do something
}
}
})
Related
I use this in a function:
$.ajax({
type: 'POST',
url: 'demopost.php',
data: { ... },
dataType: 'json',
success: function(data)
{
console.log(data);
}
});
The demopost.php contains only a query.
The output will be:
But how can I show it inside a div? OR How can I add some formation e.g. with foreach like a php array?
EDIT:
I tried with it (the place of console.log(data):
$('.inner').append(data);
Of course there was a div with class inner. But nothing show
EDIT2:
The query in the demopost.php:
... try
{
$c_id = htmlspecialchars($_POST['cid']);
$leftprice = $_POST['left'];
$rightprice = $_POST['right'];
$items=$main->pdo->prepare("SELECT name, price FROM clf_items WHERE category_id IN (
SELECT node.id
FROM clf_category AS node,
clf_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt AND price BETWEEN :left AND :right
AND parent.id = :c_id)");
$items->execute(array(':c_id' => $c_id, ':left' => $leftprice, ':right' => $rightprice));
$items_array = array();
while ($row = $items->fetch(PDO::FETCH_ASSOC))
{
$items_array[] = $row;
}
echo json_encode($items_array);exit;
}...
What you are doing here is to return some JSON data from the server which can be read by javascript, but is not useful to be pushed into HTML without some processing.
One solution would be to get the JSON array you receive and transform it into a HTML string before pushing it onto the page. This might look like:
success: function(data)
{
var result = '<table>';
for (i=0; i<data.length; i++) {
result += '<tr><td>'+ data[i].name+'</td><td>'+data[i].price+'</td></tr>';
}
result+= '</table>';
$(".inner").html(result);
}
Now this has not money formatting, no html escaping, very crude layout etc pp. Before you try to make this raw sketch into something useful I recommend looking into the various template engines available for jQuery; a few are listed in this post: jQuery Templates are deprecated? (and unlike the question suggests, jQuery templates are not dead, but got some competition).
However I would prefer another approach: create the HTML server side (instead of JSON), so you return a HTML snippet the same way you would return a full HTML page normally in PHP, and in the ajax request say you want HTML: dataType: 'html', and then you can push the result straight into $(".inner").html(data) (or $(".inner").append(data), no idea how your HTML should look like), as you originally wanted.
I guess this is the same as schwierig wanted to say, but I feel one need to tell it more explicit.
For what reason are you using Ajax if you are not processing the data you are sending? If you just want to format the data, you don't really need PHP to do that.
Of course it would be possible. If you want to process with PHP you need to echo your formatted result and use the .done() function as described in the jQuery API
http://api.jquery.com/jQuery.ajax/
$.post('demopost.php',{..}, function(data) {
$('.inner').html(data);
});
try this one hope it will help and make sure you have div with inner class
So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.
What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.
I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.
Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>
This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}
I have a little problem. I want to pass two variables from PHP to $.ajax success function
I have this code written in JS:
$.ajax({
type:"POST",
url:path,
data: "value="+info,
success:function(data,data1)
{
if(data==1)
{
$(id).css("backgroundColor","green");
$(id).attr("readonly","readonly");
$(image).attr("src",data1);
}
else
{
$(id).css("backgroundColor","red");
}
}
});
And my PHP code is :
if(isset($_POST['value']) and !empty($_POST['value']))
{
$result=0;
$image="src/photo1.jpg";
$value=trim($_POST['value']);
if($value=="Abracadabra" or strcmp($value,"Abracadabra")==0)
{
$result=1;
$image="src/abracadabra.jpg";
}
else
{
$result=0;
$image="src/photo1.jpg";
}
echo $result;
echo $image;
}
There, I want to "echo" two variables simultaneously to pass to $.ajax success function.
It is possible ? I don't refer to JSON, I refer only PHP with POST method.
Thank you
the response from php code will be something like:
0src/photo1.jpg
and you will have to parse it with the javascript (probably with regex or substring)
success:function(data,data1) {
var result = data.substring(0,1);
var image = data.substring(1);
// ... your code
}
keep in mind that it could cause you trouble if the $result variable is more than one character long :)
have PHP echo a string like "value1|value2|etc" (or whatever other character(-sequence) is unlikely to wind up in the actual data)
then on the javascript side do a string.split('|') to break the returned string up into a neat little array. you could even do key1:value1|key2:value2
and then use the solution presented here to split the key:value pairs up into an object.