Cant seem to set global vars correctly - javascript

I am trying to store a token into a global var. When the alert is run it says null, but if I put 2 alerts one after the other the 1st shows null but the second shows the token.
Its like the token is not being set because the 1st alert is run before the ajax request has finished.
Does anyone have any ideas on what I am doing wrong?
var csrf_token = null;
$(document).ready(function(){
get_csrf_token();
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
}
Thanks
UPDATED
Ok thanks for your help everyone but still dont see how this would work. I use get_csrf_token() like jqgrid to send the token with the request like below. So how do I pass the token to and have it working?
beforeRequest: function (){
get_csrf_token()
//alert(csrf_token);
$("#customer_grid").setPostDataItem('<?php echo $csrf_token_name; ?>', csrf_token);
}

The success callback function runs when the HTTP response arrives.
In your test, the response is arriving between the time that the first alert is displayed and the time you click the button to let the script continue.
Do whatever you need to do with the data in the callback, not as the statement after the one where you initiate the Ajax request.
Example as requested by comment:
$(document).ready(function(){
get_csrf_token();
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
}
});
}

The A in AJAX stands for 'asynchronous'. While you are busy clicking on the first alert, the AJAX request is going through and the value is filled. You will need to place all code that needs the variable csrf_token into your callback function. Alternatively, you can look into using jQuery 1.5 or above (if you aren't already). It has so-called Deferred Objects
This API allows you to work with return values that may not be immediately present (such as the return result from an asynchronous Ajax request).
You can also set the async value on your post request tofalse, like this:
$.ajax({
type: "GET",
async: false,
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
This will make the browser wait for the response before proceeding with the rest of your code. I wouldn't necessarily recommend it, but it should work.

The AJAX request is async. That means the script doesn't wait for it to finish. When the first alert fires the token is not set. But until you hit OK it has time to load and the token will be set.
Here's the order of the operations:
call get_csrf_token
make token request
show alert 1
finish request and set csrf_token
client hits OK on the first alert
show alert 2 (the token variable was set at 4.)

Related

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

Header PHP not working after AJAX call from Javascript

so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}

Ajax jquery making web api call

I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.

Error with Jquery Ajax Success Event and Receiving Response Message

I am calling jQuery Ajax function, everything works fine.. except, it is not receving any response and appending it in.
When form is submitted.. beforeSend event is called and loading image successfully runs, and also there is an alert box with message 'Deleted', but the request and response from page is not appended.... in network tab of chrome, i can see message of selected post deleted... but its not appending in page.
$(document).ready(function() {
$("#post").submit(function() {
var post = $('#post').val();
var token = $('#token').val();
var str = 'token='+ token + '&post='+ post;
$.ajax({
type: "POST",
cache: false,
url: "http://localhost/delete.php",
data: str,
beforeSend: function(){
$("#post").html('<img src="http://localhost/loader.gif" align="absmiddle"> Deleting...');
},
success: function(msg) {
alert('Deleted');
$("#post").ajaxComplete(function(event, request, settings) {
$("#post").html(msg);
});
}
});
return false;
});
});
You're attaching a new event listener to #post after the AJAX query succeeds. Basically what you're saying is, "after this query succeeds, wait for another query to succeed and then change the HTML." Since the query has already succeeded, you need to remove ajaxComplete and simply use:
success: function() {
alert('Deleted');
$("#post").html(msg);
}

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources