-1

I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.

$(document).ready(function () {
    $("#comments_form").on("submit", function(e) {
        e.preventDefault();
        e.stopPropagation();

        $.ajax({
            type: 'POST',
            url: 'process_in.php',
            data: {
                first: $("#firstname").val(), 
                second: $("#lastname").val(), 
                third: $("#mail").val(), 
                fourth: $("#phone").val(), 
                fifth: $("#message").val()
            },
            success: function(result) {                    
                var x = jQuery.parseJSON(result);
                alert(x.f);
            },
        });
    });  
})
<?php
    include ('connection.php');
    if (isset($_REQUEST['first']) && isset($_REQUEST['second']) &&   isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth'])) 
    {
        $firstname = $_REQUEST['first'];
        $lastname = $_REQUEST['second'];
        $email = $_REQUEST['third'];
        $contact = $_REQUEST['fourth'];
        $message = $_REQUEST['fifth'];

        $data = array();
        $data["f"] = xssafe($firstname);
        $data["l"] = xssafe($lastname);
        $data["e"] = xssafe($email);
        $data["c"] = xssafe($contact);
        $data["m"] = xssafe($message);
        echo json_encode($data);
    }

    function xssafe($d)
    {
        $x = filter_var($d, FILTER_SANITIZE_STRING);
        return $x;
    }  
Jason
  • 3,330
  • 1
  • 33
  • 38
  • 1
    Do you have any errors in the console? What is the HTTP status of the response from your server? Is the response text what you expect it to be? Have you debugged this at all, if so please edit your question to add some details. – Rory McCrossan Jan 08 '17 at 14:37
  • 1
    You should add `dataType: 'json'` in your AJAX Call – Thamilhan Jan 08 '17 at 14:39
  • 1
    ...and remove `jQuery.parseJSON(result);` and use `result.f` directly. – M. Eriksson Jan 08 '17 at 14:40
  • 1
    Btw. I'm guessing that the PHP isn't complete, since you're actually not doing anything other than filter the values, which you already could do in JS? – M. Eriksson Jan 08 '17 at 14:45
  • @Thamilan @MagnusEriksson I added `dataType: 'json'` and removed `jQuery.parseJSON(result);`, but still the responseText is `undefined` and `result.f` is empty. – Abdul Raheem Ghani Jan 08 '17 at 14:53
  • Isn't it `result`? `responseText` will be undefined – Thamilhan Jan 08 '17 at 14:55
  • @MagnusEriksson, You are right. The php is just for input validation to prevent XSS attacks. I used php for the `filter_var()` function. – Abdul Raheem Ghani Jan 08 '17 at 14:55
  • 1
    It seems like an unnecessary overhead to make a ajax call to a PHP-backend just do filter the variables. Here is how you can html-escape the data in js (which should be enough): http://stackoverflow.com/questions/2794137/sanitizing-user-input-before-adding-it-to-the-dom-in-javascript – M. Eriksson Jan 08 '17 at 14:59
  • @Thamilan, I think the problem is with the `filter_var()` function, because when I use `` as firstname, it returns a null value, but when I use `John` instead then It works fine. – Abdul Raheem Ghani Jan 08 '17 at 14:59

1 Answers1

0

A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception. Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.

$.ajax({
    type: 'POST',
    url: 'process_in.php',
    dataType: 'JSON',
    data: {
        first: $("#firstname").val(), 
        second: $("#lastname").val(), 
        third: $("#mail").val(), 
        fourth: $("#phone").val(), 
        fifth: $("#message").val()
    },
    success: function(result) {                    
        console.log(result.f);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        console.log(msg);
    }
});

You can learn how to debug the code and check your error logs

Now lets get to your code, there are many possible cases that you are not getting the value.

It could be your php code or it could be your jquery.

In php to check whether its returning a valid json hit the url in browser like this

http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo

As in your php code you haven't return any value so add an else part for the

    if (isset($_REQUEST['first']) && isset($_REQUEST['second']) &&   isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth'])) 
    {
        $firstname = $_REQUEST['first'];
        $lastname = $_REQUEST['second'];
        $email = $_REQUEST['third'];
        $contact = $_REQUEST['fourth'];
        $message = $_REQUEST['fifth'];

        $data = array();
        $data["f"] = xssafe($firstname);
        $data["l"] = xssafe($lastname);
        $data["e"] = xssafe($email);
        $data["c"] = xssafe($contact);
        $data["m"] = xssafe($message);
        echo json_encode($data);
    } else {
        echo json_encode(['error'=>'Invalid request']);
    }
Aman Rawat
  • 2,625
  • 1
  • 25
  • 40