Jquery - Pass re-assigned Global variable to function - javascript

So i have been working on this 'public chat' system for a while... I've succeeded with appending submitted message into the text box. But when it came to 'RECEIVING' other peoples messages, I failed.
The problem: I'm not able to use the re-assigned global variable inside a function.
I've assigned the global variable "global_msg_id" to an empty value in order to be able to re-assign it later inside ajax.
I want to pass the re-assigned variable (from ajax) to the function "message_receiver()"
var global_msg_id = "";
$(document).ready(function(){
$("#txtarea_msgsender").keydown(function(e){
if(e.keyCode == 13 && !e.shiftKey) {
e.preventDefault();
var url = "/pages/pmsg_sr.php";
$.ajax({
type: "POST",
url: url,
data: $("#msgbox_form").serialize(),
dataType: "json",
success: function(data) {
global_msg_id = data['id'];
$('#rec_sen').append('<div class="new_msg_box"><div class="new_msg_holder"><b>'+data['user']+': </b>'+data['message'].replace(/\\/g, '')+'</div></div>');
$('#txtarea_msgsender').val("");
$("#rec_sen").scrollTop($("#rec_sen")[0].scrollHeight - $("#rec_sen").height());
}
});
}
});
/* ############ Message receiver ############## */
setInterval(receive_message, 10000)
function receive_message() {
alert(global_msg_id); // RETURNS empty value
}
});

Related

JSON is null but data passes to success in ajax

I'm running into a problem in ajax. the scenario is: I would like to verify if the user is available or not when typing his email. So I create a function in javascript to do this with an Ajax script within it.
here my code :
$('#username').keyup(function () {
var email = $(this).val();
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
});
});
my problem is : when I type any words it calls the function of keyup then it passes into success even if the data is null. I would like to let it pass to the success only if the data is correctly done.
thank you.
Try Following..Hope it works as you want...
$('#username').keyup(function () {
var email = $(this).val();
if(email != "") {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
// Check response data...
if(data == 'true') {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
}
});
}
});
Try some error checking before doing anything. Therefore, the success callback will be invoked (you cannot stop it conditionally), but the code inside will be prevented.
Encapsulate everything in the success event handler with the following so that it only executes if data is not null (empty string):
if(data != "") {
// action here
}
I'm not sure what you mean when you say that "the data is null", so a simple empty-string conditional as shown above may not be sufficient to check whether or not the data is null. This will simply check if the data parameter is empty.

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

Check if $.ajax has already been sent and if so then retrieve data without resending

I have this ajax request that is sent from javascript in my page
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
async: false,
success: function(data) {
alert(data);
}
});
This returns an array of items with some text and ...
Now if the user clicks on a certain button the data needs to be copied to another place on the page(div)
Is there any way I can get the data again from the file (in the network tab "chrome") without resending the request?
Put the response in global variable (dataArray) and every time check that variable has value or not. So that request will not send further time. Also, you can use that global variable (dataArray) in other methods.
var dataArray = "";
function getData(){
if(dataArray != ""){
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
//async: false,
success: function(data) {
//alert(data);
dataArray = data;
}
});
}
}

Button callback function running every page load

I have a button:
<span id="signinButton">
<span
class="g-signin"
data-callback="onSignInCallback"
data-clientid="CLIENT_ID"
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
When pressed, this runs a function... which at the moment goes off, makes an AJAX post, and prints some text back in the console (just to test, this part works):
<script type="text/javascript">
var helper = (function() {
return {
onSignInCallback: function(data) {
var dataString = 'access_token=' + data['access_token'];
$.ajax({
type: "POST",
url: "getdetails",
data: dataString,
dataType: 'html',
timeout: 0,
statusCode: {
200: function(data){
console.log(data);
},
error: function(data){
console.log("There was an error");
}
}
});
}
};
})();
function onSignInCallback(data) {
helper.onSignInCallback(data);
}
</script>
However, the issue is that every time I refresh the page without clicking the button, my function runs and the data is posted via AJAX and the text gets printed into the console.
Any idea why this is happening? I want it (obviously) so this only happens when they click the button.
I'm working with the Google Plus API, code modified from:
https://github.com/googleplus/gplus-quickstart-javascript/blob/master/index.html#L44
Per the documentation for that directive:
data-callback - A function in the global namespace, which is called when the sign-in button is rendered and also called after a sign-in flow completes. When the button is rendered the callback occurs to check whether or not the user previously authorized the app and should be automatically signed in.
By design the callback will run when the button is rendered (i.e. page loads) and also when the button is clicked.
A workaround would be to set a global boolean on the first run.
<script type="text/javascript">
var first_run = true;
var helper = (function() {
return {
onSignInCallback: function(data) {
var dataString = 'access_token=' + data['access_token'];
$.ajax({
type: "POST",
url: "getdetails",
data: dataString,
dataType: 'html',
timeout: 0,
statusCode: {
200: function(data){
console.log(data);
},
error: function(data){
console.log("There was an error");
}
}
});
}
};
})();
function onSignInCallback(data) {
if(!first_run) {
helper.onSignInCallback(data);
}
first_run = false;
}
</script>
In the Google Plus documentation:
If the user previously agreed to allow your application access through this button, or another button representing the same application, they are automatically logged in. The callback function is called automatically as soon as the sign-in button is rendered and passed a new authorization object with an access token.
I was getting this as well. On my global onSignInCallBack(authResult) function, I enclosed the call that makes the ajax request in an if statement that checks for a value in authResult['access_token']. I'm using AngularJs and moved my Ajax call into my controller. Since you are not using AngularJS, you can replace the gplusController().onSignInCallback(..) line with your AJAX call.
function onSignInCallback(authResult){
if (authResult['access_token']) {
var afToken = document.getElementById('afToken').getAttribute('data-afToken');
gplusController().onSignInCallback(authResult, afToken);
}
}

Why do I get undefined when displaying value in a global variable?

I just don't get it, obviously. I've tried setters and getters, self invoking functions, you name it. It's like the click handler is returning a value but there's no way for me to keep it?
This is my code in the first file request.js
var testId = (function (inId) {
var citeId = inId;
return citeId;
})();
function mainAjax() {
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
});
}
var promise = mainAjax();
this is the code in my second file requestMain.js,
promise.done(function (json) {
var linkBase = "http://www.sciencebase.gov/catalog/item/";
var link = "";
var itemId = "";
var urlId = "";
$.each(json.items, function(i,item) {
link = linkBase + this.id;
$('#sbItems').append('<li><b>' + this.title + ' - </b>' + this.summary + '</li>');
});
$('#sbItems a').on('click', function (e) {
e.preventDefault();
var str = $(this).attr('id');
if (str.length == 7) {
itemId = str.slice(5,6);
}
else if (str.length == 8) {
itemId = str.slice(5,7);
}
testId = json.items[itemId].id;
alert(testId);
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
This webpage displays a list of links. A link could have some more information that I want displayed on a second webpage or it could have nothing. So when a link is clicked I need to store/save/keep the id from the link so that I can use it in the url to make another ajax request, because until I get the id the ajax request for the next page will have no idea what information to ask for.
For now I'm simply doing this
alert(testId);
But what I'm trying to do is this,
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' + testId + '?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
// Then doing something with json.something
testId would be used in the url and it would change depending on the link that was clicked on the previous page. The ajax call is totally dependent on the click event and is displayed on a separate webpage with new information.
And this would be in my third file requestCitation.js which currently gives me a big undefined when doing
alert(testId);
I think this is a scope issue, but how can I store the value returned from a click??? So that I can then use it globally? It seems like the value disappears outside of the scope as if there was never a click at all even thought I'm storing it in a variable?
the html for the first page has script tags for request.js and requestMain.js and the second page has script tags for request.js and requestCitation.js, so they can both see the variable testId.
Thanks for the help!
Here's the jsfiddle
These are the links and when a link is clicked
Your testId is holding the value retuned by the function you're calling, and since the function returns its argument and you've called it without arguments, it will be undefined:
var testId = (function (inId) {
var citeId = inId;
return citeId; //returns the argument
})(); // called with no argument
I'm not entirely sure what you're trying to do but if you're trying to keep the data returned from the AJAX request as a global variable, I would have thought it was done using something similar to the below.
E.g.
var promise = '';
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
data: '';
success: function(data){
promise = data;
}
});
But as I said I'm not understanding fully so I could be very wrong with my answer.

Categories

Resources