none
my jquery script working only after refreshing a page in sharepoint

    Frage

  • I made a jquery script that add a date with an attachment. It's working fine but it is very boring to do refresh every time. How can I solve this problem? 
    Donnerstag, 7. Juni 2018 10:39

Alle Antworten

  • Hi,

    Would you please share the Jquery code you are using so that we can look into the issue more easily.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Freitag, 8. Juni 2018 02:52
  • Hi,

    Would you please share the Jquery code you are using so that we can look into the issue more easily.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.


    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>

        <script type="text/javascript">

            $(document).ready(function () {

                SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments);

            });

            var attfiles;

            function RenameAttachments() {

                var ctx = new SP.ClientContext.get_current();

                attfiles = ctx.get_web().getFolderByServerRelativeUrl('Lists/Test/Attachments/' + getUrlParameter('ID')).get_files();

                ctx.load(attfiles);

                ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailed));

            }

     

            function onSuccess(sender, args) {

                var reload = false;

                var filesenum = attfiles.getEnumerator();

                while (filesenum.moveNext()) {

                    var file = filesenum.get_current();

                    var name = file.get_name();

                    var relurl = file.get_serverRelativeUrl();

                    console.log(name);

                    if (name.indexOf('(Date') == -1) {

                        reload = true;

                        var res = relurl.split('.');

                        res[res.length - 2] = res[res.length - 2] + '(Date ' + $('#ctl00_ctl40_g_b39a3716_b1e0_4b3d_bb9b_ee7fee338646_FormControl0_V1_I1_E35').text() + ')';

                        var newrelurl = res.join('.');

                        $.ajax({

                            url: "/Test/_api/web/getfilebyserverrelativeurl('" + relurl + "')/moveto(newurl='" + newrelurl + "', flags = 1)",

                            type: 'POST',

                            headers: {

                                'accept': 'application/json;odata=verbose',

                                'content-type': 'application/json;odata=verbose',

                                'X-HTTP-Method': 'PUT',

                                'X-RequestDigest': $('#__REQUESTDIGEST').val()

                            },

                            success: function (data) { if (data.d.MoveTo == null) { } },

                            error: function (xhr, status, message) { console.log(status, message); }

                        });

                    }

                }

            }

     

            function onFailed(sender, args) {

                console.log(args);

            }

     

            function getUrlParameter(sParam) {

                var sPageURL = decodeURIComponent(window.location.search.substring(1)),

                    sURLVariables = sPageURL.split('&'),

                    sParameterName,

                    i;

                for (i = 0; i < sURLVariables.length; i++) {

                    sParameterName = sURLVariables[i].split('=');

                    if (sParameterName[0] === sParam) {

                        return sParameterName[1] === undefined ? true : sParameterName[1];

                    }

                }

            }

        </script>

    Dienstag, 12. Juni 2018 07:47
  • Hi,

    Your function is called in document.ready event which will only be triggered when page refresh.

    You could add a button click event so that when button clicked, it will trigger your function:

    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    
        <script type="text/javascript">
    
            $(document).ready(function () {
    			  $("#test").click(function(){
    					SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments);
    				});
            });
    
            var attfiles;
    
            function RenameAttachments() {
    
                var ctx = new SP.ClientContext.get_current();
    
                attfiles = ctx.get_web().getFolderByServerRelativeUrl('Lists/Test/Attachments/' + getUrlParameter('ID')).get_files();
    
                ctx.load(attfiles);
    
                ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailed));
    
            }
    
     
    
            function onSuccess(sender, args) {
    
                var reload = false;
    
                var filesenum = attfiles.getEnumerator();
    
                while (filesenum.moveNext()) {
    
                    var file = filesenum.get_current();
    
                    var name = file.get_name();
    
                    var relurl = file.get_serverRelativeUrl();
    
                    console.log(name);
    
                    if (name.indexOf('(Date') == -1) {
    
                        reload = true;
    
                        var res = relurl.split('.');
    
                        res[res.length - 2] = res[res.length - 2] + '(Date ' + $('#ctl00_ctl40_g_b39a3716_b1e0_4b3d_bb9b_ee7fee338646_FormControl0_V1_I1_E35').text() + ')';
    
                        var newrelurl = res.join('.');
    
                        $.ajax({
    
                            url: "/Test/_api/web/getfilebyserverrelativeurl('" + relurl + "')/moveto(newurl='" + newrelurl + "', flags = 1)",
    
                            type: 'POST',
    
                            headers: {
    
                                'accept': 'application/json;odata=verbose',
    
                                'content-type': 'application/json;odata=verbose',
    
                                'X-HTTP-Method': 'PUT',
    
                                'X-RequestDigest': $('#__REQUESTDIGEST').val()
    
                            },
    
                            success: function (data) { if (data.d.MoveTo == null) { } },
    
                            error: function (xhr, status, message) { console.log(status, message); }
    
                        });
    
                    }
    
                }
    
            }
    
     
    
            function onFailed(sender, args) {
    
                console.log(args);
    
            }
    
     
    
            function getUrlParameter(sParam) {
    
                var sPageURL = decodeURIComponent(window.location.search.substring(1)),
    
                    sURLVariables = sPageURL.split('&'),
    
                    sParameterName,
    
                    i;
    
                for (i = 0; i < sURLVariables.length; i++) {
    
                    sParameterName = sURLVariables[i].split('=');
    
                    if (sParameterName[0] === sParam) {
    
                        return sParameterName[1] === undefined ? true : sParameterName[1];
    
                    }
    
                }
    
            }
    
        </script>
    	
    	<input type="button" id="test" name="test" value="test" />

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Dienstag, 12. Juni 2018 08:07
  • Hi,

    Your function is called in document.ready event which will only be triggered when page refresh.

    You could add a button click event so that when button clicked, it will trigger your function:

    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    
        <script type="text/javascript">
    
            $(document).ready(function () {
    			  $("#test").click(function(){
    					SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments);
    				});
            });
    
            var attfiles;
    
            function RenameAttachments() {
    
                var ctx = new SP.ClientContext.get_current();
    
                attfiles = ctx.get_web().getFolderByServerRelativeUrl('Lists/Test/Attachments/' + getUrlParameter('ID')).get_files();
    
                ctx.load(attfiles);
    
                ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailed));
    
            }
    
     
    
            function onSuccess(sender, args) {
    
                var reload = false;
    
                var filesenum = attfiles.getEnumerator();
    
                while (filesenum.moveNext()) {
    
                    var file = filesenum.get_current();
    
                    var name = file.get_name();
    
                    var relurl = file.get_serverRelativeUrl();
    
                    console.log(name);
    
                    if (name.indexOf('(Date') == -1) {
    
                        reload = true;
    
                        var res = relurl.split('.');
    
                        res[res.length - 2] = res[res.length - 2] + '(Date ' + $('#ctl00_ctl40_g_b39a3716_b1e0_4b3d_bb9b_ee7fee338646_FormControl0_V1_I1_E35').text() + ')';
    
                        var newrelurl = res.join('.');
    
                        $.ajax({
    
                            url: "/Test/_api/web/getfilebyserverrelativeurl('" + relurl + "')/moveto(newurl='" + newrelurl + "', flags = 1)",
    
                            type: 'POST',
    
                            headers: {
    
                                'accept': 'application/json;odata=verbose',
    
                                'content-type': 'application/json;odata=verbose',
    
                                'X-HTTP-Method': 'PUT',
    
                                'X-RequestDigest': $('#__REQUESTDIGEST').val()
    
                            },
    
                            success: function (data) { if (data.d.MoveTo == null) { } },
    
                            error: function (xhr, status, message) { console.log(status, message); }
    
                        });
    
                    }
    
                }
    
            }
    
     
    
            function onFailed(sender, args) {
    
                console.log(args);
    
            }
    
     
    
            function getUrlParameter(sParam) {
    
                var sPageURL = decodeURIComponent(window.location.search.substring(1)),
    
                    sURLVariables = sPageURL.split('&'),
    
                    sParameterName,
    
                    i;
    
                for (i = 0; i < sURLVariables.length; i++) {
    
                    sParameterName = sURLVariables[i].split('=');
    
                    if (sParameterName[0] === sParam) {
    
                        return sParameterName[1] === undefined ? true : sParameterName[1];
    
                    }
    
                }
    
            }
    
        </script>
    	
    	<input type="button" id="test" name="test" value="test" />

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.


    How can I do it? Can you show me?
     Already I have a button to submit in infopath
    , I think it will not be useful to make a button to click on it after adding attachment. If there is another simple method please show me.
    • Bearbeitet Zahra1234 Dienstag, 12. Juni 2018 09:34 edit
    Dienstag, 12. Juni 2018 09:28
  • Hello,

    You could add the script using Script Editor Web Part:

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Dienstag, 12. Juni 2018 09:35
  • Hello,

    You could add the script using Script Editor Web Part:

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.


    This is what I am using (script editor webpart).
    Dienstag, 12. Juni 2018 10:09
  • Hi,

    If you want to rename the attachments in the InfoPath form after adding, you could bind click event to the submit button, change the Jquery selector with the submit button, basically change this line:

    $("#test").click(function(){
    					SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments);
    				});

    This is the button click event, change to the submit button by changing the selector #test.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Mittwoch, 13. Juni 2018 01:08
  • Hi,

    If you want to rename the attachments in the InfoPath form after adding, you could bind click event to the submit button, change the Jquery selector with the submit button, basically change this line:

    $("#test").click(function(){
    					SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments);
    				});

    This is the button click event, change to the submit button by changing the selector #test.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.


    It doesn't work for me. In the other hand it is not practical to take the id of the button. because as you see in the code I take the id of the date, and the date at the first time is not available.
    Mittwoch, 13. Juni 2018 06:55
  • Hi,

    Then how did you execute your custom script ? If you don't want to execute by refreshing page, it is necessary to execute in other events.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Mittwoch, 13. Juni 2018 07:01
  • Hi,

    Then how did you execute your custom script ? If you don't want to execute by refreshing page, it is necessary to execute in other events.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.


    It is not practical to see the result of jquery after refreshing the page everytime. It will be boring for the user. And this is my question, I want a solution for this problem rather than refreshing the page everytime.
    Mittwoch, 13. Juni 2018 08:37
  • Hi,

    You could use JavaScript SetInterval Timer to execute your function automatically without refreshing the page:

    setInterval(function(){ SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments); }, 3000);

    About JavaScript SetInterval Timer, please refer:

    Window setInterval() Method

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Freitag, 15. Juni 2018 05:40
  • Hi,

    You could use JavaScript SetInterval Timer to execute your function automatically without refreshing the page:

    setInterval(function(){ SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments); }, 3000);

    About JavaScript SetInterval Timer, please refer:

    Window setInterval() Method

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.


    It's the same. I removed $(document).ready and I put it as you did, but I should refresh the page to work for me.
    Mittwoch, 20. Juni 2018 07:09
  • Hello,

    SetInterval will trigger the function automatically once you open the page, you won't need to refresh the page again which will meet you requirement.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Mittwoch, 20. Juni 2018 07:15
  • Hello,

    SetInterval will trigger the function automatically once you open the page, you won't need to refresh the page again which will meet you requirement.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    the function is not triggered automatically once I opened the page. So I need to make a refresh :(. I did it as you said.

    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
    setInterval(function(){ SP.SOD.executeFunc("sp.js", 'SP.ClientContext', RenameAttachments); }, 3000);

            var attfiles;
            function RenameAttachments() {
                var ctx = new SP.ClientContext.get_current();
                attfiles = ctx.get_web().getFolderByServerRelativeUrl('Lists/LegalIssues/Attachments/' + getUrlParameter('ID')).get_files();
                ctx.load(attfiles);
                ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailed));
            }
            function onSuccess(sender, args) {
                var reload = false;
                var filesenum = attfiles.getEnumerator();
                while (filesenum.moveNext()) {
                    var file = filesenum.get_current();
                    var name = file.get_name();
                    var relurl = file.get_serverRelativeUrl();
                    console.log(name);
                    if (name.indexOf('(Date') == -1) {
                        reload = true;
                        var res = relurl.split('.');
                        res[res.length - 2] = res[res.length - 2] + '(Date ' + $('#ctl00_ctl40_g_b39a3716_b1e0_4b3d_bb9b_ee7fee338646_FormControl0_V1_I1_E35').text() + ')';
                        var newrelurl = res.join('.');
                        $.ajax({
                            url: "/LegalIssues/_api/web/getfilebyserverrelativeurl('" + relurl + "')/moveto(newurl='" + newrelurl + "', flags = 1)",
                            type: 'POST',
                            headers: {
                                'accept': 'application/json;odata=verbose',
                                'content-type': 'application/json;odata=verbose',
                                'X-HTTP-Method': 'PUT',
                                'X-RequestDigest': $('#__REQUESTDIGEST').val()
                            },
                            success: function (data) { if (data.d.MoveTo == null) { } },
                            error: function (xhr, status, message) { console.log(status, message); }
                        });
                    }
                }
            }
            function onFailed(sender, args) {
                console.log(args);
            }
            function getUrlParameter(sParam) {
                var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                    sURLVariables = sPageURL.split('&'),
                    sParameterName,
                    i;
                for (i = 0; i < sURLVariables.length; i++) {
                    sParameterName = sURLVariables[i].split('=');
                    if (sParameterName[0] === sParam) {
                        return sParameterName[1] === undefined ? true : sParameterName[1];
                    }
                }
            }
        </script>

    • Bearbeitet Zahra1234 Mittwoch, 20. Juni 2018 09:34 edit
    Mittwoch, 20. Juni 2018 08:18
  • Hello,

    A simple test result with SetInterval method for your reference:

    <script type="text/javascript">
    setInterval(function(){SP.SOD.executeFunc("sp.js", 'SP.ClientContext', retrieveListItems);}, 3000);
    var siteUrl = '/sites/dev';
    
    function retrieveListItems() {
    
        var clientContext = new SP.ClientContext(siteUrl);
        var oList = clientContext.get_web().get_lists().getByTitle('Dummy');
            
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><RowLimit>10</RowLimit></View>');
        this.collListItem = oList.getItems(camlQuery);
            
        clientContext.load(collListItem);
            
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        
            
    }
    
    function onQuerySucceeded(sender, args) {
    
        var listItemInfo = '';
    
        var listItemEnumerator = collListItem.getEnumerator();
            
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            listItemInfo += '\nID: ' + oListItem.get_id() + 
                '\nTitle: ' + oListItem.get_item('Title'); 
                
        }
    
        console.log(listItemInfo.toString());
    }
    
    function onQueryFailed(sender, args) {
    
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    </script>
    

    As you can see, "28" is the execution count of the function. It will automatically executed once you opened the page. This is a JavaScript Timer which can automatically trigger function.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Mittwoch, 20. Juni 2018 08:37
  • Hello,

    A simple test result with SetInterval method for your reference:

    <script type="text/javascript">
    setInterval(function(){SP.SOD.executeFunc("sp.js", 'SP.ClientContext', retrieveListItems);}, 3000);
    var siteUrl = '/sites/dev';
    
    function retrieveListItems() {
    
        var clientContext = new SP.ClientContext(siteUrl);
        var oList = clientContext.get_web().get_lists().getByTitle('Dummy');
            
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><RowLimit>10</RowLimit></View>');
        this.collListItem = oList.getItems(camlQuery);
            
        clientContext.load(collListItem);
            
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        
            
    }
    
    function onQuerySucceeded(sender, args) {
    
        var listItemInfo = '';
    
        var listItemEnumerator = collListItem.getEnumerator();
            
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            listItemInfo += '\nID: ' + oListItem.get_id() + 
                '\nTitle: ' + oListItem.get_item('Title'); 
                
        }
    
        console.log(listItemInfo.toString());
    }
    
    function onQueryFailed(sender, args) {
    
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    </script>

    As you can see, "28" is the execution count of the function. It will automatically executed once you opened the page. This is a JavaScript Timer which can automatically trigger function.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    As you said it is refreshed in the page itself, but it's not appear in edit the page when I open it again, and if I attach another document it gives me an error because the date is not available in the previous attachment.(it's not affected in the page directly)


    • Bearbeitet Zahra1234 Mittwoch, 20. Juni 2018 10:01 edit
    Mittwoch, 20. Juni 2018 10:00