Getting value out of range with jQuery

Essentially, I'm trying to figure out how to get the span value (id = "camera_status") that was populated with the name of the image after it was captured using a phone screen saver.

The way I want it to work is that the image name will then be uploaded to the database along with the form information provided. At the moment, it seems that it is reading the initial empty value before the space is filled with the image name. If anyone who knows how I can fix this will be grateful.

HTML and Javascript form pages

<div> <input type="button" onclick="takePicture();" value="Take Picture" /><br/> </div> <div> <div> <b>Status:</b> <span id="camera_status"></span><br> <b>Image:</b> <img style="width:240px;visibility:hidden;display:none;" id="camera_image" src="" /> </div> <div id="landmark-1" data-landmark-id="1"> <form id="uploadForm"> <label for="email"> <b>Email</b> <input type="email" id="email" name="email"> </label> <label for="comment"> <b>Comment</b></br> <input id="comment" name="comment" cols="30" rows="10"></textarea> </label> <input type="button" onclick="uploadPicture();" value="Upload New location" /> <input type="submit" value="Upload New location" /> </form> <script> var spanValue = $('#camera_status').html() $(function(){ $('#uploadForm').submit(function(){ var landmarkID = $(this).parent().attr('data-landmark-id'); var postData = $(this).serialize(); $.ajax({ type: 'POST', data: postData+'&lid='+spanValue, //change the url for your project url: 'save.php', success: function(data){ console.log(data); alert('Your comment was successfully added'); }, error: function(){ console.log(data); alert('There was an error adding your comment'); } }); return false; }); }); </div> </div> </div> 
+4
source share
2 answers

Get spanValue when you intend to use it, and not outside the DOM ready function before anything loads:

 $(function(){ $('#uploadForm').on('submit', function(e){ e.preventDefault(); var landmarkID = $(this).parent().data ('landmark-id'), postData = $(this).serialize(), spanValue = $('#camera_status').text() $.ajax({ type: 'POST', data: postData+'&lid='+spanValue, url: 'save.php' }).done(function(data) { console.log(data); }); }); }); 
+3
source

Try .text() :

 var spanValue = $('#camera_status').text(); 
+6
source

Source: https://habr.com/ru/post/1479044/


All Articles