I want to save/assign an AJAX success response to a global variable. The response is fetched into a <p> tag, but how can I assign this response into a global variable for further use?
var x;
$.ajax({
url: url,
data: {
sending data
},
dataType: 'json',
success: function(data) {
alert(data.d)
}
});
You can just assign the data.d to x in the success block. The final solution would be
var x;
$.ajax({
url: url,
data: {
sending data
},
dataType: 'json',
success: function(data) {
x = data.d;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
const ajaxData = $.ajax({
url: "data.json",
global: false,
type: "POST",
dataType: "jsonData",
async:false,
success: function(msg){
return msg;
}
}).responseText;
console.log(JSON.parse(ajaxData));
</script>
Related
I'm currently working the project using Polymer and I'd like to get the return value of API after POST using Iron-Ajax.
Here is my sample code,
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
dataType: "json",
contentType: 'application/json'
});
rs.done(function (data) {
console.log(data);
alert(data);
}
});
Ajax is asynchronous by default,you need add async:false to make it synchronous
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
async:false,
dataType: "json",
contentType: 'application/json'
});
var result = null;
rs.done(function (data) {
console.log(data);
alert(data);
result = data;
}
});
//return result;//you can return value like this
Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}
i want to post an array from java script to php by ajax. But i don't know how do that, especially send it to php function like controller class. Correct me if i'm wrong, this is my java script source, as a function to send an array :
<script>
function send(){
var obj = JSON.stringify(array);
window.location.href = "post.php?q=" + obj;
}
</script>
i was try, but still fail. really need help..
As described in the JQuery API documentation, you can use
var rootPath="http://example.com/"
var jsonData = $.toJSON({ q: array });
var urlWS = rootPath + "post.php";
$.ajax({
url: urlWS,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function(result) {
// do something here with returned result
}
});
var array= [];
array[0] = 'hi';
array[1] = 'hello';
$.ajax({
url: 'http://something.com/post.php',
data: {array: array},
type: 'POST'
});
try like this,
var data_to_send = $.serialize(array);
$.ajax({
type: "POST",
url: 'post.php',
data: data_to_send,
success: function(msg){
}
});
or
you can pass as json like below,
$.ajax({
type: "POST",
url: 'post.php',
dataType: "json",
data: {result:JSON.stringify(array)},
success: function(msg){
}
});
var arr = <?php echo json_encode($postdata); ?>;
ajax: {
url:"post.php"
type: "POST",
data: {dataarr: arr},
complete: function (jqXHR, textStatus) {
}
You can try this .this will work
example
ajax code:
$.ajax({
url: 'save.php',
data: {data: yourdata},
type: 'POST',
dataType: 'json', // you will get return json data
success:function(result){
// to do result from php file
}
});
PHP Code:
$data['something'] = "value";
echo json_encode($data);
In the success function I want to call a function. The problem is that ajax does not fire, so the data is never triggered and display. Here is my ajax call with a javascript function call in the success function.
$.ajax({
type: "POST",
url: "./api/login.php",
data: dataString,
cache: false,
success: function(data){
if(data){
//FUNCTION CALL WHEN USER LOGGING IN
retrieveUserBlogData();
window.location = "api/home.php";
}else{
$('.alert').show();
}
}
});
function retrieveUserBlogData(){
$.ajax({
type: "GET",
url: 'retrievePostData.php',
data: "",
dataType: 'json',
success: handleData
});
}
function handleData(data) {
alert(data);
var blog_file = data[3];
$('#imageDiv')
.append('<img id="blog_img" src="upload/' + blog_file + '"><br>');
}
I cant figure out why the ajax in the retrieveUserBlogData() function is not being triggered.
Any help would be appreciated Thanks.
Even if the AJAX succeeds, you are redirecting the browser to a different page after the first AJAX request:
window.location = "api/home.php";
So I would suggest removing that.
Try the following code for redirecting to another window
window.location.assign(URL);
then it may work.
Try it like this
$.ajax({
type: "POST",
url: "./api/login.php",
data: dataString,
cache: false,
success: function(data){
if(data){
//FUNCTION CALL WHEN USER LOGGING IN
retrieveUserBlogData();
}else{
$('.alert').show();
}
}
});
function retrieveUserBlogData(){
$.ajax({
type: "GET",
url: 'retrievePostData.php',
data: "",
dataType: 'json',
success: function(data){
alert(data);
var blog_file = data[3];
$('#imageDiv')
.append('<img id="blog_img" src="upload/' + blog_file + '"><br>');
window.location = "api/home.php";
}
});
}
this may sound very easy to few of you, but i am not able to figure out why I am not able to get the return value, even after chceking many posts :(
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
Now if I call var count = getMessageCount();
it gives me undefinted :(
while inside the method count is coming correct, i.e. service is working fine.
I agree with the first line by ahren that
'That's because the $.ajax() call is asynchronous.'
you could try adding a setting - async:false
which is true by default. This makes the call synchronous.
you can edit your code as :
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
That's because the $.ajax() call is asynchronous.
If you edit your code to something like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if(typeof callback === "function") callback(count);
} //success
});
}
Then when you call it:
getMessageCount(function(count){
console.log(count);
});
use a callback:
call function like:
getMessageCount(function(result) {
//result is what you put in the callback. Count in your case
});
and the other like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if (callback) {
callback(count);
}
} //success
});
}
Why you don't just pass it to a function?
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
countMessages(count);
} //success
});
}
function countMessages(counted) {var counted = counted; console.log(counted);}
function ajax_call(url,data){
return $.ajax({ type: "POST",
url: url,
data: data,
async:false,
success: function(status){
}
}).responseText;
}
Now you will get the response text from server side via ajax call