0

I have a front end editor set up using AJAX to edit posts in Wordpress. Everything was going good, my form submits to a php file which successully updates the database and then uses the following function to create a response:

  function generate_response($action, $message = '', $details = '' ){
    $response = array(
        "action"  => $action,
        "message" => $message,
        "details" => $details
        );

    echo json_encode($response, JSON_FORCE_OBJECT);
}

However, the response does not appear to be encoded properly, When I log my jsonResponse return in JS I'm getting this:

Object {action: "updated", message: "Succes (no changes detected).", details: ""}

Which I'm pretty sure is malforemd JSON because action, message, and details are not double-quoted, right?

I try to parse the response and all I get is null:

  response = jQuery.parseJSON(jsonResponse);
  console.log(response); //returns null

What am I doing wrong here? Am I correct and the response is not fomratted properly and if so, how would I fix it?

0

2 Answers 2

1

When you log the result from ajax, you get:

Object {action: "updated", message: "Succes (no changes detected).", details: ""}

That's already an object, not a JSON string, which means you probably set dataType: 'JSON' in your ajax call, and JSON is parsed automagically by jQuery, parsing it again just causes errors.

All you need to do is use response, no parsing needed :

var action = response.action;
Sign up to request clarification or add additional context in comments.

1 Comment

I ran into some different issues which I'll have to figure out before I can know if you're answer was right, although I'm pretty sure it is.
0

@adeneo So when I am running a query to load top 5 posts and then whaterver results I am getting they would be encoded to json.The output I am getting would be a object and not a JSON string right?

Yesterday spent few hours doing stringify- just to convert it to json assuming myoutput was a json string.

1 Comment

If whatever is returned from the server is properly encoded, like with json_encode, and dataType is set to JSON in jQuery's ajax function, the result will be a javascript object ready for use, as jQuery does the JSON.parse part internally for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.