$(document).ready(function () {
$.ajax({
url: "/file_lines",
type: 'GET',
// contentType: 'application/json', // format of Data to be sent to the server
// data: 'json',//Data to be sent to the server
dataType: 'text', //The type of data that you're expecting back from the server.
success: function (lines) {
document.getElementById("tmp").innerHTML = lines
**console.log(document.getElementById("tmp").innerHTML)**
},
error: function (){
alert("get debug log's lines failed");
return false;
}
});
})
// console.log($('#tmp').html())
**var num = document.getElementById("tmp").innerHTML
console.log(num)**
I am so confuse that why I can get innerHtml value of "tmp" in the $(document).ready() but can not get this value outside $(document).ready()! I thought DOM object should be global. So I am quite confuse about this result. Could somebody help me?
Related
I'm trying to POST a comment to a using AJAX in Rails (without using remote: true and am having difficulty understanding why my myJSON variable is returning as undefined, when data is returning as expected.
Here's my code:
function submitViaAjax() {
$("#new_comment_button").on("click", function (e) {
e.preventDefault();
url = $(this.form).attr('action')
data = {
'comment': {
'content': $("#comment_body").val()
}
};
var myJSON = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url,
data: myJSON,
// headers: { 'Content-Type': 'application/json' },
success: function (response) {
var $ul = $("div.comments_section ul");
$ul.append(response)
}
}).done(function(response){
debugger
var $ul = $("div.comments_section ul");
$ul.append(response)
})
})
};
I can run var myJSON = JSON.stringify(data); in the browser console just fine, so I'm not sure why it's not doing anything in my code.
Any help would be appreciated.
I found out why I wasn't getting the response I expected. It's a jQuery function, but I was using JavaScript variable declaration to define myJSON.
In short, I need to remove var from var myJSON = JSON.stringify(data);
EDIT:
Implementing 'use strict'; within that function renders those variables undefined, which may mean that I was originally overwriting them - causing the 400 and/or 422 error.
EDIT 2:
I was getting the 422 error because my data object had a key of content when my param was looking for body.
I have this function, and every time I call it, I need the imagesUploadScript variable to be updated with a new URL. I've implemented in the server side a JSON response with the desired URL for each request, but I'm not able to get that JSON value with jQuery.
$(function () {
$('.editor').editorInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: /* The url*/
}
});
});
I have tried this, but doesn't seem to work :S
$.getJSON("/admin/upload_url",function(result){
return JSON.stringify(result)
})
EDIT
I have restructured my code, this way my function accepts a callbacks as #Mohamad suggested and thanks to this question:
function getURL(callback) {
var url;
$.ajax({
type: "GET",
async: false,
url: "/admin/upload_url",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
url = data['url'];
callback(url);
} //success
});
}
But I'm not able to return the url for imagesUploadScript but yes this way
getURL(function(url){
console.log(url);
});
I'm confused, how should I declare this function inside the other one so imagesUploadScript get's a new URL every time is called ?
Thanks in advance for any help ! :D
I have a script that makes two ajax calls - the second being contained within the success handler of the first.
However I need to use the data captured within the first success handler as a further variable to pass in the second ajax call and then use that variable within the php file that is undertaking the server side processing.
This is all very new to me, so I hope this makes some sort of sense. If anyone could assist that would be great.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id'+lead_id,
data: $('form').serialize(),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I think you lose a "=" sign in the code:
url: 'processtwo.php?lead_id='+lead_id,
You're going to want to split these into two separate functions and allow for a parameter to be passed to the second. Not really part of your question, but should make it much easier to read. The second process seems to be missing an equals sign in the url parameter which will cause it to not work
function processOne() {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function(data) {
//alert("success data from processone is " + data);
//console logs are better to use when debugging data
console.log('SUCCESS DATA', data);
var lead_id = data;
processTwo(lead_id);
}
});
}
function processTwo(lead_id) {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id=' + lead_id,
data: $('form').serialize(),
success: function(data2) {
alert("success data from processtwo is " + data2);
}
});
}
If you're still not getting anything make sure the data is directly returning the lead_id. AJAX calls commonly return JSON data, so it very well might be something like data.lead_id or something like that. Alerts aren't useful for showing this so you could use the console log, console.log('SUCCESS DATA', data) to dig into the return data.
Given the reply to my comment, and making the assumption that the data returned from the first AJAX call is a simple string value (if it's not, you can still use the code here to see how you need to do what you need to do). jQuery's serialize() returns a string (see https://api.jquery.com/serialize/) so you can just append to that.
Also, you are missing your = sign when making your URL, so if you are trying to get the lead_id as a GET var, that's why it's not working.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
// you are missing the equals sign here, which is why this doesn't work as a GET
url: 'processtwo.php?lead_id'+lead_id,
// here we tack on a lead_id variable to the serialized form and give
// it the value you got back from query 1
data: ($('form').serialize() + "&lead_id=" + lead_id),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the first ajax.
The loading class I am adding to the placeholder before sending is working for the first ajax call. However soon after the first ajax request completes the class is removed and never appends again on the second and further calls (remember recursive calls).
While debugging it shows that the beforeSend function of the second ajax call is called first and the complete function of the first ajax call is called later. Which is obvious, because the return data inserted in the page from the first ajax call starts the second call.
In short it's mixed up. Is there any way this can be sorted out?
The function code is as follows
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
$(placeholder).removeClass('loading');
},
dataType: 'html'
});
}
And the data contains the following snippet of javascript/jquery which checks and starts another ajax request.
<script type="text/javascript">//<!--
$(document).ready(function() {
$('#restart').val(-1)
$('#ajaxSubmit').click();
});
//--></script>
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: #get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
I am trying to implement Repository pattern in JavaScript. I have ViewModel which i want to initialize with the data when i call Initialize method on it. Everything seems to be falling in places except that i am not able to return the data from my AJAX call. I can see that data is coming back from the ajax call but when i trying to capture the data in SomeViewModel's done function, it is null.
Can someone please point me out where i am going wrong here?
P.S: Please notice that i am not making Async call so the call chain is properly maintained.
This is how my Repository looks like:
function SomeRepository(){
this.LoadSomeData = function loadData()
{
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
return data;
},
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
}
};
This is how my ViewModel looks like:
function SomeViewModel(repository){
var self = this;
var def = $.Deferred();
this.initialize = function () {
var def = $.Deferred();
$.when(repository.LoadSomeData())
.done(function (data) {
def.resolve();
});
return def;
};
}
This is how i am calling from an aspx page:
var viewModel = new SomeViewModel(new SomeRepository());
viewModel.initialize().done(alert('viewmodel initialized'));
alert(viewModel.someProperty);
I have used successfully an auxiliar variable to put the ajax result, when ajax call is inside a function (only works if ajax is async=false) and i need the function does return the ajax result. I don't know if this is the best solution.
function ajaxFunction(){
var result='';
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
result=data;
},
error: ajaxFailed
});
return result;
}
Doesn't matter that it's synchronous (though it really shouldn't be). Returning a value from inside the ajax callback will not cause the value to be returned from the containing function.
Using asynchronous ajax is generally a much better idea anyway, but that will force you to create an API that allows its clients to pass in handlers to be called when the ajax request completes. To do that, you'd give your "LoadSomeData" function a parameter. A caller would pass in a function, and your ajax "success" handler would pass on the results (or some transformation of the results; depends on what it is that you're doing) to that callback. It's the same idea as the callbacks used in the ajax call itself.