0

I have a jquery/ajax geolocation script that outputs data such as:

$.ajax({
        url: "https://geoip-db.com/jsonp",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function( location ) {
            $('#country').html(location.country_name);
        }
    });

I'm trying to get it to include that in a php form in a hidden field when the rest of the form is submitted. But so far I can't seem to get the geolocation script's data to submit with the form.

The important bit from the php form handler would be:

Country: " . $_POST['field_7'] . " 

And in the html form I've tried:

<input type="hidden" name="field_7" id="#country" value=''>

And various other things like value="$('#country')" but the geolocation data is not being posted/emailed with the form. How can I get the data the geolocation script captures to post to the hidden input in the form?

2
  • 2
    The # in jquery means id=, so you don't want the # in your id, change <input type="hidden" name="field_7" id="#country" value=''> to <input type="hidden" name="field_7" id="country" value=''>. And then set with $("#country").val(location.country_name); - edit: as someone answered. Commented Jun 22, 2018 at 12:51
  • $('#\\#country').val(location.country_name); Commented Jun 22, 2018 at 13:08

3 Answers 3

3

Remove # from your input field.

<input type="hidden" name="field_7" id="country" value=''>

And then in your JS, replace html with val

$.ajax({
    url: "https://geoip-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function( location ) {
        $('#country').val(location.country_name);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Original answer, and nice that you described the two issues.
This is helpful. Thanks. Yes, I can see html is for printing to the page now. val for a form.
1

Try this code:

$.ajax({
        url: "https://geoip-db.com/jsonp",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function( location ) {
            $('#country').val(location.country_name);
        }
    });


<input type="hidden" name="field_7" id="country" value=''>

3 Comments

@freedomn-m thanks. i wrote a short answer to answer quickly
yes, but a short description would improve it drastically (and may have got you marked as the answer).
1

you just need to small change

write val instead of html

$('#country').val(location.country_name); // use val

and in html

Remove # from your input field id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.