-2

I can't get array data from "response" in my jQuery script. Command "Alert" shows "undefined" instead of data.

        $.ajax({
            type:'post',
            url:'/action/edit.php',
            data:{'user_id':'<?=$user_id;?>','bid': blckID},
            response:'text',
            dataType: 'JSON',
            success: function(response){        
                var title = response.title;
                var content = response.content;
                alert(title);
            }
        
        });

Handler:

$user_id = $_POST['user_id'];
$blckID = $_POST['bid'];

$query = "SELECT title,content FROM uprt_user_blocks WHERE `user_id`={$user_id} AND `id`={$blckID}";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);


$return_arr[] = array("title" => $row['title'],
                    "content" => $row['content']);


// Encoding array in JSON format
echo json_encode($return_arr);
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • And what does `console.log(response)` give you? – freedomn-m Feb 14 '22 at 09:03
  • 1
    { "title": "Второй блок 222", "content": "

    Второй блок 222 Второй блок 222 Второй блок 222 Второй блок 222 Второй блок 222

    " }
    – Mikhail Petrov Feb 14 '22 at 09:59
  • And is that JSON (ie a string) or an object? – freedomn-m Feb 14 '22 at 10:01
  • @MikhailPetrov — No, it doesn't. – Quentin Feb 14 '22 at 10:05
  • `=$user_id;?` Are you trying to access a PHP variable in a JS script tag? Is that even possible? – Relcode Feb 14 '22 at 10:05
  • @Relcode — PHP doesn't care where, in the text file, ` ... ?>` markers are. – Quentin Feb 14 '22 at 10:07
  • @Quentin but unfortunately that's JS/Ajax not PHP. Maybe I've never experienced with it but I know for sure that PHP runs on the server and JS on the client side and that alone provides a problem. It works if you set the user_id value when PHP is running on the server `` and using some identifier to get that value `var user_id = $('.user_id').val()` but to call it directly like he did I doubt it will work. – Relcode Feb 14 '22 at 10:12
  • @connexo — No, it didn't: https://jsbin.com/mahusosaxe/1/edit?html,output – Quentin Feb 14 '22 at 10:12
  • @Relcode — "unfortunately that's JS/Ajax not PHP" — How can you tell it isn't PHP? You can put **any kind of text you like** outside of `` in a PHP program and it will pass it through unaltered. That text is often HTML (and often JavaScript in a ` – Quentin Feb 14 '22 at 10:13
  • @Quentin It is not PHP because PHP does not run $.ajax. That's a JS/JQuery syntax. – Relcode Feb 14 '22 at 10:15
  • 1
    @connexo — The options object passed to `$.ajax` isn't a jqXHR object. The return value of `$.ajax()` is a jqXHR object. – Quentin Feb 14 '22 at 10:15
  • @Relcode — So if I were to write: ` Example

    ` then that wouldn't be PHP because PHP doesn't have a DOCTYPE or any HTML tags in it?
    – Quentin Feb 14 '22 at 10:16
  • @Quentin Yes it wouldn't *automatically* be PHP unless the file has a **.php** extension. You can't use a JS syntax and expect it to be PHP just because you want it to be. But like I've said, maybe I'm inexperienced but I know for sure that JS can't access PHP directly because as I've said PHP runs on the server and JS runs on the client-side. – Relcode Feb 14 '22 at 10:20
  • @Relcode — What makes you think the code the OP provided isn't in a file with a *.php* extension? What makes you think that the JS is *accessing* the PHP? The HTML isn't. The PHP is outputting the HTML. The PHP can output JS too. Or SVG. Or RSS. Or any XML. Or any text. – Quentin Feb 14 '22 at 10:21
  • @Quentin I was answering your question *so if i were to write..:.* . I know that PHP can output anything or even build dynamic HTML but JS can't output or access PHP values directly. Unless they were rendered via HTML when PHP was loading or in localStorage. But you are the experienced one here so I'm sure you know better. – Relcode Feb 14 '22 at 10:25
  • @Relcode — "JS can't output or access PHP values directly" — That isn't what the code is doing. "Unless they were rendered via HTML when PHP was loading" — That **is** what the code is doing (probably, the HTML isn't actually needed as you can output JS directly, but that's relatively uncommon). – Quentin Feb 14 '22 at 10:26
  • @Quentin I am saying if they were rendered via HTML or probably stored in localStorage then the way to access them doesn't involve using PHP identifiers ``. directly into your JS's $.ajax script. Notice this ```'=$user_id;?>'``` the user_id is passed inside single-quotes and that automatically passes =$user_id;?> as a value rather than a PHP variable. That's another miss with the way OP's code is written. – Relcode Feb 14 '22 at 10:31
  • @Quentin I admire your profile by the way. – Relcode Feb 14 '22 at 10:34
  • @Relcode — "I am saying if they were rendered via HTML or probably stored in localStorage " — There is nothing to suggest that localStorage is involved. It's just some PHP outputting some JS embedded in an HTML document. – Quentin Feb 14 '22 at 10:34
  • "user_id is passed inside single-quotes and that automatically passes =$user_id;?> as a value rather than a PHP variable." — No. PHP doesn't care, as I have said several times already, what characters are outside ``. JavaScript string literals must be surrounded by quotes. If the quotes were missing then the generated code might look like `data:{'user_id':userIdASFGH,'bid': blckID},` which would be an error because it would try to treat `userIdASFGH` as a variable name instead of a string. – Quentin Feb 14 '22 at 10:34
  • @Quentin I am giving another scenario where it will be possible to access PHP values directly using $.ajax. I wasn't saying the OP used localStorage. If you say setting a value like this(for example) `$('.user_id').val()` works then I guess I still have a lot to learn because I am certain that it doesn't. – Relcode Feb 14 '22 at 10:37
  • 1
    @Relcode http://sandbox.onlinephpfunctions.com/code/9e561ff44f61058df399430b351590d56353b44f – Quentin Feb 14 '22 at 10:40
  • @Quentin that was helpful. I now realize that I was thinking about this from the point of using an external JS file. – Relcode Feb 14 '22 at 10:45
  • @Relcode — https://pastebin.com/UQtuJmj5 – Quentin Feb 14 '22 at 10:47
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Feb 14 '22 at 14:02

1 Answers1

2

$return_arr[] = means "Add the assignment to the end of the array in $return_arr, creating that array if needed".

The JSON you are sending looks like this:

[
    { title: "something", content: "something" }
]

response is an array containing an object, but you are trying to treat it as the object itself (with no array).


Either:

  • Return an object by saying $return_arr = instead of $return_arr[] =
  • Deal with the array in response (e.g. with a for loop or directly accessing [0]).
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335