I need to set/get the cookies stored at first.example while browsing second.example, I have full access of first.example but I only have JavaScript access (can manipulate the DOM as I want) on second.example.
My first approach was to create an iframe on second.example (with JS) that loaded a page like first.example/doAjax?setCookie=xxx and that did an AJAX call to say first.example/setCookie?cookieData=xxx which would set the cookie on first.example with the data we passed around.
That pretty much worked fine for setting the cookie on first.example from second.example - for getting a cookie I basically followed the same procedure, created the iframe that loaded first.example/doAjax?getCookie and that would do an AJAX call to say first.example/getCookie which would read the cookie info on first.example and return it as a JSON object.
The problem is that I'm unable to bring that JSON cookie object back to second.example so I can read it, well maybe I could just bring it when the AJAX call is complete using "window.top" but there's timing issues because its not relative to when the iframe has been loaded. I hope I am clear and was wondering if there's an easier solution rather than this crazy iframe->ajax crap, also seems like this won't even work for getting cookies in SAFARI.
You could inject a script element into HEAD of the document with a callback that passes the cookie you need to whatever function needs it.
Something like:
<script type="text/javascript">
var newfile=document.createElement('script');
newfile.setAttribute("type","text/javascript");
newfile.setAttribute("src", 'http://first.com/doAjax?getCookie&callback=passCookie');
document.getElementsByTagName("head")[0].appendChild(newfile);
</script>
And the page first.com/doAjax?getCookie could do this:
passCookie({'name':'mycookie', 'value':'myvalue'});
Put this PHP-File to first.com:
//readcookie.php
echo $_COOKIE['cookiename'];
On second.com you can use this javascript to get the value:
function readCookieCallback()
{
if ((this.readyState == 4) && (this.status == 200))
{
alert("the value of the cookie is: "+this.responseText);
}
else if ((this.readyState == 4) && (this.status != 200))
{
//error...
}
}
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.onreadystatechange = readCookieCallback;
refreshObject.open("GET", "http://www.first.com/readcookie.php");
refreshObject.send();
}
Regards,
Robert
For SETTING cookies you can change my script as follows:
The new PHP-Script:
//writecookie.php
setcookie($_GET['c'], $_GET['v']);
And the JavaScript:
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.open("GET", "http://www.first.com/writecookie.php?c=cookiename&v=cookievalue");
refreshObject.send();
}
That should work on all browsers.
Related
Having this API:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
How can I write using pure JS request that downloads me different data after button click event?
All I get from this code is the same quote all the time:
function getQuote (cb) {
var xmlhttp = new XMLHttpRequest();
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && this.readyState==4) {
cb(this.responseText);
}
};
xmlhttp.open("GET", quoteURL, true);
xmlhttp.send();
}
document.querySelector('button').addEventListener("click", function() {
getQuote(function(quote) {
console.log(quote);
});
})
I tried xmlhttp.abort() and stuff but it didnt want to cooperate.
Thanks in advance!
Your response is being cached by the browser. A common trick to avoid this is to perform a request to
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
Notice how the r={random_number} will make the URL different each time.
This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.
The problem is that first question loads with onload function now when I click a button to fetch the next question i.e. the 2nd question, but it fetches the first question again, after that, when I click next it fetches the 2nd question.
Now if I want to fetch the question from another subject, suppose maths section, where I have set the value of variable to 15, when I click maths it first increments the question and after that whatever button I click it still jumps to question 15.
var question = 1;
function ajaxFunction (_direction) {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status== 200) {
var ajaxDisplay = document.getElementById('ajaxDiv');
if (_direction=='') {
question=1;
} else if (_direction=='next') {
question++;
} else if (_direction>=1 && _direction <=90) {
question = _direction;
}
}
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
ajaxRequest.open("GET", "ajax-example.php?q="+question, true);
ajaxRequest.send(null);
}
well, I haven't gave up and got the solution by myself and I'm posting this in answer so that if anyone else have the same issue.
I just removed the if else condition from the onreadystatechange and placed it above the function and it worked for me.
I've had a similar problem and solved it by setting the HTTP request from asyncron to syncron (see Autoroute step by step using Yours http request has a time lag).
Did you solve your problem on the same way or did you found a better one?
best regards, Reinhard
I think there's some kind of non-fatal bug in my script that's not allowing me to a/ debug the script with Firebug and b/ causes Firefox to constantly display a Connecting... (with the swirly) while I'm on the page. The script seems to run fine though.
Any ideas what could cause that?
<script type="text/javascript">
var xmlHttp;
var xmlDoc;
loadXMLFile();
function loadXMLFile()
{
xmlHttp = new window.XMLHttpRequest();
xmlHttp.open("GET", "myFile.xml", true);
xmlHttp.onreadystatechange = StateChange;
xmlHttp.send(null);
}
function StateChange()
{
if ( xmlHttp.readyState == 4 )
{
xmlDoc = xmlHttp.responseXML;
processXML();
}
}
function processXML()
{
var firstNames = xmlDoc.querySelectorAll("name");
if (firstNames == null)
{
document.write("Oh poo. Query selector returned null.");
}
else
{
for (var i = 0; i < firstNames.length; i++)
{
document.write(firstNames[i].textContent + "<br>");
}
}
}
</script>
All the code in your page is parsed, but not executed before the page is completed. This happens, since you're calling document.write() from onreadystatechange event handler function rather than parsing time.
In this case document.write() implicitly calls document.open(), which wipes all the code out of the page, and only what is left is the text written by document.write(). Also document is left open, which causes the browser being "busy". This can be avoided by using document.close(), but it won't prevent the original content to vanish.
You need to add an element to the body and then use some "real" DOM manipulation method. Something like this:
<div id="qResult"></div>
Then instead of document.write():
document.getElementById('qResult').innerHTML = WHAT_EVER_NEEDED
I have a feed from Coupons.com in the form of an iframe in my webpage and I want to run some JavaScript on this iframe. I want it to open on a page other than the default which is the first page.
If you go to http://www.coupons.com you can see the same feed I am working with.
Above the coupons is a list of pages 1-10. If you move the cursor over page 3 (for example) it reads javascript:GoToPage(3), which seems very simple, but I can't figure out how to script it and make that page 3 show up instead of page 1. Please help, thanks in advance-
they are reloading the page via ajax.
something like that (copied from another question that i answered):
HTML
JAVASCRIPT
function xmlhttp() {
var x;
try {
x = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
try {
x = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
x = new XMLHttpRequest();
} catch (e) {
x = false;
}
}
}
return x;
}
function page(idMenu) {
var http = xmlhttp();
if (!http) {
alert('XmlHttpRequest non supporté');
} else {
var url = 'pageOutput.php?pageNo=' + idMenu;
http.open('GET', url, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
document.getElementById('pageContent').innerHTML = http.responseText;
}
}
http.send();
}
}
now all you have left to do is create a PHP where you check whatever menu ID is called and echo page content according to $_GET['pageNo']. if you already got your pages on many PHP/HTML you may also just do include and echo them...
if(isset($_GET['pageNo'])){
//echo page code here according to $_GET['pageNo'] value
}else{
//echo main page
}
EDIT: You may also add URL param to refer the current page so the user can reload your page from a new window without having no params loaded...
EDIT: Iframe version will just reload the whole iframe, if you look when you change page you see the iframe blink. i strongly recommand using a div content, much easyer.
I have to submit two forms; one is on the page, while the other is coming through combo change event using jquery. I have to get both of these forms values on the same page. Please help me I have already wasted much time.
My code looks like this:
this function which i'm calling on the button click to submit both forms
function forms_submit()
{
document.form1.submit();
document.form2.submit();
}
You cannot submit two forms.. since your are in a browser, you can only end to one page.. and it depends on which form you submit.. (unless you go the ajax way)
perhaps you want to merge the forms in a single form in your HTML..
Give some more info/code to get some more specific answers..
You can use XMLHTTPRequest to send both forms, (but that requires two requests you'd be wasting instead of one)
I would recommend joining the forms together.
anyways a codesample,
btnSubmitBoth.onclick = function () {
var xmlReq,
data = getFormsData(); // needed to be in format of "something=1&sometinelse=2"
if (typeof XMLHttpRequest !== 'undefined' && (window.location.protocol !== 'file:' || !window.ActiveXObject)) {
xmlReq = new XMLHttpRequest();
} else {
try {
xmlReq = new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
xmlReq = new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
xmlReq = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
}
xmlReq.open("post", url, true);
xmlReq.send(data);
}
If your submit your reason, probably I could submit your 2 forms
-----------edited--------------
var whatever ='<span id='updated_values'><input type=hidden></span>';
use $('#div').append(whatever);
Each time you select a category trigger the whatever to append the an existing form as hidden form type, you need to catch the variables at time of form submission.
Hope this solves your issue.