Michael Kaufman
Michael Kaufman

Reputation: 803

How to change jQuery AJAX URL with input text on form submit?

I'm kind of new to AJAX and form submission. I have a page that loads stock market data and populates fields with latest price, change, high, low etc...

I'm trying to change the stock market symbol (AJAX URL) by taking an input field's value and changing the AJAX URL without a page refresh hopefully.

In this plunkr, you can see I have a hard-coded value for the AJAX URL that pulls in data for AAPL and this works, however, I need to change that URL to whatever value is in the html form input field but can't figure out how. All that needs to change is the last stock symbol part of the URL. I would really appreciate someone's help.

click the eye/live-preview icon on Plunker

$.ajax({
dataType: 'jsonp',
url: 'http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=AAPL',
success: function(data) {
$('h1').html(data.Name);
$('.container #companyName').html(data.Name);
$('#lastPrice').html(data.LastPrice.toFixed(2));
$('#change').html(data.Change.toFixed(2));
$('#changePercent').html("(" + data.ChangePercent.toFixed(2) + "%)");
$('#range p').html(data.Low + '- ' + data.High);
$('#open p').html(data.Open.toFixed(2));
$('#volume p').html(Math.round(data.Volume / 100000));
$('#marketCap p').html(Math.round(data.MarketCap / 1000000000));

var vol = data.Volume.toString();
if (vol > 6) {
$('#volume p').append('M');
}

var cap = data.Volume.toString();
if (cap > 7) {
$('#marketCap p').append('B')
}


var date = new Date();
var hours = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
var am_pm = date.getHours() >= 12 ? "PM" : "AM";
//hours = hours < 10 ? "" + hours : hours;
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes():date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() :date.getSeconds();
time = hours + ":" + minutes + ":" + seconds + " " + am_pm;
$('#time').html('As of ' + time);

$("#getQuote").submit(function(event) {
var newURL = 'http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=' + $('#symbolInput').val();
$.ajax({url:newURL});
event.preventDefault();
});
}
});

and here is what the HTML looks like (it's using bootstrap):

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Stock Quotes</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>
  <div id="quote-module" class="col-md-12">
    <h1></h1>
  </div>
  <hr id='hruleFat' />
  <div class="container">
    <div class="row">
      <div class='col-md-1' id='companyName'></div>
    </div>
    <div id='prices'>
      <div class='row'>
        <div id='lastPrice' class='col-md-6 pull-left'></div>
        <div id='changes'>
          <div id='changePercent' class='col-md-3 pull-right'></div>
          <div id='change' class='col-md-3 pull-right'></div>
        </div>
      </div>
    </div>
    <hr>
    <div id='range'>
      <p class='pull-right'></p>Range</div>
    <hr>
    <div id='open'>
      <p class='pull-right'></p>Open</div>
    <hr>
    <div id='volume'>
      <p class='pull-right'></p>Volume</div>
    <hr>
    <div id='marketCap'>
      <p class='pull-right'></p>Market Cap</div>
    <hr>
  </div>
  <div class='row'>
    <div id='time' class='col-md-6 pull-right'></div>
  </div>
  <hr>
  <div id='getQuoteForm' class='row'>
    <form class="form-inline" id='getQuote'>
      <div class="form-group" id='formGroup'>
        <div class='col-xs-6'>
          <input type="text" class="form-control" id="symbolInput">
        </div>
        <div class='col-xs-6'>
          <button type="submit" class="btn btn-default">Get New Quote</button>
        </div>
      </div>

    </form>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css" />
</body>
</html>

Upvotes: 1

Views: 2970

Answers (3)

Anonymous
Anonymous

Reputation: 1998

Method $.ajax takes an object with options as parameter, thus you can rewrite your code this way

var options = {
    dataType: 'jsonp',
    url: 'http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=AAPL'
    // here go other options
}

$('.someForm').bind('submit', function(e)
{
    $.ajax(options);     // send request
    e.preventDefault();  // stop default form action
    return false;        // do some form specific action
});

Then, if after first submission you decided to change URL to another, then simply change relevant property in your "options" object, all possible URLs can be defined in JS or in some DropDown control on your form, for instance :

$('.someForm .urlSelector').bind('click', function()
{
    var selector = $(this);
    options.url = selector.val();
});

After this, when you click "submit" button again it will send request to URL taken from "urlSelector" element on your form.

Upvotes: 2

james emanon
james emanon

Reputation: 11837

wrap your ajax code in a function ala..

function fireAjax(data){

   $.ajax({
     dataType: 'jsonp',
     url: data.url,
     success: function(data) {
       $('h1').html(data.Name);
       $('.container #companyName').html(data.Name);
       $('#lastPrice').html(data.LastPrice.toFixed(2));
    // etc...
}

then, your submit code outside that function. Now, you "can" keep it all together and add a listener onto the "submit click".. concept of it is the same.

$("#getQuote").submit(function(event) {
  var newURL = 'http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=' + $('#symbolInput' ).val();
  fireAjax({url:newURL});
  event.preventDefault();
});

Upvotes: 3

Goku
Goku

Reputation: 176

You can concatenate the value of the input from to the url, try this

url: 'http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol='+ $('input#symbolInput').val(),

Upvotes: -2

Related Questions