JSON output on HTML page - javascript

I want to display a JSON object on a html page. When I enter
productArray[0][0].xyz
into the Firefox console then I get a value back.
Question:
How can I display the value which is stored in this variable on a HTML page?
I have tried this (didn't work):
<div id="test">
<script>
window.onload = function()
{
var out = productArray[0][0].xyz;
document.getElementById("test").innerHTML = out;
}
</script>

Since it's working in console in browser, I guess it's a timing problem. You're probably trying to use the value in the json before the json data is loaded and ready to use.
Assuming you're running an xhttp request or ajax call or something you'll have to run the code AFTER data is loaded. Which often means running it inside successmethod.
Maybe this post and answer helps you locate the problem? NB: This uses Ajax, so feel free to update your post with some more information so we can help you with your solution / technologies.
Ajax success function

Assuming that missing div close tag is a typo most probably the productArray is not populated by the time your code executes. Can you post a more detailed snippet ?

var out = "your value";//productArray[0][0].xyz commented to show you running code uncomment it when you use this in you code. ;
document.getElementById("test").innerHTML = out;
<div id='test'></div>
You actually forgot to close the DIV tag.

Related

Can I shorten this script? (update DB table and refresh)

I really want to know if there is a shorter alternative to writing this code. I have attempted to shorten it to 2 or 1 functions and achieved miserable failure. I'm seeking constructive feedback!
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function f_solar_1() {
$.get("f_solar_1.php");
return false;
}
</script>
<script type="text/javascript">
function refresh(){
location.reload(true);}
</script>
<script type="text/javascript">
function both(){
f_solar_1()
setTimeout(refresh, 5);
}
</script>
Activate
Details:
This code is an excerpt from my php page that displays a table from my mysql database (I'm using wamp).
The "Activate" text at the bottom is supposed to UPDATE a variable on that table, and does so via the f_solar_1.php file.
The issue is the table reflecting the database does not automatically reflect this change.
So I made a "reload()" function to refresh the page, and the "both()" function to time the refresh after updating the database.
I have known basic html for a while, but I am new to mysql, ajax, and php as of this morning, and this is my attempt to dive into it.
My code works fine, it just bothers me not knowing if I can accomplish the same thing within one function.
Thank you in advance!
UPDATE: Thankyou to Dat Pham for pointing me in the right direction!
<script type="text/javascript">
function newfunc(){
$.get( "f_solar_1.php", function( data ) {
location.reload(true);
});}
</script>
<span onclick="newfunc();">newfunc</span>
The code is all in one function (well...) and without causing a refresh and php recall timing conflict.
Making 1 function do all the thing is considered bad practice, a function should do and only do an atomic task. Your code is fine except some minor points:
ajax call $.get() and location.reload should not be used with each other as this destroy the meaning of ajax call. You can pass a callback function to handle data from backend server like
$.get( "f_solar_1.php", function( data ) {
alert( "Load was performed." );
});
Combine all your script tags into 1 with all your function declare
Regards,
Have you checked the database through the backend (phpmyadmin for example) and verified if the changes are being made even though it's not displaying?
i'm wondering if your page isn't really refreshing, and simply going to "#". Check the "return false" - it's not really applying to the "A" link, you would have to put "return false" in the 'both' function for that to cancel the link. But you might not want to do it that way after taking a minute to read this: The return false onclick anchor not completely working
additionally, I'd recommend using the jquery add event listener to trigger your function calls, and get the onClick out of your html tag. Bonus if you learn how to do it without jquery. Read this real quick jquery href and onclick separation

Javascript not working when echo'd by php

I have the problem when i echo this:
echo "Logged in! <script> alert('hello'); </script>";
The message "Logged in!" appears, but not the alert. How can i fix it so i get the alert? I can't use header(); because i already echod things out!
I also tried multiple thing like:
echo "Test message <script> window.location.href = 'index.php';"
Same thing again, Test message was echo'd, but the script wasn't run.
I hope someone can help me!
Edit:
NOTE: All of this code is in a xml file that i get that response of and put that in a div. So the script is in a message that i get with responseXML and output the data in a div.
Question i have in 1 sentence: How can you run a javascript function in a ajax call without jquery?
I'm guessing you call this script through ajax after the page is already loaded. In this case it's not surprising the script isn't running because the browser runs the scripts as it reads them and isn't on standby for another script tag to appear.
If this is the case, you can solve this by adding some event listener or even better, call a desired function in the end of the ajax response.
Your PHP looks fine, but you might need to change the way that you collect the JavaScript.
Consider this example:
http://jsfiddle.net/0vcewvkc/1/
If you are collecting JavaScript only, you can wrap the response in a jQuery tag ($()), and then append it to your document.
$("#go").click(function() { // call the function here
// your ajax code would go here, but either way you will end up with a string of JavaScript
var response = '<script>alert("hi");</' + 'script>';
// use jQuery to append this script to your document's body, like so:
$(response).appendTo(document.body)
});
Update
To do this without jQuery, the end of your AJAX call would have this code:
var response = 'alert("hi");'; // note that we have removed the <script> tag
var s = document.createElement("script");
s.innerHTML = response;
document.getElementsByTagName('body')[0].appendChild(s);
try the following this should work
<?php
echo 'Logged in ';
?>
<script> alert("hello")</script>;
<?php
// the rest of your php code
?>

Counting the number div loaded from external php file

I have two php files, child.php and parent.php. Child.php generates div. Now, the parent.php calls child.php to be loaded in <div id='divContainer'>. Now, I need to count the div inside the divContainer. Is it possible?
I tried something like this:
$(document).ready(function () {
var total_record = $('#divContainer > div').length;
alert(total_record);
});
But it's not working. Even an empty alert is not popping out.
Can someone here, help me on this? THank you!
There's a syntax error:
)};
Should be:
});
Often if you are not getting any output/result at all when expected, it is down to a syntax error which will cause the browser to be unable to parse and execute the code. For future debugging, use the error console as this normally points out any errors with a decent description of the problem.

jQuery AJAX is not showing output after first PHP conditional

I am having trouble using the jQuery AJAX call. The query runs properly and debug output also shows the correct data, but anything apart from the first PHP conditional in the document being called is not being shown.
First, there are two buttons, one linked to "core" the other "email":
Here's the relevant JavaScript:
$("#core").click(function(){
loaddetails ("core");
});
$("#email").click(function(){
loaddetails ("email");
});
function loaddetails(type) { var query = "details=" + type;
$.post("details.php", query , function( data ) {
$("#d-features").html(data); alert (data);});
return false;
};
And the contents of details.php:
<? if($_POST['details']=='core'){ ?> blah1 <? }
if($_POST['details']=='email') { ?> blah2 <? } ?>
Both "blah1" and "blah2" appear in the alert box debug output. But, only "blah1" ever gets posted on the page div (#d-features), as "blah2" never appears on the page.
I have checked Firebug and there are absolutely no errors. But I suspect the second conditional request may have gone in a loop, as the alert window showing up when "email" button is clicked shows "Prevent page from creating additional dialogs", though no additional dialogs show up even when unchecked.
What is causing this problem and how to fix it?
.html() replaces the content instead of appending.
Try changing that line to see if all the data is returned from both calls:
$("#d-features").html(data); ==> $("#d-features").append(data);
A small modification on your code, you could try to see if this works:
function loaddetails(type) {
$.post(
"details.php",
{
details: type
},
function( data ) {
$("#d-features").html(data);
alert (data);
}
);
return false;
}
Ok, it seems to be a conflict with the tabs effect I loaded for a div that encompassed these links. So once I removed that effect, it works now. But I'm not sure what is wrong with the effect yet, I'll post another question to figure it out.
Thanks to those that offered assistance!

jQuery - Click on X, grab the NAME, then use that to show a related element

Here's what's happening.
My page loads. Then jQuery loads a feed which is injected into a contentCol div...
in that feed is:
Comment
There is also:
<div class="storyItemComments" id="storyItemComments_66" style="display:none;">....
For some reason this is not working:
$(".commentWrite").live("click",function(){
cmt2open = $(this).attr('name');
$("#" + cmt2open).show();
return false;
});
Any ideas? The only thing I can think of is that it has something to do with the fact that I am using jQuery AJAX to load in the content which the LIVE statement above is referencing....
thanks
on most occasions people should use the die() function before the live... so that will clear any previews instructions and that function is only triggered once...
another thing could be that the instructions are called before the contents are retrieved from the ajax. therefore you should use .success to check if the ajax was successfully loaded and then trigger the click instructions.
as it seems that the <div id="storyItemComments_66" has not been picked up from the DOM.
Following from your comment to this answer
Can you try the following instead of show()?
$("#" + cmt2open).attr('display', 'block');
Can you place your javascript inside;
$(document).ready(function(){
//your code here
});
Not sure this will fix it but it's good practice I find.
Also have you alerted out your variables to see what you get?
What is the error you are getting if any?
Have you tried putting an alert at the top of the function to see if the click event works?
edit
let me know if the above does not fix it and I'll remove this answer to clear out the noise

Categories

Resources