Because itâs asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.
Take the section youâve marked âajax endsâ and put it in your ajax callback function:
success : function(response){
value = response.company;
modal.find('.modal-title').text('New message to ' + value);
}
If you care about developer convenience, you could write your code with async/await.
Since jQuery 3.x, $.ajax returns Promises - which is a browser-builtin technology to manage asynchronous code.
So instead of infinitely nesting your callbacks (you will get tired of callbacks once you have to fetch resources after fetching, because your data is dependend) you could also use .then() and .catch()
Since the javascript community and specification LOVES promises - they are built into every browser by now, they invented syntax to make this even easier:
async function setModalTitle() {
var response = await $.post(url)
modal.find('.modal-title').text('New message to ' + response.company)
}
This way, you can write your javascript as if it were synchronous. Without needing to wrap something in callbacks etc.
By the way, this âasyncâ function also returns a Promise.
Which means it can be awaited by another async function:
async function updateModal() {
await setModalTitle()
console.log('done!')
}
async/await is supported in all modern browsers: https://caniuse.com/#feat=async-functions
If you do care about backwards compatibility with IE, but want that developer comfort, there are tools (webpack, parcel, babel) to automate transforming the code into IE understandable code.
If you care about developer convenience, you could write your code with async/await.
Since jQuery 3.x, $.ajax returns Promises - which is a browser-builtin technology to manage asynchronous code.
If youâre going to use async/await, you donât need to use jQuery. Fetch API is promise based already and is a native function in the same browsers where async/await is available.