Fetch/XHR data generated after execution of function using Python and Selenium - javascript

I have a website opened using Python and chromedriver. This website loads variables and you can make use of its javacript files to execute its functions (well this website and all others as it is usual behaviour)
If I do the following
driver=webdriver.Chrome()
driver.get(www.myurl.com)
script="const xhrfunction= new websitevariable.some_class; var a=entry data; xhrfunction.load(a); return xhrfunction"
driver.execute_script(script)
I see in the devtools in the network tab that a new fetch/xhr line has been generated and that the response is a long string with data. However, I can't get this string of data returned from driver.execute_script(script)
When it is possible to perform the fetch directly, I do the following and it generates the exact same line in the network tab and also returns me the data from the response
script='var url= myurlhere; resp= await fetch(url); return {'status':resp.status, 'data': await resp.text()}
driver.execute_script(script)
But that is not an option so I need to get this string of data generated by the execution of my function in the first code snippet.
How would I accomplish this using execute_script?

Related

Can't able to get the data using ajax in the MVC

I am using AJAX call in JS and calling a controller and action method with the url
I ran the code in my local it is working fine but when it was deployed in production the AJAX call didn't get the data and it is throwing a message in console
Could not load content for https://az416426.vo.msecnd.net/scripts/JavaScript/JavaScriptSDK/ajax/ajax.ts (HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE)
The data on local is limited but it has more data on production
I tried it by calling through AJAX and from the action method I am returning the data in the JSON format and the data i recieved is parsed and then it is sent to a hidden field it was running fine on my local all the data is there but when it was deployed on production after the page load the ajax will be called but I can't able to see the data and it shows the error which I mentioned above.
I will give you two recommendations that work better for me when dealing with passing JSON data from a controller.
First try this on your get data method:
[HttpGet]
public ContentResult Getsubscriptiondata()
{
var subdata = db.ExistingSubscriptionList.Where(substatus => substatus.OSCP_SubStatusId == "1").ToList();
return Content(JsonConvert.SerializeObject(subdata));
}
Second in your javascript change the line
document.getElementById('hdnExistingSubs').value = JSON.stringify(data)
to
document.getElementById('hdnExistingSubs').value = JSON.parse(data)
This gives me more consistent results when receiving data from the controller, hope this helps.
Clarification: I prefer this methods because passing a Json result sometimes haves quirks in the way the data is rendered on the javascript in the browser.

Accessing JSON data through API with js

WHY! Why is this not working. I am using the weatherbit api, and trying to simply get the uv index. Mind you, in a browser the proper link displays all the information but I can not get it to work through js, putting it through to a div.
I replaced the actual request data with (nameOfData) for privacy, I assure you that there is no problem with the parameters specific.
$getJSON('https://api.weatherbit.io/v2.0/current?lat=(Lat)&lon=(Lon)&key=(Key)', function(data) {
// JSON result in `data` variable
$(".UV").html(data.data[1].uv);
});
Please help.
It is failing because you need an API key. Using the URL in the address bar of a browser does not have that restriction.
Sometimes a workaround in this case is to use a proxy on a server. Your code queries the server, and the server mimics a browser. It depends on the web service how you will fare.
I got it working with async, somehow.
async function getData(){
let response = await fetch(weatherbitApi);
let data = await response.json()
return data;
}
getData().then (data =>
console.log(data.data[0]));

Form submitted to Web Api Get(string id) is repeated until ::ERR_CONNECTION_RESET

I have a Web Api site and I am trying to call a controller and have it return a zip file from the server. I submit a form to my Web Api site using javascript:
document.getElementById("downloadSettings").submit();
The action on the controller is defined as:
public HttpResponseMessage Get(string id)
The form being submitted has an input that has the expected value (id). I submit the form, the controller receives the call, performs the action (fetches the requested file as byte[]), and attempts to return the file like this:
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(fileContents))
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(ms);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "fileName.zip";
return response;
}
Simply running the code ends in me receiving an error - ERR_CONNECTION_RESET.
If I debug the Get action, what I see is - the moment the Get function finishes, a new thread arrives at the beginning of the function! There is no new call being made from the browser (the Network tab shows no new calls), and yet, the function is repeated several times over until suddenly it doesn't and on the client (browser) I get ERR_CONNECTION_RESET.
What is going on? How do I fix it? Am I doing something wrong in the way I am attempting to return the file?
Apparently, the problem was the using([...]).
Once I removed that from the MemoryStream, everything went swimmingly!
I still do wonder though... what was up with the repeat calls?

Working with JSON via GET requests in Javascript

I've built a php API that provides data in json output, I need to get the values via a get request to then plot as a graph on the page.
The front end web component in hosted on the same server as in the api in this basic structure:
index.php
graph.php
/api/
/api/src
/api/src/api.php
My current code in graph.php is as follows:
<script>
var myJson;
$.getJson('api/src/api.php/poll/results/current/13/', function(jd){
myJson = jd.AnswerCount.1;
});
document.getElementById('jsonhere').innerHTML = myJson; //just to test
</script>
The endpoint outputs data like the following:
{"AnswerCount":{"1":5,"3":1,"2":2,"4":1,"5":5,"6":3,"7":2}}
Which I need loaded into a key-value pair array,
1:5
3:1
2:2
4:1
...
to then be put into the graphing library.
How do I fix my code/write new code to do this? I'm pretty stuck here.
EDIT:
On a hunch I logged all the get requests via wireshark, and no request is ever sent to the url in question. Even with an empty function { } ? http://grab.kfouwels.com/pmgW
You can't use a number as an identifier, to access the 1 property you have to say [1] not .1
You have to use the variable containing your data, not x which hasn't been mentioned until you try to assign it somewhere
The A in Ajax stands for Asynchronous. You have to work with your data inside your callback since the function you pass to getJson won't be called until the HTTP response arrived but the line starting document.get will run as soon as the HTTP request has been sent.

JMeter modifying output to file from XML Stream

I'm attempting to write a JMeter script which after receiving and XML response from a server, extracts a string from it on the fly (drops the first part of the response) and writes it to a file.
Currently I use a Save Response Data to write to ChannelData_UAT_1 (filename). All good, it writes happily.
Then I add a BSF PreProcessor BEFORE it, and use javascript to try and extract the string. It's a bunch of XML tags, I want everything from "<Markets>" onwards.
I use:
function extract_markets(str)
{
marketIndex = str.indexOf("<Markets");
__log(marketIndex);
length = str.length;
marketString = str.substring(markeIndex, length-1);
return str;
}
vars.put('ChannelData_UAT_1', extract_markets(vars.get('ChannelData_UAT_1')));
As far as I can tell, ChannelData_UAT_1 is the variable the data is in. However this is only mentioned in the Save Response Data. But I can't do it afterwards otherwise it'll have already written to the file.
The current performance is for it to receive the response and write to the file. No filtering is done - as if my javascript didn't exist.
Anything small or obvious that I've missed? Suggestions?
I believe the issue stems from the fact that ChannelData_UAT_1 is not a variable and how Save Response Data works.
ChannelData_UAT_1 is the file name, not the content of the file.
You need to modify the contents of the "Response". You can replace the value of the page response with the value of your function.
I think the code would look something like this:
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.samplers.SampleResult;
prev.setResponseData(extract_markets(vars.get('ChannelData_UAT_1')));
Source:
http://www.javadocexamples.com/java_examples/org/apache/jmeter/samplers/SampleResult/

Categories

Resources