1

Background

Okay, I have a page which displays simple information on rows from a mysql database. For example, the table has 7 columns, but only #'s 1, 3 & 4 are displayed on the page. On the right side of the row is a href link to open a modal window, and I am attempting to display all the rows, in a nicely formatted window with html/css/etc...

After spending about 4 hours in tutorials on this, the closest thing I have come up with is the code base below, which does the job of passing the "id" to the json script, (almost) properly pulls the information, puts it in a single object line, and passes it back into my html/php page to be read into the modal window.

I am politely asking for help to convert my codebase so that it transfers all objects individually instead of one gigantic line of php to echo into html (arse-backwards). I am rather new to JSON/AJAX/jquery, but can navigate and work with the html/css/php once I am able to figure this out.

My apologies if the code examples are a little muffled and poor in syntax, I have spent hours trying to get this work as it is supposed to.

PHP Page With The AJAX

$('.view_information').click(function(e) { // Button which will activate our modal
            //On Clicking the function, dynamically load the data for the viewing
                  var data_id = $(this).data('id');
                $.ajax({
                    url: 'view_agency_info.php',
                    type: 'POST',
                    data: {id: data_id},
                    dataType: 'json',
                    success: function(data){
                        $('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV
                   //I want to be able to use...
                   //$('.placeholder_name')xxxx
                   //$('.placeholder_accountnumber')etc

                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        $('.view_modal_content').html(''); 
                        alert('Error Loading Information');
                    }
                });

As you can see from the php page, as of right now, the mysql is being pulled into an array, then inserted individually into a single HTML object, then being passed back into PHP to be outputted. How can I convert this code to output more than just one object?

JSON

<?php
$customer_id=$_SESSION['customer']['customer_id'];
$id = (int)$_POST['id'];
$query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row
$result = mysql_query( $query );
//$message = mysql_fetch_assoc( $result ); //expecting just one row

$message=array();
while ($row = mysql_fetch_assoc($result)) {
    $message[]=$row['agency_name'];
    $message[]=$row['account_number'];
    $message[]=$row['phone'];
}


$json = array();
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';



header('Content-Type: application/json');
echo json_encode( $json );
?>

2 Answers 2

1

If I understand this correctly, then I would advise you to change the PHP to generate JSON directly rather than sending back HTML. Something like:

$first = 1;
$json = '[';
while ($row = mysql_fetch_assoc($result)) {
    if ($first == 1) $first = 0; else $json = $json + ',';
    $json = $json.'{';
    $json = $json.'"AgencyName":'.$row['agency_name'];
    $json = $json.', "AccountNumber":'.$row[account_number];
    $json = $json.', "Phone":'.$row[phone];
    $json = $json.'}';
}
$json = $json.']';

I have done this more in MVC and am rusty on PHP syntax, but hopefully this gets the gist across. Then your javascript can parse the results as just JSON. If you have "bad" characters in your data, you may have to html encode some, but the data should be easier to work with as data. You will have to provide template HTML for your modal and then fill it in.

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

3 Comments

Yes! Thank you! but how would I output it inside the actual html page individually and what would I need to change inside the PHP / Ajax page
In the success function for your ajax, you will want to expect that the data parameter is a JSON object. Then you will need to have fields on your modal page that you can fill in. (e.g. AccountNumber) and then $("#AccountNumber").html(data[0].AccountNumber)
Thanks! I've been able to get this particular function to work through a different methodology, but I appreciate the response :)
1

The line: $json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';

only pulls one object from the result "$message[0]" the first elememt of the array. This is why you are only getting one object returned.

edit: you'll need to change:

$message=array();
while ($row = mysql_fetch_assoc($result)) {
    $message[]= ('name'    => $row['agency_name'],
                 'account' => $row['account_number'],
                 'phone'   => $message[]=$row['phone']
                 );
    }
print json_encode($message);  

This will then return a json object that you can parse with js

then in your js:

edit: then add your html in js if thats how you wanna do it

var html; 
$.each(data, function(info) {
   html += "<p><pre><code>id:"+ data_id +".<br>Agency Name: "+ info.name +"<br>Account Number:"+ info.number +"<br>Phone:"+ info.phone +"</code></pre></p><br><br>";
});

$('.view_modal_content').html(html);

??????????????????????????????????????????????????????????????????

are you trying to do:

var divObj = {}; //make sure this is in the correct scope
//anonymous array
$.each(data, function(info) {
   divObj.push("<p><pre><code>id:"+ data_id +".<br>Agency Name: "+ info.name +"<br>Account Number:"+ info.number +"<br>Phone:"+ info.phone +"</code></pre></p><br><br>");
});
//or associative array
$.each(data, function(info) {
   divObj[info.name] ="<p><pre><code>id:"+ data_id +".<br>Agency Name: "+ info.name +"<br>Account Number:"+ info.number +"<br>Phone:"+ info.phone +"</code></pre></p><br><br>";
});

or are you trying to simply update elements of an existing block of code in a div?

9 Comments

Thank you for your response, but this is not what was needed!! I must return more than one object individually, not a single html line.
if you dont want any of the html added in PHP then just return $message and parse that object in javascript
i've updated my answer with how to pass the json object back and manipulate in js
Okay, maybe my question isn't clear. I WILL have a div for the modal window...but for example, to keep code clean.. how can i output like this <div id="modal> <div class="style" id="name"> Name : xyz</div><div class="style" id="address"> Add: xyz</div></div>
|

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.