It's my first time on StackOverflow, please forgive me if I forget some important information or if my question sounds stupid!
I am building a web site which generates a list once the user writes a word and hits the "Send" button. Php is responsible for extracting the required data and returning it to the web page as a list.
My problem is that I then want to pass this data in a js function. I have read a lot of answers on StackOverflow concerning this, and it sounded like a callback function is what I needed. However, my js function keeps telling me that my node is null; it seems the data returned from ajax is not accounted for.
Here are some parts of my code:
<script>
var xmlhttp;
function loadXMLDoc(cfunc){
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var us = document.getElementById("user").value;
var ur = document.getElementById("wiki").value;
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET","contributions_old.php?user="+us+"&wiki="+ur+"",true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc(function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("result").innerHTML=xmlhttp.responseText;
var parser = new DOMParser ();
var responseDoc = parser.parseFromString (xmlhttp.responseText, "text/html");
var text1 = responseDoc.getElementById('old1').value;
var text2 = responseDoc.getElementById('new1').value;
var dmp = new diff_match_patch();
dmp.Diff_Timeout = 0;
// No warmup loop since it risks triggering an 'unresponsive script' dialog
// in client-side JavaScript
var ms_start = (new Date()).getTime();
var d = dmp.diff_main(text1, text2, false);
var ms_end = (new Date()).getTime();
var ds = dmp.diff_prettyHtml(d);
document.getElementById('outputdiv').innerHTML = ds + '<BR>Time: ' + (ms_end - ms_start) / 1000 + 's';
}
});
}
</script>
It's of course the Send button that calls myFunction() at the bottom of my web page, once the user has entered a word.
I have also verified that my web page, once the list has been generated, has the divs with "new1" and "old1" as ids (they are generated through my php code).
Any help would be really appreciated! I feel like I've tried everything!
Thank you! :)
Highly recommend using jQuery or some other lib for this.
var url = "contributions_old.php?user=" + $("#user").val() + "&wiki=" + $("#wiki").val();
$.get(url);
Related
How to make javascript code execute on php page which was previously loaded from an ajax call?
code samples:
ajax+function parseScript to force javascript to run on the ajax requested page
Senario: I am selecting a question from selectQuest.php and using ajax it request a page called showRecord.php.
The page showRecord.php will display a table which contain the information corresponding to the quetsion selected.It contains the javascript that do not run.The javascript return will allow me to update info in db when i click submit.
The code sample below is found in the showRecord.php.Finally, if the latter run the showRecord will make another ajax request for updateQuestion.php.
But the javascript is not running in showRecord.php
function show(fileTex,aTex,bTex,cTex,dTex,eTex,newQuestNumTex,textAreaTex,textQuesAnsTex)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
var resp=xmlhttp.responseText;
document.getElementById("txtHint2").innerHTML=resp;
parseScript(resp);
// document.getElementById("txtHint").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("POST","updateQuestionAdmin.php?param="+fileTex+"&text_A="+aTex+"&text_B="+bTex+"&text_C="+cTex+"&text_D="+dTex+"&text_E="+eTex+"&text_ID="+newQuestNumTex+"&text_Ques="+textAreaTex+"&text_Ans="+textQuesAnsTex,true);
xmlhttp.send();
}
// this function create an Array that contains the JS code of every <script> tag in parameter
// then apply the eval() to execute the code in every script collected
function parseScript(strcode) {
var scripts = new Array(); // Array which will store the script's code
// Strip out tags
while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
var s = strcode.indexOf("<script");
var s_e = strcode.indexOf(">", s);
var e = strcode.indexOf("</script", s);
var e_e = strcode.indexOf(">", e);
// Add to scripts array
scripts.push(strcode.substring(s_e+1, e));
// Strip from strcode
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
}
</script>
As iyrag said, a Javascript framework would help. jQuery has a callback function that you can run when a script is successfully loaded and finished with ajax.
You'll want to execute some other stuff within that callback function, for instance :
$.ajax({
url: 'test.php',
success: function(data) {
$('#result').html(data); // Display script return on some div
someFunction(); // blabla
// Execute some other javascript here, you'll be abble to access the DOM of the test.html
// page because here you'lle be sure that test.html is loaded.showRecord.php should not contain javascript, which would rather be here
}
});
I also posted this because the tag features jQuery...
for (m=0;m<z;m++) {
document.write("<img src=" + image1 + '>' + "<br>");
}
I'm successfully getting a list of image URLs from an XML file via PHP.
The var 'image1' returns 'image_1.png'.
In the above loop I want to output these images. 'image1' above displays 'image_1.png' twice (z=2 in this case), but I'm after a list of all the images. I want to throw in something like 'image[m]', but i know thats not right.
I'd be surprised if anyone hasn't asked this question before, I searched but couldn't find an answer.
This is the PHP thats getting my XML data:
<script type="text/javascript">
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","../../file.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("project")
var j=xmlDoc.getElementsByTagName("imagelist");
for (i=0;i<x.length;i++) {
for (z=0;z<j.length;z++) {
this["image" + z] = j[z].getElementsByTagName("image")[z].childNodes[0].nodeValue
}
}
Whoa. Ok. This right here:
this["image" + z] = j[z].getElementsByTagName("image")[z].childNodes[0].nodeValue
Don't do that.
This is dynamically creating variables in the global scope. I could explain why that is (this here is the global object, and properties of the global object are themselves global variables), but for novice JS programmers it's probably sufficient to say that you should just never do that because, generally, it's a pretty bad idea.
Instead, what you really want is an array.
var images = [];
for (i=0;i<x.length;i++) {
for (z=0;z<j.length;z++) {
images.push(j[z].getElementsByTagName("image")[z].childNodes[0].nodeValue);
}
}
Now your loop later is pretty straight forward. You simply use the loop index as the array index to fetch the value you want.
for (m=0;m<z;m++) {
document.write('<img src="'+ images[m] +'"><br>');
}
<script type="text/javascript">
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","../../designportfolio.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var projectname = "<?= $name ?>";
var x=xmlDoc.getElementsByTagName("project")
var j=xmlDoc.getElementsByTagName("imagelist");
var k=xmlDoc.getElementsByTagName("image");
for (i=0;i<x.length;i++) {
//vars from xml used to display data in html
var folder = x[i].getElementsByTagName("folder")[0].childNodes[0].nodeValue;
//only defines the data if the projectname and folder name match
if (folder == projectname) {
var projecttitle = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var projectinfo_l = x[i].getElementsByTagName("projectinfo_l")[0].childNodes[0].nodeValue;
var skillsused = x[i].getElementsByTagName("skillsused")[0].childNodes[0].nodeValue;
var date = x[i].getElementsByTagName("date")[0].childNodes[0].nodeValue;
var videoURL = x[i].getElementsByTagName("videoURL")[0].childNodes[0].nodeValue;
var images = [];
for (z=0;z<k.length;z++) {
images.push(x[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
document.write("images " + images + "<br>");
}
}
}
im in a total mess. im using an IF to pick only one project, this works. I want only the images from this project. the above code is getting all the images in the xml file (13 of them), i want ONLY the images from the current project (the project corresponding to 'folder' or 'projectname'). I cant do this :(
You have an array of images that you would like to render with js. There are several approaches. The sample code you have in the question is probably the worst way to do it.
Don't use document.write() to do this.
All examples assume 'images' is an array containing n-number of image urls.
Example 1
var images = [],
target = document.getElementById('target_div'); //this is the location in the document where the images are appended to
for(var i=0, len=images.length; i++){
var img = document.createElement('img');
img.src = images[i];
target.appendChild(img);
}
Example 2
var images = [],
target = document.getElementById('target_div'); //this is the location in the document
var arr = [];
for(var i=0, len=images.length; i++){
arr.push('<img src="'+ images[i] +'">');
}
target.innerHTML = arr.join('');
I'm trying to find the answer somewhere around but i can't,
So i'm having a .bind() event and I want when's triggered to make a get query from a php file with JSON like AJAX does.
I have tried the following which doesn't work:
$(document).ready(function() {
$("#adivhere").bind("valuesChanged", function(){
// Some variables here
var max2 = 10
var min2 = 5
//The classic AJAX Request
function afunc(max2,min2){
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
//The classic AJAX onreadystatechange function
xmlhttp.onreadystatechange=function()
{ if (xmlhttp.readyState==4 && xmlhttp.status==200){
//The code triggered
var fets = jQuery.parseJSON( xmlhttp.responseText );
var t = fets.date.split(/[-]/);
var d = new Date(t[0], t[1], t[2]);
alert(d);
}}
//The XHR request with the .php file and the
// two values that sends
xmlhttp.open("GET","getdates.php?max2="+max2+"&min2="+min2,true);
xmlhttp.send();
};
});
It looks like you're using jQuery, so this should work:
$(function(){
$('#adivhere').bind('valuesChanged',function(){
var max2 = 10;
var min2 = 5;
$.getJSON('getdates.php?callback=?', {max2: max2, min2: min2}, function(json){
alert(json);
var t = json.date.split(/[-]/);
if (t && t.length) {
var d = new Date(t[0], t[1], t[2]);
alert(d);
}
});
});
});
There's already an awesome $.getJSON method in jQuery that will do all of the heavy lifting for you, including return your results as JSON.
You'll need to make your getdates.php script echo the callback and wrap your results in parentheses so it returns as actual jQuery.
There are several "errors" in your script:
"afunc" is never called, so why should it be executed?
the parenthesis are not closed properly; at the end there are two missing: )}
I am building a website with user-profiles. I am at the picture part at the moment. When a person upload their image with no problem, the picture will be stored in 4 different folders. One for size 25, 100, 150 and normal size. After this they will be redirected to the same page, with new content. This is the part, where they need to crop their picture. Crop part works great, but I have a problem. When they leave the site without cropping, the pciture they just uploaded is still stored in the folders, and that's not what i want. So i mate some checks with AJAX, and it will unlink the 4 files sotred already. My problem is, that this shall only happen, when they leave the site(onbeforeunload.)
This works very great in IE, but not in Chrome.(Only two browsers i've tested yet.)
Here is what I'm doing:
function unfinished(album,img){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
}
The function above get information from "uncl/unfinished.php" by the query string. And it all works well.
Code on unfinished.php:
session_start();
require('../dbconnect.php');
$sql = "SELECT * FROM users WHERE username='".$_SESSION['username']."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$username= $row['brugernavn'];
}
$album = $_GET['a'];
$img = $_GET['i'];
$sourcex = "../users/".$username."/images/".$album."/x-x/".$img;
$source25 = "../users/".$username."/images/".$album."/25/".$img;
$source100 = "../users/".$username."/images/".$album."/100/".$img;
$source150 = "../users/".$username."/images/".$album."/150/".$img;
if(unlink($sourcex)){
}
if(unlink($source25)){
}
if(unlink($source100)){
}
if(unlink($source150)){
}
echo "Error 908. The picture didn't get cropped, and neither saved. Try again.";
The AJAX code and unfinished.php deletes the images withpout any problems. I've tested that already. Now my problem:
I am running the AJAX code by
The code should be running inside this:
//function warn(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = unfinished(album,img);
}
// For Safari
return unfinished(album,img);
};
//}
But when i try to return xmlhttp.responseText, the popup box doesn't popup, and i am not able to see the response.
But if i add "Hello world"(or some text) to the return like return Helloworld!''; or e.returnValue = 'Hello world!';, instead of the xmlhttp.responseText value, it pops up, and display the message. But it doesn't display the xmlhttp.responseText, because it doesn't run the unfinished() function.
any solutions how i can run the AJAX when user leaves page?
If it helps here is the HTML code:
if($_POST['where'] == "newalbum"){
$nameonalbum = $_POST['nameonalbum'];
}else{
$nameonalbum = $_POST['existingalbum'];
}
$filenamenew=time().'.gif';
?>
<body onload="warn('<?=$nameonalbum?>','<?=$filenamenew?>')">
Solved it by myself. Did like this:
function unfinished(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
var response = '';
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
response = xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = response;
}
// For Safari
return response;
}
}
But now i have another problem... 1st of all the unload function works great, but I don't want it to trigger when the "Save crop" button is clicked. Any ideas how to do this?
Save button html:
I am not aware of the proper terminology or jargon with programming, so forgive me if this question is unclear. To make if more clear here is the code I have written so far. I will explain the problem in more detail after the code:
I use this code to retrieve data from Facebook:
function rsvpEvent() {
FB.api('/me/events/', function(response) {
for (var i=0; i<=2; i++) {
eventname=response.data[i].name;
eventid=response.data[i].id;
eventstatus=response.data[i].rsvp_status;
eventInfo(eventname,eventid,eventstatus);
strEvent=strEvent + "You are " +
eventstatus + " " + eventname + ", EID: " + eventid + "<br/>";
}
document.getElementById('rsvpEvent').style.display = "block";
document.getElementById('rsvpEvent').innerHTML = strEvent;
});
}
Request to PHP file (containing mySQL calls):
function eventInfo(eventname,eventid,eventstatus) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("eventInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","event_info.php?eventName=" + eventname + "&eid=" + eventid +
"&rsvp_status=" + eventstatus,true);
xmlhttp.send();
}
So, the issue is that I need to store individual event names, ids and statuses and the code as it stands now. I can output them to a page individually, but cannot send them to the PHP file individually. How do I do this (presuming it is possible)?
Use jQuery for your ajax call to your php script.
$.post('/somefile.php', myJSobjectOrArr, function(data) {
// return something from your script to say it succeeded or not...
console.log(data);
}
In your php script just check your $_POST variable and serialize() or json_encode() it and pop it into your database.
To get your data back just unserialize() or json_decode() it.
You can join eventnames with comma(,) ,and when reading those data to save into database you can delimit comma(,), means remove commas from that and store each event name to database..
This is what i understand according to your problem..