guyfromfl Posted October 20, 2010 Share Posted October 20, 2010 I am trying to learn AJax, and like probably most of you doing it alone, through trial & error and google. What I have done is write a script that takes a stock number and references a MySQL database to get the description and returns the db's unique id, description and msrp. My company, in its genius, used the same stock number for multiple items, so say stock number 510 might have 2+ rows returned from the database. I currently create a string in php with the elements of the result appended to each other seperated by #### echo it back, then .split() in js back into an array. I then count the elements and divide by 3 (how many fields in the row)... Is there a better way to return the data or is making a string then splitting it back into an array the best way to do this? I will get to the ajax function in jQuery but I want to know whats going on first... Any suggestions would be most helpful! Thanks Quote Link to comment Share on other sites More sharing options...
trq Posted October 21, 2010 Share Posted October 21, 2010 Is there a better way to return the data or is making a string then splitting it back into an array the best way to do this? I always return json objects, especially when there are multiple results. There just VERY easy to work with. So, your jQuery might be something like..... $.ajax({ url: 'query.php', data: {id:10}, datatype: json success: function(results) { if (results.msg == 'success') { for (var i in data) { $('#content').append( 'id = ' + results.data[i].id + ', description = ' + results.data[i].description + ', msrp = ' + results.data[i].msrp ); } } else { $('#content').append(results.msg); } } }); And your php.... if (isset($_GET['id'])) { $sql = "SELECT id, description, msrp FROM tbl WHERE id = '{$_GET['id']}'"; $return = array(); if ($result = mysql_query($sql)) { if (mysql_num_rows($result)) { $return['msg'] = 'success'; while ($row = mysql_fetch_assoc($result)) { $return['data'][] = $row; } } else { $return['msg'] = 'No results found'; } else { $return['msg'] = 'Query failed'; } header("Content-type: application/json"); echo json_encode($result); } Quote Link to comment Share on other sites More sharing options...
guyfromfl Posted October 21, 2010 Author Share Posted October 21, 2010 Wow. That looks very good. I knew there had to be a better way to handle the data than just appending a string to a string then splitting it back. I will have to try it. Thanks!!! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.