Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.
My address bar currently looks like this:
http://localhost/social3/browse/?locationName=Cambridge
Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:
$searchResult = $_POST['locationName'];
echo $searchResult;
But because I'm in an Ajax div, I can't seem to get to the variable.
Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)
My Ajax:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
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)
{
document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
If your url contains the variable, you should use $_GET["key"] instead of $_POST
alternatively, you can use $_REQUEST["key"] to handle both cases.
Related
I'm trying to get the xml from nodes. Let's say I have an XML file:
<?xml version="1.0"?>
<story title="My title here">
<subject key="key1" caption="Intro">
Text here for subject 1. There might be an occasional <html> markup present.
<action tag="actiontag"/>
</subject>
<subject key="key2" caption="Chap1">
Text for chapter 2
<directions>
<dir go="chap5" to="Solving"/>
<dir go="chap12" to="Searching">
<extra1 subtitle="subtitle">You can expect extra text here as well.</extra>
<extra2 subtitle="subtitle2"/>
</dir>
<dir go="chap2,chap5" to="Finding"/>
</directions>
</subject>
<chapters key="chap1" caption="Chapter1">
The text for chapter1 goes here
<newtag>This one has text as well</newtag>
</chapters>
</story>
Now I'm trying to get the whole XML code including nodes and tags into an array of objects. So the result should ideally be:
subjects[0].key=key1
subjects[0].caption=Intro
subjects[0].txt=Text here for subject 1. There might be an occasional <html> markup present.<action tag="actiontag"/>
subjects[1].key=key2
subjects[1].caption=Chap1
subjects[1].txt=Text for chapter 2<directions><dir go="chap5" to="Solving"/><dir go="chap12" to="Searching"><extra1 subtitle="subtitle">You can expect extra text here as well.</extra><extra2 subtitle="subtitle2"/></dir><dir go="chap2,chap5" to="Finding"/></directions>
This 'text' can than later be processed as XML.
Now I've been able to read the XML and access the tags separately. I've been able to traverse through the file and get the text but I can't seem to loop through all the nodes/text/tags and keep it formatted as is.
What I have is:
var xmlDoc;
function loadxml() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "assets/myfile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xmlhttp.onloadend = init(xmlDoc);
}
function init(xmlDoc) {
var subjects = [];
var x, i;
x = xmlDoc.getElementsByTagName('subject');
for (i = 0; i < x.length; i++) {
subjects.push({ key: x[i].getAttribute('key'), caption: x[i].getAttribute('caption'), txt: x[i].childNodes[0].nodeValue });
}
//just to check if there's something recorded..
document.getElementById("result").innerHTML = subjects[1].txt;
}
The array of objects is no problem, that works. But how do I change x[i].childNodes[0].nodeValue to hold all the childnodes of [subject] and keep accompanying tags and formatting?
Thanks for your time.
function loadxml() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "assets/myfile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
responseText = xmlhttp.responseText;
textNodes = responseText.split(/<subject.*>/);
textNodes.shift(); //remove first chunk of text
for (var i = 0; i < textNodes.length; i++) {
textNodes[i] = textNodes[i].replace(/\r?\n|\r/g, ''); //remove line breaks;
textNodes[i] = textNodes[i].replace(/^\s*/, ''); // Replace "> " with ">"
textNodes[i] = textNodes[i].replace(/>\s*/g, '>'); // Replace "> " with ">"
textNodes[i] = textNodes[i].replace(/\s*</g, '<'); // Replace "< " with "<"
}
xmlhttp.onloadend = init(xmlDoc, textNodes);
}
function init(xmlDoc, textNodes) {
var subjects = [];
var x, i;
x = xmlDoc.getElementsByTagName('subject');
for (i = 0; i < x.length; i++) {
subjects.push({ key: x[i].getAttribute('key'), caption: x[i].getAttribute('caption'), txt: textNodes[i] });
}
console.log(subjects);
}
I am new to javascript, am using PHP variable for created link dynamically as given below
$addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart('.#$product_id.',"add")><span class="allitem"
<font color="#A2F3AB">Added</font></span></button>';
This my php variable created by dynamically like below.
Added
Added
Added
I want to change the content of all variable“ added” as“ add” by just one click,Am using ajax function for changing that text as given below..
function clearcart(msg) {
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('cartreturn').innerHTML = xmlhttp.responseText;
document.getElementsByClassName('allitem').innerHTML = "Add";
}
}
xmlhttp.open("GET", "/addcart.php?msg=" + msg, true);
xmlhttp.send();
}
But first link text only affected.. other is not affected how I can solve this problem
document.getElementsByClassName returns a NodeList. You have to iterate over all the elements:
var allItems = getElementsByClassName('allitem');
for (var i = 0; i < allItems.length; i++) {
allItems[i].innerHTML = 'Add';
}
See this question.
You can't do document.getElementsByClassName('allitem').innerHTML.
You can do document.getElementsByClassName('allitem')[0].innerHTML = "Add"
Do you have several elements with the class "allitem"? If you don't, then maybe you should use an id, instead of a class, and then call document.getElementById('allitem').innerHTML = "Add";
Once a dropdown list option is selected, I would like to hold that selected option as a javascript variable.
To make this a little more complex, the variable should be held inside the page's main Ajax coding, so it is not lost when different Ajax content is loaded.
Here's my wonderfully basic form code:
<form name="searchLocations" method="POST">
<select name="locationName">
<?php
$sql = mysql_query("SELECT locationName FROM tbl_locations ORDER BY locationName ASC");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['locationName'] . "</option>";
}
?>
</select>
<button onclick="loadXMLDoc(indexSearchingSubmit);" id="searchingSubmit">Search</button>
</form>
and here is my main ajax code, where the form dropdown variable should be held so it can be used later:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
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)
{
document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
Using jQuery:
$('[name="locationName"]').change(function() {
YOUR_VAR = $(this).attr('value');
});
Not using jQuery-
Add onChange() to your SELECT element, also added id attribute.
Add javascript onchange handler function, which just retrieves the selected value and sets your var
<select name="locationName" onChange="setSelected()" id="locationSelect">
function setSelected(){
var myselect= document.getElementById("locationSelect");
YOUR_VAR = myselect.options[myselect.selectedIndex].value;
}
How can JSON be used to parse xmlhttp.responseText? I can't seem to get textboxes populated using the parsed data. I tried using .value and .innerHTML with the dot notation with b.first and b.second used with json_encode from the loadTextBox.php file (see below), but the textboxes won't populate.
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = xmlhttp.responseText;
var b = JSON.parse(a);
document.getElementById("textbox").innerHTML=b.first;
document.getElementById("textbox2").innerHTML=b.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query("SELECT column_one FROM table_one");
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
This is fully tested and works. Use as a starting point to accomplish what you are trying to do:
var url = "YOUR.php"
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.send(null);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && (ajax.status == 200)) {
console.log("ready")
var Data = JSON.parse(ajax.responseText);
console.log(Data);
console.log(Data.first);
} else {
console.log("not ready yet")
}
}
This assumes your JSON output is properly formatted as you stated:
{"first":"radim","second":"radi"}
I have figured out the underlying problem. Extra tags were being sent because I had unnecessary tags in my DB info file. Those tags were being sent in the responseText with {"first":"radim","second":"radi"}. So the code pertaining to ---Placeholder for correct DB login info--- was wrong. I also changed .innerHTML to .value and now it works as intended.
Main page code updated:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
Hi I have the following code
<html>
<head>
<script type="text/javascript">
var xmlhttp;
var allSearchResults = [];
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction(paramm)
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
if (txt.match(paramm)!= -1){
//store all instances in allSearchResults array Here
}
else{
document.getElementById("myDiv").innerHTML = paramm;
}
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction('CXS101289')">Change Content</button>
</body>
</html>
ajax_info.txt
CXS101289_5_R1A06_100628150914
CXS101289_5_R1A06_100628343414
CXS10rfe_5_R1A06_100628150955
CXS101349_5_R1A06_100628150432
CXS154f89_5_R1A06_100628150914
CXS101289_5_R1A06_10062456914
CXS101369_5_R1A06_100628150914
CXS15679_5_R1A06_100628150914
So I want to search this file for the "CXS101289". So after I have run this method, the "allsearchResults" array shall contain ["CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_10062456914"]
Any smart idea on how to implement this?
This should do what you're looking for
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"));
for example after
param = "x";
txt = "x_1 y_2 z_3 x_4 yx_5 z_6 x_7";
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"))
result is ["x_1", "x_4", "x_7"]
Note that if param is going to contain charaters that have a special meaning for a regular expression (for example * or + or ]) then you have to escape them by prepending a backslash.
The initial \b is needed to be sure that your search key is only accepted at the beginning of an item.
function findMatched(text, keyword) {
var arr = text.split('\n');
var result = [];
for(var i = 0, len = arr.length; i < len; i++) {
if(arr[i].match(keyword)) {
result.push(arr[i]);
}
}
return result;
}
//...and in your code
if (txt.match(paramm)!= -1){
allSearchResults = findMatched(txt, paramm);
}
It is the only way I can see it solve. But maybe you already taught of this and where asking something else.