简体   繁体   中英

Cannot get value of implode() response from php file using ajax (array to string conversion error)

The scenario is here I accept all button click that has ID starts with 'editbtn' like editbtn1/editbtn2 etc; and get only the number to send via ajax to find data id based on the button id (number)

    $(document).ready(function(){
        $('[id^=editbtn]').click( function () {
            noform=this.id.match(/\d+/);
            event.preventDefault();
        
            $.ajax({
                'url': 'visitor_book_crud.php',
                'data': {
                    'request': 'find_data',
                    'data_id': noform
                },
                'type': 'post',
                'dataType': 'html',
                'beforeSend': function () { }
            })
            .done( function (response) {
                console.log(response);
            })
            .fail( function (code, status) {    alert(code+' - '+status);
            })
            .always( function (xhr, status) {   })
        });
    });

And In visitor_book_crud.php

    if ($request=="find_data"){
        $data_id = $_REQUEST['data_id'];

        $mqdata = mysql_query("SELECT * FROM tb_visitorbook WHERE id_vb = '$data_id'") or die (mysql_error());
        $mfadata = mysql_fetch_assoc($mqdata);
        if($mfadata){
            echo implode(",", $mfadata);
        } else {
            echo "failed"; 
        }
    }

I tried to directly send request to visitor_book.crud?request=find_data&data_id=1 and the output is like this, exactly same as what I want to be appeared in ajax response 1,2022-06-29,03:07:30,03:39:39,6,,A_NAME,3,,,SOME_NAME,,1,

But when I press edit button, it says

<br />
<b>Notice</b>:  Array to string conversion in <b>C:\xampp\htdocs\security_editless\visitor_book_crud.php</b> on line <b>48</b><br /> //line 48 is in mysql_query("SELECT......
failed

I searched from many thread but still dont solve my problem, any help would be appreciated

First of all, you should do all the validation before sending the data from JS and also validate the data on the PHP side as well.

However noform = this.id.match(/\d+/); will give your an array. to get the number you'll have to use noform[0] , also make sure you do the validation if any match found or not before using noform[0]

right now you're sending noform as data_id and your PHP is warning about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM