AJAX json_encode PHP file

Asked

Viewed 190 times

2

Good morning. I’m trying to build a form where the input is validated by a PHP file via an AJAX call, but I’m having problems with how I receive the "date" in callback.

This is my call via AJAX:

$('#submit').click(function(e){
    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();
    var msg_subject = $("#msg_subject").val();
    var message = $("#message").val();

    $.ajax({
        type: "POST",
        url: "process_test.php",
        dataType: "json",
        data: {name:name, email:email, msg_subject:msg_subject},
        success : function(data){
            if (data.code == "200"){
                alert("Success: " +data.msg);
            } else {
              alert( data);
            }
        }
    });

  });

And this is the PHP file where the validation is made:

<?php

$errors = array();


/* NAME */
if (empty($_POST["name"])) {
    $errors["name"] = "The name is required";
} else {
    $name = $_POST["name"];
}

/* EMAIL */
if (empty($_POST["email"])) {
    $errors["email"]= "The email is required";
} else if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    $errors["email"] = "The email contains invalid characters";
}else {
    $email = $_POST["email"];
}

/* MSG SUBJECT */
if (empty($_POST["msg_subject"])) {
    $errors["subject"]= "Subject is required";
} else {
    $msg_subject = $_POST["msg_subject"];
}


if(empty($errorMSG)){
    $msg = "Name: ".$name.", Email: ".$email.", Subject: ".$msg_subject.", Message:".$message;
    echo json_encode(['code'=>200, 'msg'=>$msg]);
    exit;
}

    echo json_encode(['code'=>400, $errors);

?>

The goal was to use php’s "json_encode" method to return the answer in object format because I need to access the positions to format the form fields that have an error, something like this example:

$obj = {
    "name":"Jose", 
    "email":"[email protected]",
    "assunto":"bla bla bla"
    }

However, despite using json_encode, the answer is always in "string" format. I can’t figure out what I’m doing wrong. I appreciate all your help

EDIT I changed the code in AJAX to the following:

 $.ajax({
        type: "POST",
        url: "process_test.php",
        dataType: "json",
        data: {name:name, email:email, msg_subject:msg_subject},
        success : function(data){
            if (data.code == "200"){
                console_log(data.msg.name)
                alert("Success: " +data.msg.name);
            } else {
              console_log(data.err.name)
            }
        }
    });

but I don’t have any console output or error. I’m going crazy

EDIT Output result with empty form:

ajax.php:99 
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (a)
always: ƒ ()
complete: ƒ ()
done: ƒ ()
error: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (a)
overrideMimeType: ƒ (a)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (a)
readyState: 4
responseText: "<br />↵<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>↵<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: name in C:\wamp64\www\Test\process_test.php on line <i>31</i></th></tr>↵<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>↵<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>↵<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0002</td><td bgcolor='#eeeeec' align='right'>404648</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\Test\process_test.php' bgcolor='#eeeeec'>...\process_test.php<b>:</b>0</td></tr>↵</table></font>↵<br />↵<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>↵<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: email in C:\wamp64\www\Test\process_test.php on line <i>31</i></th></tr>↵<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>↵<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>↵<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0002</td><td bgcolor='#eeeeec' align='right'>404648</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\Test\process_test.php' bgcolor='#eeeeec'>...\process_test.php<b>:</b>0</td></tr>↵</table></font>↵<br />↵<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>↵<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: msg_subject in C:\wamp64\www\Test\process_test.php on line <i>31</i></th></tr>↵<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>↵<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>↵<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0002</td><td bgcolor='#eeeeec' align='right'>404648</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\Test\process_test.php' bgcolor='#eeeeec'>...\process_test.php<b>:</b>0</td></tr>↵</table></font>↵{"code":200,"msg":{"name":null,"email":null,"subject":null}}"
setRequestHeader: ƒ (a,b)
state: ƒ ()
status: 200
statusCode: ƒ (a)
statusText: "OK"
success: ƒ ()
then: ƒ ()
__proto__: Object
  • 1

    But JSON is a string. jQuery’s AJAX already identifies the request response and "parsea" automatically. The end, what’s wrong with your code?

  • 1

    Boas Lipespry. How do I access for example the value of the "name"? If it were an object could do for example obj.name. That is my question.

  • 1

    Ahh yes. Now I get it. It turns out that in the variable $msg you have fulfilled the values. You should make a array associative and Javascript would receive as an object, as it already does with the rest of the answer. By the way, Mr @Weessmith already formulated an answer solving this! ;)

1 answer

2

I organized so that you can work with all the data that will be returned by PHP, transforming the variable $msg in a array() with the content:

if(empty($errorMSG)){
    $msg = array("name"=>$name,"email"=>$email,"subject"=>$msg_subject,"message"=>$message);
    echo json_encode(['code'=>200, 'msg'=>$msg]);
}else{
    echo json_encode(['code'=>400, $errors]);
}

In the callback of $.ajax() the parenchyma data will be that json_encode() of PHP:

success : function(data){
    if (data.code == 200){
        alert("Success: " +data.msg.name);
        //ou uma forma de ver todo conteúdo do retorno é
        console.log(data);
        //ou apenas o conteúdo do elemento msg
        console.log(data.msg);
    } else {
        console.log(data);
    }
},
error:function(e){
    console.log(e);
}

Recalling that the alert() will not show a returned object, it will only appear [obj Obj].

  • 1

    Hello Wees. First of all thank you for the help. So how do I get the values of this object into the AJAX callback? for example if I want to print the array value['name']?

  • 1

    @Sergioneves has already put this in the answer: data.msg.name. Read the code more carefully. Oo

  • 1

    just like I put it in there alert() you will access the parameter data, that will contain every return, from there you use the keys of the PHP, for example: data.code or data.msg.name

  • 1

    Because that’s exactly the problem. It is that I had already tried this solution, but I still have no Output on the side of the form, is well filled or with errors. Won’t even log me to the console

  • edited the answer and added the error in the $.ajax, checks in the console which problem is occurring

  • I edited my question with the output output when submitting the completely empty form. You can see that by sending the empty form it responds with {"code":200,"msg":{"name":null,"email":null,"Subject":null}} which makes no sense. In PHP file my error array should be filled in if I submit the form without data

  • Even if you fill in the form correctly, AJAX does not show Alert

  • look at the error Notice: Undefined variable: name in C:\wamp64\www\Test\process_test.php on line 31

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.