0

I am very new to AJAX and PHP and am currently working on a small website where I initialize php objects as session variables. The functions and objects are all workable in php and compiled with SWIG. When I try to access these variables after calling AJAX, the integer that I send over works well. However, the object that I send over gets set to 0. Below is my code, any advice or help is greatly appreciated. Thank you!

Below is the code that displays the website: index.php

<?php
session_start();
$_SESSION['w_id'] = 1;
$_SESSION['wordSet'] = init_WordSet(2234);

?>

<html>
        <head>   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><head>

        <body>
                <form method="get" class="ajax">
                        <input type="text" name="w_str">
                        <input type="submit">
                </form>
                <script>
                        $('form.ajax').on('submit', function(e){
                                e.preventDefault();
                                //Issue: How to get the input from php?
                                $.ajax({
                                        type: "GET",
                                        url: 'includes/functions.php',
                                        data: ({w_str: 'data'}),
                                        success: function(result){
                                                alert(result);
                                        }

                                });

                        });
                </script>




        </body>


</html>

Below is the php code that Ajax calls

<?php

        session_start();
        echo $_SESSION['w_id'] . ' ' . $_SESSION['wordSet'];
?>

The code for initializing the word set

struct WordSet* init_WordSet(int totalWords){
    //the total number of word blocks
    int arrLength = ceil((double)totalWords / (double)(sizeof(unsigned long) * NUM_BYTES));

    //the hash set that contains whether all words have been, or have not been used 
    struct WordSet *wordSet = malloc(sizeof(struct WordSet));
    wordSet->words = calloc(arrLength, sizeof(unsigned long)); 
    int i; 
    for(i = 0; i < arrLength; i++){
        //setting all the words to be unused
        wordSet->words[i] = 0; 
    }
    wordSet->totalWords = totalWords; 
    return wordSet; 
    
}```
  • Just updated it, it's C. The php should be outputting "Resource ID #n" in the php code, it works perfectly in the index.php script, however, in the functions.php it outputs as 0. – Jordan Driscoll Apr 29 '22 at 02:12
  • You have not cancelled the submit button default action, so this will cause a GET request that reloads the current page, in addition to the AJAX request. I am guessing your problem most likely lies in that somehow. Add a parameter to receive the event object to your callback function (`function(e)`), and then inside call `e.preventDefault();`, before you make your AJAX request - does that change anything? – CBroe Apr 29 '22 at 08:53
  • 1
    @CBroe Thanks for the feedback! I just added that in, and edited the code up above. I also tried changing the submit to a button and then having the ajax on run on click. Unfortunately it did not seem like either of them worked. Let me know if what I did looks correct, or if there's something I'm missing. Thank you! – Jordan Driscoll Apr 29 '22 at 16:42
  • In your __includes/functions.php__ file, are you trying to concatenate an Integer, an empty string, and an object? `PHP Fatal error: Uncaught Error: Object of class ... could not be converted to string`. – bloodyKnuckles Apr 29 '22 at 17:39
  • @KenLee When I echo the init_WordSet(2234), it outputs Resource ID #n, n usually being 1-3. That's true in both index.php and the functions.php. – Jordan Driscoll Apr 29 '22 at 18:03
  • @bloodyKnuckles when I only have echo $_SESSION['wordSet'] it outputs 0 in the functions.php file, however it outputs Resource ID #n in the index.php. – Jordan Driscoll Apr 29 '22 at 18:06
  • So you're trying to `echo` an object: `PHP Fatal error: Uncaught Error: Object of class ... could not be converted to string`. [echo — Output one or more strings](https://www.php.net/manual/en/function.echo.php) – bloodyKnuckles Apr 29 '22 at 18:14
  • Change `$_SESSION['wordSet'] = init_WordSet(2234);` to `$_SESSION['wordSet'] = print_r(init_WordSet(2234), true);` and retry please – Ken Lee Apr 29 '22 at 18:28
  • @KenLee I just gave that a try, it now successfully outputs the String Resource ID #n, but unfortunately it looks like the actual functionality crashes, so if I try to use the function markUsed_WordSet(0, $_SESSION['wordSet']), it works if it's not a string index.php, but when I use print_r it looks like it doesn't work. – Jordan Driscoll Apr 29 '22 at 18:40
  • @bloodyKnuckles Concatenation doesn't seem to be the issue. The issue seems to be that somehow the resource id gets lost when I use Ajax. Where $_SESSION['wordSet'] outputs Resource ID #n properly in the index.php, when I do a get request to functions.php and output it, it outputs 0. – Jordan Driscoll Apr 29 '22 at 18:42
  • 1
    In your original question, you want to echo the object (after passing thru the pages by SESSION, in that case we use print_r to force casting the object to a string. Now if your ultimate goal is to pass the object and then "use it later on", please serialize it and then base64encode it (and in the destination , base64decode it and then unserialize it). For reference pls see [this](https://stackoverflow.com/questions/1442177/storing-objects-in-php-session) – Ken Lee Apr 29 '22 at 18:48
  • You can't echo an object from the server to the client. If you wish to send your PHP object, which only exists on the server, to the client and use it there you'll need to convert it to a string for delivery to the client over HTTP. Then use Javascript on the client to convert the string to a format Javascript can use, likely JSON. – bloodyKnuckles Apr 29 '22 at 20:04
  • @bloodyKnuckles Do you have any advice on how I might be able to keep it entirely on the server? – Jordan Driscoll Apr 29 '22 at 21:55
  • @KenLee When I try to serialize, and then immediately serialize the object, it serializes it to i:0, and then unserializes it to just 0. I don't know if this is a SWIG issue, or if I need to convert it to a JSON object. – Jordan Driscoll Apr 29 '22 at 21:56
  • "...how...to keep it entirely on the server?" Don't use Ajax (XHR). Submit the __index.php__ form to itself. `
    `. Do you need to display data from the `wordSet` object on the __index.php__ page? Or some other page? Do you simply need to pop up an `alert` (using Javascript) containing data from your PHP `wordSet` object?
    – bloodyKnuckles Apr 30 '22 at 00:22
  • @bloodyKnuckles My goal is to be able to have access to the object such that I can use it in functions. How might I use the form to be able to call a particular php method that exists on the index page? Thank you – Jordan Driscoll Apr 30 '22 at 01:09
  • "My goal is to be able to have access to the object such that I can use it in functions." ...is too broad to determine a solution. What is an example state of the object, and what is an example function you like to use it in? Be specific, and add them to your question. – bloodyKnuckles Apr 30 '22 at 02:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244348/discussion-between-bloodyknuckles-and-jordan-driscoll). – bloodyKnuckles Apr 30 '22 at 02:18

0 Answers0