Capture POST request to local variable in script [duplicate] - javascript

This question already has answers here:
AJAX not updating variable
(5 answers)
Closed 5 years ago.
I have the javascript code below that POSTs a request, I then want to save the response to a local variable named sku, but it is not binding.
the variable sku remains an empty string.
var sku = ""; //to be passed to server when filled
var cookie_info = {
number_nights: number_nights_cookie,
number_travelers: number_travelers_cookie,
type_traveler: type_traveler_cookie,
departure_date: departure_date_cookie,
country: country_cookie
};
$.ajax({
type: 'POST',
url: 'https://azooree.com/wp-admin/php/sku-calculation.php',
data: cookie_info,
success: function(response) {
console.log('success', response);
sku = response;
},
error: function() {
console.log('error!');
alert("[ERROR] Information lost, please try again. Thank you!");
}
});
var basic = {
info: sku + "LP"
};

The value of variable sku is being returned from your POST request which is asynchronous. That's why at the time of assigning the value of sku to basic - it will be empty.
You can easily update the value of basic either by using a callback function like below-
$.ajax({
type: 'POST',
url: 'https://azooree.com/wp-admin/php/sku-calculation.php',
data: cookie_info,
success: function(response) {
console.log('success', response);
sku = response;
updateBasicValue(sku);
},
error: function() {
console.log('error!');
alert("[ERROR] Information lost, please try again. Thank you!");
}
});
function updateBasicValue(sku) {
basic = {
info: sku+"LP"
};
}
Or else, you can do whatever you need to do with the sku variable inside the success function of your AJAX request.
UPDATE
You also need to check for CORS issues if your request is being sent from any other domain or subdomain different than the one causing it. - (Thanks LordNeo)

Related

how to properly use else if in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
i have this script for submitting a form using jquery ajax, everything works fine except i can only get two responses, the loading part is implemented but the rest of them i can only get the else statement. the else if, none is working.
the json statement works just fine. and the data is passed to php successfully but the responses are not according.
(function($) {
'use strict';
const FormFunction = function(){
const checkSelectorExistence = function(selectorName) {
if(jQuery(selectorName).length > 0){return true;}else{return false;}
};
let registerForm = function() {
if(!checkSelectorExistence('.registration-form')){return;}
jQuery('.registration-form').on('submit', function( event ) {
event.preventDefault();
let response = $('.loading').addClass('show').show();
jQuery(this).find(".message").addClass('active').show('slow');
const formData = new FormData(this);
const formAction = jQuery(this).attr('action');
jQuery.ajax({
type: 'POST',
url: formAction,
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: 'json',
beforeSend : function(){
$('.info').addClass('show').show('slow');
},
complete : function(){
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
success : function(data)
{
if(data.status === 1){
response = $('.success').addClass('show').show('slow');
}
else if(data.status === 2) {
response = $('.taken').addClass('show').show('slow');
}
else if(data.status === 0){
response = $('.empty').addClass('show').show('slow');
}
else {
response = $('.error').addClass('show').show('slow');
}
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
error : function(data){
$('.error').addClass('show').show('slow');
$('.registration-form')[0].reset();
},
});
});
}
/* Functions Calling */
return {
afterLoadThePage:function(){
registerForm();
},
}
}(jQuery);
/* jQuery Window Load */
jQuery(window).on("load", function (e) {FormFunction.afterLoadThePage();});
})(jQuery);
Based on some comments that we traded I managed to test it out and found out, what is the root of your problem. Even thought you are setting dataType as JSON, what you actually pass from PHP is a string of value "{\"status\":1}". This is currently the content of your data variable in Success function of your AJAX call.
Adding following line of code at begging of your Success function will do what you want it to do: data = JSON.parse(data);. This will parse string returned by PHP into an JSON object in JS which will create data.status instance holding desired value of number type.
I did some test on my end and it worked as expected with IF and ELSE IF as well.

JSON to ver strage cache issue [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
Im retriving data from my php and its working fine , the problem is that
var myData is getting cached and only updates if i refesh my page 2 times...
on my firebug i can see the post updates but when i `console.log(myData);the data is the old one ..until i refresh..
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
}
});
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
You're probably trying to set and read mydata before the request/response is complete. Instead, move that into your success callback.
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
}
});

CefSharp - Get result of AJAX request

I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.
My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has completed its work.
Here an example (just a sample code):
var tasks = pdBrowser.EvaluateScriptAsync(#"
(function(){
$.ajax({
type: ""POST"",
dataType: ""json"",
cache: false,
url: ""_resources/php/ajaxRequests.php"",
async: false,
data: {
action: ""insertCrossPlatform"",
type: """",
values: JSON.stringify(""foo bar"")
},
success: function(response) {
if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
{
return response;
}
else
{
//pageReload();
return ""OK"";
}
},
error: function(xhr, textStatus, errorThrown) {
return errorThrown + ""\n"" + xhr.responseText;
},
complete: function() {
return ""COMPLETE"";
}
});
})();", null);
tasks.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
if (response.Success)
{
if (response.Result != null)
{
MessageBox.Show(response.Result.ToString());
}
}
else
{
MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}, TaskScheduler.Default);
Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?
Thanks in advance.
Firstly SchemeHandler is unlikely to be suitable in this scenario, you would typically implement a SchemeHandler when your providing the response.
Most people choose to bind an object, and call a method on their bound object when they wish to communicate with the parent application. See the FAQ for an example. https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#3-how-do-you-expose-a-net-class-to-javascript
With 49.0.0 you can implement ResponseFilter to gain access to the underlying response buffer, it's complex and not well documented, so if your not comfortable digging through reference C++ code then this option isn't for you. Here's a reference https://github.com/cefsharp/CefSharp/blob/cefsharp/49/CefSharp.Example/Filters/PassThruResponseFilter.cs#L17
Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.
When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.
var myDivElement =document.getElementById('textareaInfo');
if( myDivElement === null)
{
var input = document.createElement('textarea');
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"
var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}
Then later with ajax
var root = 'https://jsonplaceholder.typicode.com';
var _holder = callbackObj;
callbackObj.showMessage(""ajax"");
$.ajax({
url: root + '/posts/1',
contentType: 'application/json; charset=utf-8',
method: 'GET',
complete: function(data){
},
success: function(response) {
$(#'textareaInfo').value(response);
}
}).then(function(data) {
callbackObj.showMessage(data);
});
Then read the texarea from cefsharp in c#
chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result
You can use PostMessage javascript method to notify .NET application:
CefSharp.PostMessage('Your data Here');
Here is .NET code example for headless browser:
var browser = new ChromiumWebBrowser("", null, RequestContext);
browser.JavascriptMessageReceived += (sender, e) =>
{
if ((string)e.Message.notificationid == "notification1")
{
// Your processing code goes here
}
};
browser.Load(destinationUrl);
browser.ExecuteScriptAsync("(function() { ... ; CefSharp.PostMessage({data: data, notificationid: 'notification1'});})()");

Why return not working after Ajax call jquery? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am not able get the returned value after ajax call. I can see that values are being returned but when I do console.log() it shows undefined. Is there something wrong in my approach.
var base_path = "http://localhost/lab/theapp/api/"
$(function () {
var url = base_path + "tasks"
var type = "post"
var data = ""
var get = submit_me(type, data, url)
console.log(get)
})
function submit_me(type, data, url) {
try {
$.ajax({
url: url,
type: type,
data: data,
dataType: "json",
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", $.cookie("token"))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('page_login_submit - failed to login');
console.log(JSON.stringify(XMLHttpRequest))
console.log(JSON.stringify(textStatus))
console.log(JSON.stringify(errorThrown))
},
success: function (r) {
if (r.sessid) {
var sessid = r.sessid
var session_name = r.session_name
var token = r.token
jQuery.cookie("token", token)
return r
}
},
})
} catch (error) {
console.log(error)
}
}
Your ajax call will take some time to retrieve that values. You cannot pass the value directly to the variable. Write the code in ajax success function. ie console.log() in ajax request function. That would follow the delay caused by the ajax call. Try this link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings Check the async attribute here and experiment.

Javascript retrieving username from db [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to write a JavaScript function that retrieves surname that corresponds to a supplied email address with no success so far. Here's my code:
function getUsername(){
var username;
$(function(){
var dataString = 'email=' + EMAIL_ADDRESS;
$.ajax({
url: 'user_crud_operations.php',
data: dataString,
dataType: 'json',
success: function(data){
U = data[1];
username = data;
}
});
});
return username;
}
I need to use the retrieved username in another function elsewhere. Where am I going wrong?
Asynchronous functions (as used in AJAX) usually do not return values but instead trigger callback functions.
You must restructure your design so that "getUserName()" passes to a callback instead of returning a value. For example:
function getUsername(handler) {
// ...
$.ajax({
// ...
}).done(function(username) {
if (handler && (typeof(handler)==='function')) {
handler(username);
}
});
}
// Sample usage...
getUsername(function(username) {
alert("OK: username=" + username);
});

Categories