Site icon Hip-Hop Website Design and Development

WordPress jQuery Post – Amending Variable Value Within Function Command

I have a variable in Javascript which I am trying to pass to PHP. I have this working using jQuery.post. The issue is, the variable (linkforsharedURL) is declared within a multidimensional array and the default value is immediately sent when the jQuery.post command is executed. However the value of this variable is further modified within the function, but the modified value is not sent to PHP – the original value is sent.

A solution forward I was considering was to execute another jQuery.post just after the If statement again containing the updated ‘data’ array – but I don’t think this would be best practice.

I did consider bringing the If statement out of the jQuery.post, however the If statement is dependent on the jQuery’s response variable.

Another idea was whether there is any way to allow everything in jQuery.post to execute and then send to PHP (asynchronous?).

My apologies for the way I have explained the above – just trying to get my head round this particular issue.

    // build data
    var dataURL = dataURLs[0],
        data = {
            email: email,
            name: name
            linkforsharedURL: linkforsharedURL 
        };
    
    // send data
    jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {


        if (response.share_id !== undefined) {
            var pattern = new RegExp('(share_id=).*?(&|$)'), shareUrl = window.location.href;
            if (shareUrl.search(pattern) >= 0) {
                shareUrl = shareUrl.replace(pattern, '$1' + response.share_id + '$2');
                linkforsharedURL = shareUrl;
                
            }