Im sure there is a simple solution for this but im having issues,
I have an external ajax.js file that has an AJAX call like so:
$(function() {
$.ajax({
url: url,
success: function( data, status )
above the AJAX call I have got two global variables called ticker and url like so:
var ticker = 'AAPL'
var url = 'http://blahblahblah' + ticker
In my HTML file I have got an input box where the user types in a ticker symbol (e.g. GOOG) and clicks a button that would update the ticker variable so that the AJAX call is done again with the new URL.
<form id="form">
<h3>Enter the ticker symbol of the company you wish to view:</h3>
<input type="text" id="userInput">
<button onclick="myFunction()">Try it</button>
</form>
<script type="text/javascript" src="ajax.js">
<script>
function myFunction()
{
//old value
alert(ticker);
ticker = document.getElementById('userInput').value;
//new value
alert(ticker);
}
</script>
This code changes the ticker variable but the AJAX call is still being performed with the old ticker url. I think its not being assigned properly? Im very new to AJAX but I cant find any tutorials online that explain this problem.
Thanks
Strings are immutable in Javascript, meaning that url is going to be constant, even if you change ticker. Do this instead:
$(function() {
$.ajax({
url: "http:/blah" + ticker,
success: function(data, status) {}
});
});
EDIT: Now that I think about it, it has nothing to do with strings being immutable. Doing url = "http:/" + ticker doesn't create a closure with the value of ticker, it simply creates a new string value and stores it in url. After the new value is created, it's not linked to ticker in any way.
As far as I can tell from the code you've posted, your ajax routine is only being called when the page is loaded, which explains why only the default url / ticker is shown in the results.
You need to wrap the ajax routine in a function and call it after the user has inputted a symbol:
In your ajax.js file:
function getSymbolInfo(ticker) { // consider passing ticker to this function instead of using a global var
$.ajax({
url: url + ticker,
success: function( data, status ) {
// show results
}
});
}
And from MyFunction:
function myFunction()
{
var ticker = document.getElementById('userInput').value;
getSymbolInfo(ticker);
}
Related
I have an Ajax call to comments-set.php. In the php file I set a session variable to a random value. In the Ajax.done callback I'd like to retrieve the session variable.
I have verified that the session variable is being correctly set to a new random value but the old value is still displayed by the code in .done.
$(document).on("click", "#submit", function () {
var comment = document.getElementById('comment').value
var no_spam = document.getElementById('no_spam').value
var jqxhr = $.ajax({
type:"POST",
url: "comments-set.php",
dataType: "html",
data:{no_spam:no_spam, comment:comment}
})
.done(function(data) {
$("#display").html(data);
$('input[type="text"],textarea').val('');
var nsq = '<label for="no_spam" style="color:#717171;" id="no_spam_Q"><?php echo $_SESSION['q']; ?></label>';
$("#no_spam_Q").replaceWith(nsq);
});
});
I assume (with my very limited knowledge!) this has something to do with Ajax being async or JS not waiting for the php to resolve. How can I get round this?
I've tried using events like Ajax.complete instead of doing it in the .done without success, I've even used onMouseUp on the button that triggers this code, figuring it gets fired in mouse down, so I'll get the session variable in mouse up, still no joy.
I have a problem with jQuery and PHP.
I have a .php file that contains a variable, for example var surname = "";
The problem that I am facing is, I want remotely access it from a .html file and give it a value from another variable in the .html file.
Is there any way to do it?
Thanks.
Ok, so you said you wanted to get a variable from HTML and send it to the PHP file to change data, that is what the variable 'varfromhtml' is.
You just need to give it a value you want to send, you can get the value of a div using jQuery eg
<div id="div">data</div>
var varfromhtml = $.("#div").val();
The variable 'varfromhtml' is now equal to 'h08sahdas', you can mess around with that to get it right for you.
Here is the final script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var varfromhtml = $.("#div").val();
$(document).ready(function(){
$.ajax({
method: "POST",
action: "myfile.php",
data: {
varfromhtml:varfromhtml
},
success: function(data){
$('#mydiv').val(data);
}
});
</script>
I want to know how an I target javascript variable using jquery. Here is situation of my web page where I want to use some details that are stored in javascript variable which I will use in user registration. My page codes looks like this
<html>
<head>
<script>
var userData =
{"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
</script>
</head>
<body>
<form id="register">
<button id="regbtn">Register</button>
</form>
</body>
<script src="jquery.js"></script>
<script src="custom.js"></script>
</html>
So now how can I use custom jquery function that will target "userData" variable on click of "regbtn"?
I am doing in my custom javascript is
$( document ).ready(function() {
$('#regbtn').click(function(){
//do something here that will target that userData variable and will send its data using ajax
//$ajax function will send data to page with details that user entered and userData
});
});
But I don't know how to target that userData variable using json. This variable in json data format out put of php. Can anyone help me?
And with negative votes I'd appreciate if you tell me why are you voting negative this question. I am not pro so asked this question. May be this is stupid but not for me. So thank you anyways for seeing this question
If you need to access your json object "userData", you'll want to add the following in your click function:
var country = userData['country'];
var region = userData['region'];
and so on.
You could send the whole object without separation if you plan on sending it via AJAX. Below is an example of this:
$(function() {
var userData = {"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
$('#regbtn').click(function() {
$.ajax({
url: "someURL",
data: userData,
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, textStatus, jqXHR) {
// check if response was valid/invalid or do other stuff here
});
});
});
I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.
I have an SVG with this code for some shapes (its a map)
onclick="top.traeDatos(evt.target.id);"
in the html file I have:
function traeDatos(region){
alert(region);
}
So, I click on a region, I have the alert window with the region name and the variable in the html file. Thats great
Now I want that the click on the map shows a popup with more information i'll get using ajax from multiple databases trough a file called, for example "getDetails.php".
Im new in js and ajax, I know how to make a standard call in ajax to get some information given an id (or name in this case), I know how to change the value of a text field to the text I get trought the ajax call...but I dont understand how to call ajax and show a tooltip from that javascript code in the SVG or the one in html.
Im not sure too of what tolltip to use, but one problem at the time ;)
Can you enlighten me a little.
Thanks!
Here's a start:
function traeDatos(region){
var domn = document.domain;
document.domain = domn;
var detURL = "http://" + domn + "/getDetails.php";
$.ajax({
url: detURL,
type: 'POST',
data: {
region: region
},
cache: false,
success: function(json){
var data = jQuery.parseJSON(json);
//using PHP's json_encode() you can return an array
//in the example below 'info' is an item in the array
$('#insert_place').val(data.info);
}
});
}
Let me know if you have some problem with that.