1

I'm wondering how to reference specific variables in my jquery.ajax() success function.

My php code on addit.php

if ($_POST) {
    $user_id = $_SESSION['user_id'];
    $filename = $_SESSION['filename'];
    $quote = $_POST['quote'];

    $query = "INSERT INTO  `submissions` (
         `id` ,
         `user_id`,
        `quote` ,
        `filename` ,
        `date_added` ,
        `uploaded_ip`
        )
    VALUES (
    NULL , '{$user_id}',  '{$quote}',  '{$filename}',  NOW(), '{$_SERVER['REMOTE_ADDR']}')
    ";

    $db = DbConnector::getInstance();
    $db->insert($query);

    // remove funky characters from the quote
    $cleanRemove = preg_replace("/[^a-zA-Z0-9\s]/", "", $quote);

    // replace any whitespace with hyphens
    $cleanQuote = str_ireplace(" ", "-", $cleanRemove);

    // get the id of the last row inserted for the url
    $lastInsertId = mysql_insert_id();

  $returnUrl = array ("lastId"=>$lastInsertId, "cleanQuote"=>$cleanQuote);
  echo json_encode($returnUrl);
  }

My jQuery code:

        $.ajax({
            type: "POST",
            url: "addit.php",
            data: ({
                // this variable is declared above this function and passes in fine
                quote: quote
            }),
            success: function(msg){
                alert(msg);
            }
        });

Returns in the alert:

{"lastId":91,"cleanQuote":"quote-test-for-stack-overflow"}

How can I now reference that in the success function? I was trying something like this, but it didn't work (returns "undefined" in the alert):

        $.ajax({
            type: "POST",
            url: "addit.php",
            data: ({
                // this variable is declared above this function and passes in fine
                quote: quote
            }),
            success: function(data){
                alert(data.lastId,data.cleanQuote);
            }
        });

2 Answers 2

3

It seems like the response JSON isn't being parsed into an object, which is why the alert() displays the entire string (otherwise you'd see [object Object]). You could parse it on your own but a better solution might be to do one (or both) of the following:

  1. Add dataType = "json" to the call to ajax() to tell jQuery that you're expecting JSON as the response; jQuery will then parse the result and give you a data object that you can work with and not just a string. Also, note that alert() only accepts one argument, all subsequent ones will simply be ignored.

  2. Update your PHP to respond with the correct content type header('Content-type: application/json'); - this will allow jQuery to automagically figure out that the response is JSON and it will parse it for you, without needing a dataType value. This will also make it easier for other consumers since you'll be explicitly specifying the data type.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Got it working. Thanks.. the alert was just for debugging. I'm actually using both variables to construct a URL to redirect the user to, and it works perfectly. Thanks again.
@bob_cobb Great, glad to be of help :)
0

I usually use the following to process the returned json object:

data = $.parseJSON(data);

Then data.lastID should return the value you expect for lastID.

Comments

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.