I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).
Related
I have a variable within a laravel PHP page, held within Javascript. I currently print / output this as:
${data.id}
I now want to connect to PHPMyAdmin to check to see if the ID is within a table. However, I realise I can't use the ID number in PHP - as this is done on the server side and JS on the client side. A little stuck.
Unfortunately, I'm on a shared hosting package so node.js isn't a solution I can use.
Any help would be great! I think I can use AJAX, but unsure on how this would look.
here the AJAX sample.
$.ajax({
method: "POST",
url: "some.php",
data: { id: data.id}
})
.done(function( response) {
console.log(response);
//TODO:process your response here if receive response from php file.
});
All the other solutions in stackoverflow doesn't seem to work for me so i'm posting my code for assistance. I want to output the variable: #less_per_unit via jquery
Here is my tag inside _form.html.erb:
<script>
$(document).on('keyup', ".input-quantity", function(){
$.ajax({
url: "/so_check_increment",
type: "GET",
data: { quantity: $(this).val(), product_id: $(this).closest('tr').find('.input-product_code').val()}
});
$(this).closest('td').next('td').find('.increment').text('<%== j #less_per_unit%>');
});
</script>
And here is my controller:
def check_increment
#less_per_unit = "testing"
end
I know that the ajax works, i've also set up the routes. If I try binding.pry, I know that rails can find #less_per_unit, but I can't output it with javascript.
This is not working because:
Let us say this form is rendered in action 'new' of controller 'Post', then #less_per_unit needs to be initialised there to use it in the view file of that action which you are using. Where as you are using an AJAX call and during that call, you are defining an instance variable which will definitely be not accessible to the already rendered html file.
So, you need to return JSON data from your check_increment action and receive that data in AJAX call response and then use it.
I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.
I'm working on a scraper of my bank statements with CasperJS, so far I've managed to login and get to the statements page. I accomplished to get the table with the first page of the statement, but I need to get it complete.
The bank's web have the option to export to a .txt file (sort of a CSV actually), but in order to download it I have to be able to download the file that comes as an attachment in the response header of a POST request when I submit a form by clicking a button.
So I figured that I could do the POST via AJAX, get the response and output it. I tried running the code on the firebug console and it works, but for some reason it just doesn't work in CasperJS.
Btw, I have tried using --web-security=no , still doesn't work
This is how I'm trying to do it:
this.then(function() {
eurl = "http://bankurl.com";
response = this.evaluate(function() {
params = $("#lForm").serialize();
$.ajax({
type: "POST",
url: eurl,
data: params,
success: function (data) {
return data.responseText;
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
I wasn't able to test this with the code you provided, but it looks as though you just aren't returning anything back from the evaluate().
return __utils__.sendAJAX(url, 'POST', params);
You would probably also need to call CasperJS with the following:
casperjs --ignore-ssl-errors=true /path/to/script.js
Well, after struggling finding a way to solve this I finally did, I just put the ajax call inside a try catch and found that the error was that it wasn't reading the eurl variable (I declared it outside the evaluate). I put it inside and it worked. Thanks for your help
I'm trying to assign the contents of an xml file to a var, like so:
var testing = $.load('xx.xml');
$('#display').text(testing);
but it's not working. I tried the ".load" function as suggested in:
How to assign file contents into a Javascript var
and I had a look at the page they suggest form the jquery website, but I can't find something specific to assigning the contents of the .xml file to the var as a string.
I appreciate this is probably very obvious & I am arguably being lazy, but I have been trying random things for a while & cannot figure this out.
Thanks
EDIT! I was loading up the contents inside the load function, i didn't mean this, it's now edited.
Firstly, $.load isn't a defined function in the latest jQuery source, nor is it documented on the jQuery site.
Secondly, assuming you haven't modified jQuery's global AJAX settings, jQuery.fn.load and other request functions will be asynchronous, so you can't just assign the result to a variable because the function returns before the request has completed. You need to use callback handlers.
Try using $.ajax with a callback function instead:
var testing;
$.ajax('xx.xml', {
dataType: 'text',
success: function (data) {
testing = data;
$('#display').text(testing);
}
});
Since you want the data as text and the file appears to be XML, we're using dataType to tell jQuery to return the data as a string.
There is no $.load function. What you probably want is jQuery.get:
var xml;
$.get("xx.xml", function(data) {
xml = data;
});
As the file is retreived asynchronously, you need to assign the result to the variable inside the callback, which is executed when the request returns successfully. Note however that if you try and run code that depends on xml after the .get call, xml is going to be undefined because the callback won't have run yet. For example:
var xml;
$.get("xx.xml", function(data) {
xml = data;
//Do stuff with data here
});
console.log(xml); //Most likely undefined because asynchronous call has not completed
If you are trying to insert the results into a DOM element, then you can use the .load method:
$("#someElem").load("xx.xml");
if you are trying to get an xml from your server using ajax, you may try something like this -
function getXml()
{
var contents;
$.ajax({ url :'/website/method', type: 'GET', dataType :'xml', async : false,
cache : true, success : function(myXml){
contents = myXml;
}
});
return contents;
}