can't get d3.xml to POST correctly - ajax

I tried to POST/GET some Vars to a php-file via AJAX/d3.xml, but a print_r($_POST/$_GET) inside the php, tells me they're empty. Even the example on the doc won't work for me.
d3.xml("xxx.php")
.header("Content-Type", "application/x-www-form-url-encoded")
/*
.get("a=2&b=3", function(error, data) {
console.log(error);
})
*/
.post("a=2&b=3", function(error, data) {
console.log(error);
})
.on("load", createTable(data));
The console tells me that there is a POST request but under POST (on Firefox, not on Chrome) it lists the Vars in one line "a=2&b=3", instead of
a = 2
b = 3
as it usually does. What is it that I'm not getting?

First, apologies for the confusion in the comments. I was looking at the source for an old version of d3. In the newer code, it is indeed true that if you do not provide a callback to d3.xml it returns an xhr request that you can configure directly. (If you do provide a callback, it executes a GET right away as before).
You're going to hate this, so get ready. :) Your issue is because you have an extra dash in your Content-Type header. You have:
application/x-www-form-url-encoded
but it should be
application/x-www-form-urlencoded
Looking at a modified version of your jsfiddle in Firefox, I see the arguments show up in the list view as expected: http://jsfiddle.net/WaT6r/3/

Related

Cypress: Switching from cy.route() to cy.intercept()

It seems that most people I read about experence zero trouble with this. I, on the other hand, have a test suite which someone else wrote, in which I'm trying to replace route() with intercept(). The API intercepts are done to handle button clicks etc., and about 99.9% percent of them fails if I just replace it. So, there's obviously some syntax in/use of intercept() I've not found a description for.
Example:
This works:
cy.route('POST', getApiPrefix() + '/prosjektfinansiering/'+ pfId +'/eiendom', result);
This does not work. The button click is not executed:
cy.intercept('POST', getApiPrefix() + '/prosjektfinansiering/'+ pfId +'/eiendom', result);
I've tried adding '**' in front of "/prosjekt...", and I've tried removing 'POST', with no luck.
Any ideas? I'll gladly post more info if necessary.
UPDATE:
Futher attempts:
Getting some hints here and there, it seems that this is a more correct way of using intercept():
return cy.intercept('POST', getApiPrefix() + '/prosjektfinansiering/'+ pfId +'/eiendom', {
body: result
});
This doesn't work, either.
The variables result in these examples is an object describing what is sent back to the frontend of the POST-request in the route matches the api path.
For troubleshooting, I can see that when using intercept(), there is ONE route that is not working when using intercept (the bottom one in the picture). However, I cannot for the life of me see why, and how the route match can be written differently?
Most likely, you're mixing the old use of cy.route() and cy.server(). In my experience, those two won't work well together. It's easier when you're starting fresh with just cy.intercept().
Your update is correct too; You have to encapsulate the return value you want mocked in {body: value}.
from what I am seeing in your circled screenshot, the API is not called after you try to intercept it. (the count under # column is -)
You need to track when the API is to be called and ensure you intercept before the call is made. Cypres can help you with this. You can go through the run steps in the cypress window.
You could also share this if you don't mind.
If you are 100% certain the button makes the call. Steps should be:
cy.intercept()
cy.get('button').click()
In the cypress window, right after the click, you should see the API being called.

Google javascript API returns 404's

I have the same code (more or less) working fine in Java, but when I write it in javascript, I end up with 404's. I can't figure out what I'm doing wrong and it's driving me crazy!
gapi.client.load('translate', 'v2', function () {
gapi.client.language.languages.list().execute(function (response) {
response.data.forEach(function(language){
console.log(JSON.stringify(language));
});
});
"language":
{"code":404,"message":"Not Found","data":[{"domain":"global","reason":"notFound","message":"Not Found"}],"error":{"code":404,"message":"Not Found","data":[{"domain":"global","reason":"notFound","message":"Not Found"}]}}
I can see in the console the following POST data to https://content.googleapis.com/rpc?key=MY_API_KEY:
[{"jsonrpc":"2.0","id":"gapiRpc","method":"language.languages.list","apiVersion":"v1"}]
Should that say v1?
By contrast, the REST URL is https://www.googleapis.com/language/translate/v2/languages?key=MY_API_KEY (and it's a GET) and it works fine.
You are right that this was a bug in gapi.client.load. This bug has been fixed and you should no longer run into 404s.

XMLHttpRequest.send(Int8Array) POST fails in Firefox only

I'm trying to post data (a chunk of a file) using a XmlHttpRequest object with an Int8Array as the data but it fails in FF18, but works perfect in IE 10 & Chrome.
Here's my JS:
//dataObj is an Int8Array with approx. 33,000 items
var oReq = new XMLHttpRequest();
oReq.open("POST", "Ajax/PostChunk");
oReq.onload = function (oEvent) {
//
};
oReq.send(dataObj);
I use Firebug in Firefox to debug my JS and when I watch the activity under the Net tab, nothing ever shows up for this XHR call. As if it was never called.
Also, prior to this call, I call jQuerys .ajax() method for "Ajax/PostChunkSize" and that works fine in all browsers, although that doesn't use an Int8Array for its data. I can't use .ajax() for this since .ajax() doesn't support Int8Array objects, as far as I know.
Does anyone know why Firefox doesn't even attempt to send this? Any questions, please ask.
Thanks in advance.
The ability to send a typed array (as opposed to an arraybuffer) is a recent addition to the in-flux XMLHttpRequest2 spec. It'll be supported in Firefox 20 in April or so (see https://bugzilla.mozilla.org/show_bug.cgi?id=819741 ) but in the meantime if your Int8Array covers its entire buffer, doing send(dataObj.buffer) should work...
Note that per the old spec the code above should have sent a string that looks something like "[object Int8Array]" instead of throwing; you may want to check to make sure that other browsers really are sending the array data and not that string.

MooTools AJAX Request on unload

i'm trying to lock a row in a db-table when a user is editing the entry.
So there's a field in the table lockthat I set 1 on page load with php.
Then I was trying to unlock the entry (set it 0) when the page is unloaded.
This is my approach. It works fine in IE but not in Firefox, Chrome etc....
The window.onbeforeunload works in all browsers, I tested that.
They just don't do the Request
BUT
if I simple put an alert after req.send(); it works in some browsers but not safari or chrome. So I tried putting something else after it just so that's there's other stuff to do after the request but it doesn't work.
function test() {
var req = new Request({
url: 'inc/ajax/unlock_table.php?unlock_table=regswimmer&unlock_id=',
});
req.send();
alert('bla'); // ONLY WORKS WITH THIS !?!?!?
}
window.onbeforeunload = test;
i've already tried different ways to do the request but nothing seems to work. And the request itself works, just not in this constellation.
ANY help would be appreciated!
Thanks
the request is asynchronous by default. this means it will fork it and not care of the complete, which may or may not come (have time to finish). by placing the alert there you ensure that there is sufficient time for the request to complete.
basically, you may be better off trying one of these things:
add async: false to the request object options. this will ensure the request's completion before moving away.
use an image instead like a tracking pixel.
move over to method: "get" which is a bit faster as it does not contain extra headers and cookie info, may complete better (revert to this if async is delayed too much)
you can do the image like so (will also be $_GET)
new Element("img", {
src: "inc/ajax/unlock_table.php?unlock_table=regswimmer&unlock_id=" + someid + "&seed=" + $random(0, 100000),
styles: {
display: "none"
}
}).inject(document.body);
finally, use window.addEvent("beforeunload", test); or you may mess up mootools' internal garbage collection

IE7 not digesting JSON: "parse error"

While trying to GET a JSON, my callback function is NOT firing.
$.ajax({
type:"GET",
dataType:'json',
url: myLocalURL,
data: myData,
success: function(returned_data) {
alert('success');
}
});
The strangest part of this is that:
my JSON(s) validates on JSONlint
this ONLY fails on IE7...it works in Safari, Chrome, and all versions of Firefox, (and even in IE8). If I use 'error', then it reports "parseError"...even though it validates!
Is there anything that I'm missing? Does IE7 not process certain characters, data structures (my data doesn't have anything non-alphanumeric, but it DOES have nested JSONs)? I have used tons of other AJAX calls that all work (even in IE7), but with the exception of THIS call.
An example data return here is: (this is a structurally-complete example, meaning it is only missing a few second-tier fields, but follows this exact hierarchy)
{"question":{
"question_id":"19",
"question_text":"testing",
"other_crap":"none"
},
"timestamp":{
"response":"answer",
"response_text":"the text here"
}
}
I am completely at a loss. Hopefully someone has some insight into what's going on...thank you!
EDIT
Here's a copy of the SIMPLEST case of dummy data that I'm using...it still doesn't work in IE7.
{
"question":{
"question_id":"20",
"question_text":"testing :",
"adverse_party":"none",
"juris":"California",
"recipients":"Carl Chan"
}
}
I am starting to doubt that it is a JSON issue...but I have NO idea what else it could be. Here are some other resources that I've found that could be the cause, but they don't seem to work either:
http://firelitdesign.blogspot.com/2009/07/jquerys-getjson.html (Django uses Unicode by default, so I don't think this is causing it)
Anybody have any other ideas?
The example data you present looks all right but my strong suspicion still is that there is an unclosed comma somewhere like this:
"timestamp":{
"response":"answer",
"response_text":"the text here"
}, <------------
}
IE is the only browser that (correctly) trips over this.
If this is not it, can you show a full data sample (or confirm that the example you show is indeed a full sample)?
Did you already exclude the possibility of a caching issue?
e.g. you tested with IE7 when myLocalURL returned invalid json. IE7 still caches that response and thus it doesn't work. Try adding something like this (e.g. if php) to myLocalURL or make myLocalURL look like myLocalURL?random=123 just for testing to make sure it isn't a caching thing
header("Cache-Control: no-cache, must-revalidate");
header("Expires: 0");
Are you returning a correct content-typ header? e.g.
header("Content-Type: application/json");
I've just encountered exactly the same issue. It turns out that IE7 fails to parse JSON responses that have leading \r\n line feeds in the response body. Your fix of removing {% load customfilter %} works because you removed the new line that was being included after this tag.
An alternative fix would be to just remove the new line to get
{% load customfilter %}{ "question":{ "question_id":"{{question.id}}",
"question_text":"{{question.question_text|customfilterhere}}"
}
}

Resources