javascript syntax $.tzPOST - javascript

I have the following segment js code, but I can't understand $.tzPOST.
$.tzPOST('login',$(this).serialize(),function(r){
working = false;
if(r.error){
chat.displayError(r.error);
}
else chat.login(r.name,r.gravatar);
});
What does $.tzPOST mean?
Thanks you so much !

I think you're referring to this tutorial about a live webchat.
Rboe guessed right that tzPOST is a custom function that was added to $ (jQuery) object. The tutorial provides the source for both tzPOST and tzGET functions on the same page (use CTRL+F there to find it quickly), here they are:
// Custom GET & POST wrappers:
$.tzPOST = function(action,data,callback){
$.post('php/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?action='+action,data,callback,'json');
}
It just makes POST and GET requests code shorter and therefore easier to read and maintain. For example, if you change the name or location of your ajax.php file you'd just need to change the path in these 2 functions instead of changing it in every AJAX request. With the standard way your function would look like this:
$.post('php/ajax.php?action=login', $(this).serialize(), function(r) {
working = false;
if(r.error){
chat.displayError(r.error);
}else {
chat.login(r.name,r.gravatar);
}
}, 'json');
So the difference is small.

Related

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Load .txt file using JQuery or Ajax

How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php

YUI 3 - Set global request headers for Ajax

I've mostly worked with jQuery before and I'm new to YUI. I wish to set a custom header for each Ajax request using either IO or DataSource in YUI 3. I want the header to be inserted automatically for each request. In jQuery I could accomplish this with $.ajaxPrefilter like so:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var value = 'blah';
if (value) {
jqXHR.setRequestHeader("My-Custom-Header", value);
}
});
I found these pages in the online documentation for YUI 3 but I just don't "get it". How can I accomplish this?
http://developer.yahoo.com/yui/3/examples/io/io-get.html
http://developer.yahoo.com/yui/3/api/io.html
Check out the "header" method in the io module: API docs
I haven't tested it, but you should be able to do something like this:
YUI().use('io', function(Y) {
Y.io.header('X-My-Header', 'My Custom Value');
Y.io(/*...*/); // Should have the X-My-Header HTTP header
});
Note that this will only apply to the current YUI instance. So if you have another YUI().use(/.../) statement, you'll need to set the header again.
If you need it to provide headers across instances, you should define your own module that wraps the Y.io functionality. Check out this gist to get a sense of what that entails.
I honestly don't think it is good idea to do it "JQuery style". Either way you need to provide configuration object, so few more characters doesn't make much difference.
But the worst part is that when someone else will see your code he will not have idea where the additional headers come from and he will probably waste hours of his life.
If you still want to have default headers somewhere, do it Javascript way like so:
Y.myDefaultIOCfg={"My-Custom-Header":value}
...
var cfg=Y.merge(Y.myDefaultIOCfg, {
method: 'GET',
data: 'foo=bar'
})
request = Y.io(uri, cfg)
This way you explicitly say that you are using some object as a pattern for the config object and additional header definition can be found there.
I don't know YUI syntax very well, but try this:
YUI().use("io-base", function(Y) {
var cfg, request;
cfg = {
methos: 'GET',
data: 'foo=bar',
headers: {
'My-Custom-Header': value
}
}
request = Y.io(uri, cfg);
});

What's a good pattern to take JSON and assign to various attributes/innerHTML?

For example here, lets pretend we have a program that sends an ajax request to a PHP file, and needs to apply it's values to do things such as:
Update form inputs
Set checkboxes
Update the innerHTML of elements
Lets say the below code here does all that, and that's lovely, but it isn't an elegant pattern and maintainability of it is awful if I'm working with more than 10-15 values.
The JSON would just simply: {"ID": "1", "gender":"M", .....etc..... }
I've made a simple object to save me from having to write the selector a bunch of times when dealing with the form.
var dataVars = {
phone : $("#Phone1_input"),
gender : $("#Gender_input"),
birthdate : $("#BirthDate_input"),
chk01 : $("#chk01"),
chk02 : $("#chk02"),
chk03 : $("#chk03")
/*Imagine 30 more lines of this*/
}
After a successful ajax call to get the data, I assign the form objects one-by-one and have to considder what type of form element I'm updating with hard-coded settings.
$.ajax({
url: "./whatever", dataType: "json", type: "post",
success: function (data) {
dataVars.phone.text(data.ID); //text/innerHTML
dataVars.gender.val(data.CreationDate); //Value attribute
dataVars.birthdate.val(data.UserName);
dataVars.chk01.attr('checked',data.chk01); //Checkbox attribute
dataVars.chk02.attr('checked',data.chk02);
dataVars.chk03.attr('checked',data.chk03);
/*Imagine 30 more lines of this*/
}
});
I have the general feeling this is awful, and while I could probably come up with a function that does a lot of checking, I can't help but come up with a lot of different ways to start off a more elegant solution, so really I don't even know what path to take with optimizing this. Should I make that dataVars into an object of functions? Should I make one function to check all the types? Should I change my JSON to be more descriptive? Any thoughts on a best design for this?
You can look into some templating libs for jquery.
if you want to roll your own, what i would do is this:
return slightly more complex json like this:
[
{'type':'checkbox', 'id':'theId', 'val':'value'},
{'type':'container', 'id':'theId', 'val':'value'},
...
]
this way you know what type of element this is when you assign the values and can call the right method.
now your success function might be:
function(data){
$.each(data){
var $it = $("#"+this.id);
if(this.type === "checkbox"){
if(this.value) {
$it.attr("checked", "checked");
} else {
$it.removeAttr("checked");
}
} else if(type === "container"){
$it.html(this.value);
} else if(type ==- "input"){
//todo
} else if ...
}
}
this simplifies the code on client side, but the downside to this way of doing things is that now your server side code needs to know about elements on your client side.

How to obtain jquery post return values?

I want to retrieve the height and width of an image on a server by using an ajax post call to a php file which returns a double pipe delimited string 'width||height'
My javascript is correctly alerting that requested string from the php file so the info is now in my script but i cannot seem to access it outside the $.post function.
This works:
var getImagesize = function(sFilename)
{
$.post("getImagesize.php", { filename: sFilename, time: "2pm" },
function(data){
alert(data.split('||'));
});
}
But retrieving is a different matter:
// this line calls the function in a loop through images:
var aOrgdimensions = getImagesize($(this, x).attr('src')) ;
alert(aOrgdimension);
// the called function now looks like this:
var getImagesize = function(sFilename)
{
var aImagedims = new Array();
$.post("getImagesize.php", { filename: sFilename },
function(data){
aImagedims = data.split('||');
});
return "here it is" + aImagedims ;
}
Anyone able to tell me what i'm doing wrong?
You are misunderstanding the way that an AJAX call works. The first "A" in AJAX stands for asynchronous, which means that a request is made independent of the code thread you are running. That is the reason that callbacks are so big when it comes to AJAX, as you don't know when something is done until it is done. Your code, in the meantime, happily continues on.
In your code, you are trying to assign a variable, aOrgdimensions a value that you will not know until the request is done. There are two solutions to this:
Modify your logic to reconcile the concept of callbacks and perform your actions once the request is done with.
Less preferably, make your request synchronous. This means the code and page will "hang" at the point of the request and only proceed once it is over. This is done by adding async: false to the jQuery options.
Thanx for the Asynchronous explaination. I did not realize that, but at least now i know why my vars aren't available.
Edit: Figured it out. Used the callback function as suggested, and all is well. :D

Categories

Resources