March 7, 2013

I need to pullback data from a jquery ajax post and break the array out to seperate outputs

Question by Ezos

I need to get the array and instead of just pushing the data into an html div – get back the php variable.

My $.ajax post —-

  <script type="text/javascript">
    $(function() {

        $("#login").click(function() {
            var theName = $.trim($("#username").val());

            if(theName.length > 0)
            {
                $.ajax({
                  type: "POST",
                  url: "callajaxdemo.php",
                  data: ({name: theName}),
                  cache: false,
                  dataType: "text",
                  success: onSuccess
                });
            }
        });

        $("#resultLog").ajaxError(function(event, request, settings, exception) {
          $("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
        });

        function onSuccess(data)
        {
            $("#resultLog").html("Result: " + data);
            //$.mobile.changePage('stats.html', { transition: 'slideup'}, true, true);
        }

    });
</script>'

My PHP file is —–

<?php
 $username = $_POST['username']; 
 $password = $_POST['password'];

$host = 'https://api.qpme.com/api/accounts/me';

$process = curl_init($host);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($process);

$content = json_decode($return);

/*
echo "<pre>";
print_r($content);
echo "</pre>";
*/

print $content->email . "<br>";
print "<h3>" . "Welcome" . ' ' . $content->firstName . ' ' . $content->lastName . '!' . "<h3>";

?>'

The goal would be to get back the array and then post certain parts of it to different jquery mobile pages.

Answer by Starx

You can send JSON data back to AJAX request.

Change your arrays to JSON like this:

echo json_encode($yourData);

To read this, you have to setup your script to accept JSON data

        $.ajax({
          type: "POST",
          url: "callajaxdemo.php",
          data: ({name: theName}),
          cache: false,
          dataType: "json", // <--- Here
          success: onSuccess
        });

Then you can access the properties as JavaScript Object.

    function onSuccess(data)
    {
        // access using data.item1
        //           or data.item2 how you prepare your array
    }

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!