4

So I'm still a newbie when it comes to javascript and php. I am having this issue:

from javascript, I scan a package's barcode using a barcode reader. I send this to an PHP file using ajax, Which builds an object, and needs to return it to my javascript code.

I'm doing this:

function LoadPackage(ScannedCode) {
    var res;

    console.time("Load package " + ScannedCode);
    $.ajax({
        type: "POST",
        url: "ajax/3gmodule_inventory_ajax/getPackage.php",
        data: "packageSerial=" + ScannedCode,
        cache: false,
        async: false //inline operation, cannot keep processing during the execution of the AJAX
    }).success(function(result) {
        res = $.parseJSON(result);
    });

    console.timeEnd("Load package " + ScannedCode);

    return res;
}

The php file:

    <?php
        include_once "../../init.php";

        $packageSerial = $_POST["packageSerial"];

        $package = tbProductPackage::getInstanceByPackageSerial($packageSerial, $db);
        return json_encode($package);
// edit: first part of the problem was here, I was supposed to ECHO here. not RETURN.
    ?> 

I am 100% certain my object gets built properly. I did do a var_dump of my $package object, and everything is fine with it. However, when trying to get it back to javascript, I tried a bunch of different things, nothing works.

The $.parseJSON(result); statement seems to be giving me this error:

Uncaught SyntaxError: Unexpected end of JSON input

I also tried to use serialize(), but I get an error message:

Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDO instances'

Basically, My database is in my object, I'm guessing I can't serialize it...

What am I doing wrong here?

Thank you

Mathieu Turcotte
  • 344
  • 2
  • 14
  • What is the data type of your `$package` object? – bassxzero Nov 18 '16 at 18:41
  • 1
    First, there is no such thing as an "ajax file". That's just a PHP file that you happen to be calling using ajax. Second, whatever your `getInstanceByPackageSerial()` function is returning either isn't what you think it is, or the way you're trying to do this isn't the right way. It would be helpful to know what your end objective is here. What do you end up trying to do with `res` in the javascript code? Third, you are using `async: false` in your ajax setup. This is generally not considered a good thing to do. – Patrick Q Nov 18 '16 at 18:44
  • Instead of use return, have you tried "die(json_encode($package));" ? – Vítor Oliveira Nov 18 '16 at 18:44
  • In the `.success` function, why don't you log the `result` to see what the actual return object is. Whatever PHP is returning is not correctly formatted for JSON. – TheValyreanGroup Nov 18 '16 at 18:46
  • bass: the type is tbProductPackage. Is a custom class. Patrick: I'm sorry I used the wrong term. However, my getInstanceByPackageSerial() has been touroughly tested, and returns exactly what it should return: an instance of the tbProductPackage class. I am well aware I'm doing something the wrong way here, hence the question! ;) – Mathieu Turcotte Nov 18 '16 at 18:46
  • "Basically, My database is in my object, I'm guessing I can't serialize it..." Just return the data you need; why would you want to pass data related to your DB connection object back to a client-side script? I don't think your "custom class" is as air-tight as you think it is – WillardSolutions Nov 18 '16 at 18:48
  • TheValyreanGroup: I did log it. empty string basically. However, I am 100% positive the PHP returns something, again, I did a var_dump() of it and I'm getting my object. Not going to paste it here, it's a pretty darn big object lol. But I do get it. Once I get in javascript though... nothing... I don't get it... – Mathieu Turcotte Nov 18 '16 at 18:50
  • PeanutButter: I don't know what you mean about my class being air-tight, but basically my object has a bunch of properties, and it has an array of parts in it as well, and I need all of that back in my JS. Each one of my parts are from another class, and they basically all have the DB as well. You are right I don't really want my DB stuff back tough, it would actually be pretty bad to expose that... How can I do this then? I need to return my package, and all of the items in it. I just don'T need the db stuff. The rest is all needed... – Mathieu Turcotte Nov 18 '16 at 18:53

3 Answers3

7

In getPackage.php page :

echo json_encode($package);

not use return

In Jquery should be :

data: {packageSerial:ScannedCode},

After success not need $.parseJSON( because getPackage.php already retrieve json encode

so, is should be :

}).success(function(result) {
    res = result
});

also add dataType: 'json', after data: {packageSerial:ScannedCode},

So, Final correction code is :

Jquery :

function LoadPackage(ScannedCode) {
    var res;

    console.time("Load package " + ScannedCode);

    $.ajax({
        context: this,
        type: "POST",
        url: "ajax/3gmodule_inventory_ajax/getPackage.php",
        data: {packageSerial:ScannedCode},
        dataType: 'json',
    }).success(function(result) {
        res = result;
    });

    console.timeEnd("Load package " + ScannedCode);

    return res;
}

PHP :

<?php
    include_once "../../init.php";

    $packageSerial = $_POST["packageSerial"];

    $package = tbProductPackage::getInstanceByPackageSerial($packageSerial, $db);
    echo json_encode($package);
?>
Razib Al Mamun
  • 2,663
  • 1
  • 16
  • 24
  • mhhh. I'm going to try it but you are so right about the echo... I have no clue why I'm trying to do a return... again. I'm a n00b at php and javascript lol. I got my old .net thinking again lol. I'll try to put an echo instead and see if that helps. It should. The only thing though, like we discussed in the question intself... I am realizing I may not want to return the whole thing. I have the DB info in the object, and I'm worried I'll expose logins and stuff. I'll try it first and check the data that comes out of it, but I may have to construct something before "echoing" it in PHP... – Mathieu Turcotte Nov 18 '16 at 18:58
  • well it kinda... didn't really... work... I did echo json_encode($package);, and I basically receive only { } in javascript... I just don'T get it... In PHP, I have the entire object... but it won'T go trough to javascript... – Mathieu Turcotte Nov 18 '16 at 19:08
  • try to run `getPackage.php` directly not help jquery just for test. and let me know can you get any data? – Razib Al Mamun Nov 18 '16 at 19:12
  • I'm on to something. I echoed: echo json_encode((array) $package); The cast to array seems to have helped. Now the problem is that the array of parts that is inside of my object gets out as { } { } { }... I'll have to find a way to convert those to arrays aswell... The good news thogh: my object does not include the login informations like I feared. Or rather... it tried, but it came out as { } as well haha – Mathieu Turcotte Nov 18 '16 at 19:15
  • @MathieuTurcotte You may be interested in [this answer](http://stackoverflow.com/a/4697671) to a similar question to the problem you seem to be encountering now. – Patrick Q Nov 18 '16 at 19:23
  • If you explain why the OP should use `echo` (or `print`) then I might consider giving your answer an upvote... – Sᴀᴍ Onᴇᴌᴀ Nov 18 '16 at 19:24
  • I don'T even think that need more details, this is simply how using AJAX works lol. php isn't running a function that can return something to JS... It's building a webpage just like any regular php, but it'S "shown" to JS instead of being shown to the user. You can then analyse it with JS and do whatever you need with it. – Mathieu Turcotte Nov 18 '16 at 19:39
  • Now, in my case, I want to build a table containing the parts in my package. I COULD build this table inside of my php, just like any regular table, and send that to JS. I could then simply set that as the innerhtml of my div. The thing is I want php to give me the package itself, so that I can reuse that php file for other purposes! I like objects XD (again, thats my .net experience talking. I'm mad for objects lol. I may be taking this too far here tough...) – Mathieu Turcotte Nov 18 '16 at 19:39
  • Patrick, I did read the question you linked, it may just be my brain being tired (it IS friday afternoon, and we are encouraged to have a pint of beer... or two... at lunch on fridays here XD ), but I can't really wrap my head around what I should do with that answer! I can see the problem was similar, but I can't really understand how to apply it to the current situation :( – Mathieu Turcotte Nov 18 '16 at 19:48
  • well, I ended up generating my table in php. Screw that, this was taking waaaay too long! I build the table in php, sent it to js, and used js to put it inside my div. simple as that. Not 100% happy with it, but it works. weekend is here in 5 minutes! hurray! XD – Mathieu Turcotte Nov 18 '16 at 20:51
0

Ajax expects the JSON inside the request body.

Use

die(json_encode($SOME_ARRAY_OR_OBJECT));

not "return" json_encode($SOME_ARRAY_OR_OBJECT)

Vítor Oliveira
  • 1,851
  • 18
  • 23
-1

I don't know how your database is done, but as a first step, you could make a SELECT query and fetch it as an array. Then, json_encode would work without problem. Something along the lines of:

$vec = array();
$query="SELECT * From YourTable
                    WHERE 1";

$result= mysql_query($query) or die(mysql_error() . $query)

while ($r=mysql_fetch_array($result)) {
   $vec [] = $r;
}

$toreturn=json_encode($vec );
Syl OR
  • 117
  • 1
  • 10
  • 1
    Never use `mysql_` extensions. Also, this answer really misses the point of the question and makes a lot of assumptions about OP's use-case. – WillardSolutions Nov 18 '16 at 18:51
  • I've done plenty of that in other circumstaces and I can get it to work. But I'm in a oop web application. I go through objects whenever I can. In some cases I do return stuff straight from a query, but that doesn't cut it here. Still, thanks for trying to help – Mathieu Turcotte Nov 18 '16 at 19:01