0

I cannot figure out where I'm going wrong here. I have an ajax call that calls an insert statement and returns the ID of that insert. This works.

But I'm trying to create a global variable of this so that I can use the ID as a value in another insert and update that are called in a different ajax call.

I currently get the page ID returned and can echo it in the console, but when I call the 2nd function it says invalid integer type for page_id.

The first ajax call:

<script type="text/javascript">
$(document).ready(function(){

    var page_id;

$("#submitForm").click(function(){
event.preventDefault();
var string = $('#pageForm').serialize();

// AJAX Code To Submit Form.
    $.ajax({
        type: "POST",
        url: "addPage.php",
        data: string,
        dataType: 'json',
        cache: false,
        success: function(response){
          console.log(response['last_insert_id']);
          page_id = JSON.stringify(response['last_insert_id']);
        }
    });

});

});
</script>

calls addpage.php

$addpage = "
    INSERT INTO pages (title, page_type_id, display_id, duration)
    VALUES ('$title','$page_type','$display_id','$duration');
";

if ($mysqlConn->query($addpage) === TRUE) {
    $last_id = $mysqlConn->insert_id;
    $data['last_insert_id'] = $last_id;
    echo json_encode($data);
} else {
    echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

So now I want to store the 'last_insert_id' as a global variable back in my first file to use in another ajax call/insert

<script type="text/javascript">
    $(document).ready(function(){

    $("#form-data").submit(function(e){

        var content = tinymce.get("mytextarea").getContent();

        $(".leftContent").html(content);
        $("#new").val(content);

          var string = $('#form-data').serialize() +  page_id;

        // AJAX Code To Submit Form.
            $.ajax({
                type: "POST",
                url: "addPanel.php",
                data: string,
                cache: false,
                success: function(response){
                  console.log(JSON.stringify(response));
                }
            });



        return false;

    });

});
</script>
Geoff_S
  • 4,917
  • 7
  • 43
  • 133
  • Have you tried doing `console.log(string);`? If so, what did it show? – dokgu Jul 24 '18 at 18:12
  • On the first ajax call, or the 2nd? – Geoff_S Jul 24 '18 at 18:12
  • Right after `var string = $('#form-data').serialize() + page_id;`. – dokgu Jul 24 '18 at 18:13
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Taplar Jul 24 '18 at 18:13
  • @uom-pgregorio it prints ```page_content=%3C!DOCTYPE%20html%3E%0D%0A%3Chtml%3E%0D%0A%3Chead%3E%0D%0A%3C%2Fhead%3E%0D%0A%3Cbody%3E%0D%0A%3Cp%3Efor%2086%3C%2Fp%3E%0D%0A%3C%2Fbody%3E%0D%0A%3C%2Fhtml%3E&panel_type=2&page_id=&halfLeftText=%3C!DOCTYPE%20html%3E%0D%0A%3Chtml%3E%0D%0A%3Chead%3E%0D%0A%3C%2Fhead%3E%0D%0A%3Cbody%3E%0D%0A%3Cp%3Efor%2086%3C%2Fp%3E%0D%0A%3C%2Fbody%3E%0D%0A%3C%2Fhtml%3E[object HTMLInputElement]``` – Geoff_S Jul 24 '18 at 18:15
  • To clarify, all other data is correct. It's just this returned ID that i'm having problems with – Geoff_S Jul 24 '18 at 18:16
  • Is that serialized string what you were expecting or no? – dokgu Jul 24 '18 at 18:17
  • I don't understand that `#pageForm` is being submitted on `#submitForm` click but `#form-data` is being submitted right on `$(document).ready()`. How can `#pageForm` be sent before `#form-data`? And from what I understand the script depends alot on `#pageForm` being sent first.. – Lou Jul 24 '18 at 18:19
  • Well, it's a little bit obscure because this is returning tinyMCE data which has html formatting, but panel_type=2 is right, and after that it should have page_id=85 but it's empty – Geoff_S Jul 24 '18 at 18:19
  • @lou that's correct, it does depend on page form being sent first – Geoff_S Jul 24 '18 at 18:19
  • Then `#form-data` should most likely be submitted in the first ajax callback – Lou Jul 24 '18 at 18:20
  • No I need the first ajax call to happen first in order to get the page ID. Are you saying I should remove document.ready from the 2nd call? – Geoff_S Jul 24 '18 at 18:20
  • I'm not used to AJAX so I'm sure I'm over complicating it but If I have a general idea of where it's going wrong then I can refactor – Geoff_S Jul 24 '18 at 18:21
  • The second call shouldn't be launched in document ready.. It must be launched somewhere after the first ajax call is done. So, if nothing needs to be done between the two calls, do it right in the first ajax callback.. – Lou Jul 24 '18 at 18:21
  • @Lou just to clarify, the first call (#submitForm) happens in a required modal form on page load. Once complete, It inserts the page record and gets the ID. Then the user puts content into one of the text areas and hits another save button which makes the 2nd call. Can you show what you mean? – Geoff_S Jul 24 '18 at 18:23
  • also @Lou if i add ```var string = $('#form-data').serialize() + '&page_id=' + page_id;``` for the 2nd call, it gives me the error and puts [objectHTMLInputElement] as the page_id – Geoff_S Jul 24 '18 at 18:29
  • Ok, I understand now.. Otherwise, with the code provided as it is in your post ajax1 and ajax2 aren't in the same scope, they're both in their very own `$(document).ready(function(){ })`. `var page_id` is declared in the first ajax call scope, therefore not available in the second one. Can you declare `var page_id` up of `$(document).ready()`, in the global scope? – Lou Jul 24 '18 at 18:32
  • @uom-pgregorio I don't know if you saw my comment above, but the page_id of that serialized string is the only thing missing. SHould I use serializeArray – Geoff_S Jul 24 '18 at 18:32
  • @Lou trying that, I think it may fix it – Geoff_S Jul 24 '18 at 18:34
  • @Lou thank you that got it! I have a lot to learn still with AJAX. If you want to make it into an answer I'll gladly accept it – Geoff_S Jul 24 '18 at 18:38
  • @Lou I had a quick question as response to your answer, just to see if this would change the formatting – Geoff_S Jul 24 '18 at 19:00

1 Answers1

2

As shown in your code

<script>
    $(document).ready(function(){
        var page_id = 123;
    });
</script>
<script>
    $(document).ready(function(){
        console.log(page_id);
    });
</script>

If you run this, you will get an error "page_id" is not defined.
It gives such an error because page_id in the second $(document).ready callback is not in the same scope as where it has been declared.

Now for example :

<script>
    var page_id = 123;
    $(document).ready(function(){
        console.log(page_id);
    });
</script>
<script>
    $(document).ready(function(){
        console.log(page_id);
    });
</script>

No errors and 123 gets logged twice in the console. This is because page_id has been moved in the global scope. In JavaScript, parents variables are available to children, as long as they don't get overwritten by a declaration such as :

function test(){var page_id = 456; console.log(page_id);}

Which would log the function page_id value instead of the one in the parent scope.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Lou
  • 866
  • 5
  • 14
  • Thank you, it makes much more sense now! – Geoff_S Jul 24 '18 at 18:44
  • one quick question: If I made another call on a button click calling a different file but all I wanted to do was send that same page_id, would I format it differently? – Geoff_S Jul 24 '18 at 18:57
  • 1
    like this: ```$(document).ready(function(){ $("#setActivePage").on("click", function(e){ var string = page_id; // AJAX Code To Submit Form. $.ajax({ type: "POST", url: "savePage.php", data: string, cache: false, success: function(response){ console.log(JSON.stringify(response)); } }); ``` – Geoff_S Jul 24 '18 at 18:58
  • That got it actually, sorry – Geoff_S Jul 24 '18 at 19:02