I send a post to the server to create a new table entry in my database. Once the table entry is created I have the server respond with the id of the table entry. In the chrome developer tools I can see the response as just a singular number (i.e. if its the fifth entry in the table the server response is just 5). How do I store this information using javascript/YUI to be used later? Do I have to do something with the Y.io on: success function?
EDIT:
Y.io('/sessionsimulator/sessioncreate/', {
method: 'POST',
data: jdtoldstring,
headers: {
'Content-Type': 'application/json'
},
on: {
success: buildtable()
}
});
this is the code that posts the date/time and creates a session id. I can view the sqlite table afterwards and see that the session is created exactly how I wanted. the success function buildtable is the code that is called to generate the simulated data. within buildtable() i have a global variable that I am trying to set called sess_is
sess_id = Y.JSON.parse.responseText;
that statement lies within buildtable(), but when the table is created, the column that is filled with sess_id the variable is "undefined."
I can see in the developer tools the response to the url call /createsession is a number, I am just trying to pick that number and store it in sess_id variable.
If the response is just a number, you can access it from response.responseText in your IO success callback. It's a string, so you need to parse it as a number:
Y.io(url, {
//...
on: {
success: function (requestId, response) {
var id = parseInt(response.responseText, 10);
// do something with the id
}
}
});
It's usually a good idea to send JSON from the server and parse it in JavaScript when you want to send more information than just a number. You can read more about this in the IO User Guide, starting from the Response Object section.
Related
I'm using the jquery tabledit plug-in to update a database. Works perfectly like in the official examples.
I can succesfuly include a static dropdown with a fixed number of options (defined in custom_table_edit.js).
I'd like to be able to dynamically get those options from a database instead, but I don't know how to customize the code in custom_table_edit.js.
I can code this in php with a loop querying the database and generating a html <select> field. But I don't have knowledge of javascript or if it's even possible in this framework.
This is the custom_table_edit.js file. A dropdown is defined with three colour options. I want this dropdown to be dynamically produced.
// custom_table_edit.js
$('#example2').Tabledit({
url: 'example.php',
eventType: 'dblclick',
editButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}
});
I really haven't tried anything because i'd like to know if it's possible to do in this framework.
Welcome to SO, nucelar.
What you are describing is a HTTP request from the client to server through JavaScript. This is commonly referred as AJAX or Asynchronous JavaScript And XML. This API enables you to manually send requests to the server and there are multiple implementations.
Because you are using jQuery I will recommend you to use the $.ajax function which is included in the jQuery library.
Down here I've made a very basic example of how to send a HTTP request to a server with the GET method to retrieve some data.
$.ajax({
url: 'https://yourdomain.com', // Where to send the request to. Can also be a file.
method: 'GET', // What method of request it uses.
success: function(data) { // When a response is succesfully received.
// Do something with the received data.
console.log(data); // Show what the data looks like in the console.
},
error: function(jqXHR, textStatus, errorThrown) { // When an error occurs while making a request.
console.log(jqXHR, textStatus, errorThrown); // Show the error in the console.
}
});
In your case the url property value might be the URL of a PHP file in which you query the database and return the result, as you mentioned you are able to do.
The response of the AJAX function (which is stored in the data variable in the success method) can be text, as in a string, or even JSON if you want to send structured data.
Beware of the Asynchronous part. This means that the AJAX code does not stop the execution of the rest of your JavaScript code, but simply continues and comes back whenever the HTTP request has been completed.
I hope that this is enough to get you started. Good luck and don't hesitate to ask questions.
I'm trying to send the data I gathered from my web app to a google spreadsheet.
I'm using the script from Martin Hawksey:
https://gist.github.com/mhawksey/1276293
I've set it up and did everything as shown in the manual. And I am getting data back, but it's showing up as undefined values:
This is the code I use to send the JSON string to my spreadsheet:
function sendData(){
var url = 'https://script.google.com/macros/s/AKfycby3SUJvfEjdHWVoEON0L5hN4uXod8M4Jv1LAIWH3Ny16MIUz9o/exec';
var data = JSON.stringify(member);
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: function (response) {
console.log("succes! I sent this: " + data);
console.log("got this back: " + JSON.stringify(response));
},
});
}
This gives me a success message, it even tells me which row it was placed on.
This is the JSON string I'm sending:
{"Voornaam":"Name","Achternaam":"Name","Mail":"x#x.com","Verjaardag":"0/0/0000","Foto":"https://graph.facebook.com/xxxxx/picture?width=1020","School":"School X","Richting":"Course X"}
I even checked this JSON with a JSON parser online and it didn't return any errors.
For starters, I'm not entirely sure how to check which string I'm receiving at my spreadsheet. If it's still correct when it arrives. I tried logging it, but can't seem to get any response from the google logger.
If anyone could point out what I'm doing wrong, you would be greatly appreciated!
The Web script expects a JSON object. However, Ajax call is made with a string using the stringify function
var data = JSON.stringify(member);
Modifying the script to make the GET call with JSON object as is resolved the issue, like so
var data = member;
In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!
I want to send a JSON object to a PHP file while my script opens that PHP file in a new popup window. Is it possible to send it via POST method (by jQuery or without it)?
If not, how do I convert JSON to a URL encoded string? Is there any JavaScript function?
You may create a form (on the fly) with an input (where you fill the value with the JSON) and a target-attribute regarding to name of the popup (second parameter of window.open()).
Then send this form.
Open the popup: var popup = window.open(...)
Assign the json object to a new variable in the new window: popup.json = ...
Use the variable json in your popup (it will be accessible as window.json or just json from JavaScript code running in the popup).
There's a JSON encoder/decoder that looks like it would do the job. You could call this to encode your object before adding it to your querystring.
Example
alert(JSON.encode([0,1,false,true,null,[2,3],{"some":"value"}]));
// [0,1,false,true,null,[2,3],{"some":"value"}]
alert(JSON.decode('[0,1,false,true,null,[2,3],{"some":"value"}]'))
// 0,1,false,true,,2,3,[object Object]
You can use the Ajax API to do so... In the Ajax API, you can specify the data property and set it a JSON, and it will send the data to the server based on the type you have set, that is, GET or POST.
For example:
$.ajax(
{
url: url, // Your post URL
type:"POST", // or GET
data: {a:1} // In your case, your JSON object
success:function(response){}, // Function that will be called when your posted URL responds
crossDomain: true, // If it's a cross-domain request
dataType: "json" // Response datatype: JSON, text, HTML, XML, etc.
}
);
One thing to note is that if your response needs to be processed, you need to get around the same origin policy set by the browser. Please read about the same. You could use something called JSONP. It's part of the Ajax API.
I hope this is what you want.
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).