PHP - Return Value From Ajax Using Json
Hi all btw after the json_encode i added json_last_error_msg and recieved no error message, so its something in the jquery in my understanding <?php if (isset($_POST['productid_typed'])) { $userid=$_POST['productid']; $stid = (DBOracle::getInstance()->get_product_desc($productid)); while ($row = oci_fetch_array($stid, OCI_ASSOC)) { $data=array(); $data['productname']=$row['P_DESC']; oci_free_statement($stid); oci_close($con); } echo json_encode($data); } ?> <html> <head> <meta charset="UTF-8"> <title>Product</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="../../bootstrap-4.5.0-dist/css/bootstrap.min.css" /> <script src="../../bootstrap-4.5.0-dist/js/bootstrap.min.js"></script> </head> and this is the part of the jquery and ajax (the productid_desc is an input box on the page that should be filled automaticaly) <script> $(document).ready(function() { $('#productid').focusout(function() { debugger; var productid=$('input[name=productid]').val(); if (productid!==' ') $.ajax ({ type:"POST", url:"index.php", data: { productid_typed: 1, productid: productid }, datatype:"json" , success:function(data) { $('#productid_desc').val(data.productname); } }) else { alert("Plase enter id"); } }); }); </script>
Similar TutorialsI have the following code and it always says it's a string! How do I make it see it as a json object? Code: [Select] <?php //We'll return a json object from post request if ( !empty( $_POST ) ) { $arr = array ('status'=>1,'message'=>'Some message'); echo json_encode($arr); } else { ?> <input type="button" value="submit" id="submit" /> <script type="text/javascript" src="/scripts/jquery-1.4.2.js"></script> <script> var submit = document.getElementById( "submit" ); submit.onclick = function() { $.post( "test.php", function(data) { /* * This always prints as: * {"status":1,"message":"Some message"} * string * Code: undefined * Message: undefined */ alert( data + "\n" + typeof( data ) + "\nCode: " + data.status + "\nMessage: " + data.message ); } ); } </script> <? } ?> What do I do to make it a json object? I am returning the following through JSON: Code: [Select] $this->view->lead_query=$lead_query->fetchALL(); header('OK', true, 200); header('Content-type: application/json'); echo json_encode($this->view->lead_query); I am getting the results in this format: [{"client_name":"Steve Harris","state":"TX"}] Now if the above output was displayed without the square brackets [] I can populate the values in my form correctly. Is there a way i can return the output without the square brackets? im trying to get this ajax function working but for some reason it runs the error function...I've corresponded with the manual and I can't see a fault...any advise would be great...thanks
$(document).ready(function() { $.ajax( { url: "items.php", dataType: "json", data: '<?php echo $data; ?>', timeout: '2000', cache: false, error: function(data) { alert('error'); }, success: function(data) { $.each(data, function() { $("#table").append('<div class="row"><span class="cell">'+ data.title +'</span><span class="cell"></span><span class="cell"></span></div>'); }); } }); }); I am retrieving Google Books info in JSON format and displaying it inside a div. I would like to send the contents of this div (name, title, description) to my database using Ajax.
Currently only the ISBN field sends because I have it declared as a variable. However my question is, how do I send the other fields (name, title, author). How do I declare these also, I'm not sure what format they need to be in etc.
My JS
$(document).ready(function() { $('#submit').click(function(ev) { ev.preventDefault(); var isbn = $('#isbn_search').val(); //get isbn direct from input var url='https://www.googleapis.com/books/v1/volumes?q='+isbn; $.getJSON(url,function(data){ $.each(data.items, function(entryIndex, entry){ var html = '<div class="results well">'; html += '<h3>' + entry.volumeInfo.title + '</h3>'; html += '<div class="author">' + entry.volumeInfo.authors + '</div>'; html += '<div class="description">' + entry.volumeInfo.description + '</div>'; }); }); }); });My Ajax; $.ajax({ type: 'POST', url: 'addIsbnScript.php', data: { 'isbn' : isbn, 'title' : title 'subtitle' : subtitle, 'authors' : authors, 'description' : description }, success: function () { $.growl({ message: " Record added" }); } });Note, if i manually set the vars like below they all do successfully send to my database, so I know my query is working ok var title = "some text", var author = "some text", Var description = "some text"Thanks in advance for any help, newbie here (incase it wasn't obvious!). J This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=315198.0 //my php code sample <?php include_once('con.php'); if(isset($_POST['username'])){ $message = []; if(empty($_POST['username'])){ $message['username'] = 'username required'; } #some validation continue... $data = $_POST['username']; if (count($errors) === 0){ #ccode... $message['username'] = 'success your name saved'; } } ?> //my jquery ajax $('.username').click(function() { $.ajax({ url: 'user.php', method: 'POST', data: $('.user').serialize(), success: function(data) { swal('Wow!','success message from php','success'); }, error: function(data) { swal('Oops!','error message from php','error'); } }); return false; });
Hi all
we have an ajax query which queries a MySQL database for cities around the world for our hotel search. We are running on a Linux web hosted server.
The problem we are having is when you first visit out site and type in Brisbane or Sydney it takes around 15 seconds maybe to return. After that what ever city you query is lightening fast. I have had a few friends try this and when they first visit our site they experience the same then second time around it is fast.
Could this be some sort of caching issue or setting somewhere that I am missing?
I have attached a file so you can see what I mean
Thanks in advance
Attached Files
ajaxqry.jpg 169.31KB
0 downloads Hi Guys, I'm trying the following.. returning an array from a php function to Ajax success but the alert seems to only display undefined. PHP Code: [Select] public function reply() { $item_id = $this->uri->segment(3); $type = $this->uri->segment(4); if($type == 1){ $data['get_news_item'] = $this->Newsletter_model->get_news_item($item_id); $test = array( "Paul", "Mike"); return $test; } } AJAX Code: [Select] $.ajax({ type: "POST", url: "<?php echo site_url(); ?>newsletter/reply/"+id+"/"+type, cache: false, success: function (data){ alert(data[0]); // So this should display "Paul"? }); [/code] Right now I redirect to index page after I delete a record. However I am looking to make it so that I can delete a record without redirecting the page. I know this can be accomplised using Ajax. I have spent countless hours before trying to make it work, but it did not work.
So here is a basic setup I created. Can you please update it with ajax code so that I can see how it's done properly?
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <div class="record" > <a href="record.php?id=<?php echo $record_id ?>"><?php echo $record_name; ?></a> <div class="delete-record"> <a href="delete.php">Delete Record</a> </div> </div> </body> </html> Edited by man5, 18 August 2014 - 08:55 PM. Now I'm having this strange issue with my website I'm currently working on a tester system and I've encountered a problem that I'm unable to find the issue, tho I'm thinking my ajax php part of the script to be the thing causing it even tho it seems strange that it would cause it. The first part which is connected to where the problem occurs is the echo"<form>"; and from there, It should take you to index.php?page=tester&select=answer, now that is where it in the browser goes there tho it still shows the page stuff from the last page which is index.php?page=tester&select=applications, so it's like showing both &select=answer and &select=applications on the same page. <?php $q=$_GET["q"]; include'../config/connection.php'; $result = mysql_query("SELECT * FROM applications WHERE id = '$q'"); echo "<center><table border='1'> <tr> <th>Account Name</th> <th>Character Name</th> <th>Gender</th> <th>Skin Color</th> </tr>"; $row = mysql_fetch_array($result); echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['charactername'] . "</td>"; echo "<td>" . $row['gender'] . "</td>"; echo "<td>" . $row['race'] . "</td>"; echo "</tr></table></center>"; echo"<br/>"; echo"<table><tr> <th>Description</th> <th>Metagaming</th> <th>Powergaming</th></tr>"; echo"<tr>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['description']."</textarea></td>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['mg']."</textarea></td>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['pg']."</textarea></td>"; echo"</tr></table><table><br/><center><h1>Answer</h1><br/><form action='index.php?page=tester&select=answer' method='post'>"; echo"<textarea name='why' style='height:10em; width:60em;'></textarea><br/>"; echo"<input type='submit' name='answer' value='Accept' /><a/>"; echo"<input type='submit' name='answer' value='Decline' /></center>"; echo"<input type='hidden' name='id' value='$q'/>"; echo"</form></table>"; ?> Now on &select=answer it included a page which the script of that include consist of the stuff below, it outputs that the query was successfully, and all that. <? if(!empty($_POST['why'])) { $why = mysql_real_escape_string($_POST['why']); $answer = trim($_POST['answer']); $id = $_POST['id']; if($answer == "Accept") { $query1 = mysql_query("UPDATE characters SET accepted = '1' WHERE id = '".$id."'"); echo"Successfully accepted"; $answer = 1; } elseif($answer == "Decline") { echo"Successfully declined"; $answer = 0; } $query = mysql_query("UPDATE applications SET answer = '$why' AND tester = '".$_COOKIE['Username']."' AND accepted = '$answer' AND answered = '1' WHERE cid = '".$id."'") or die('Could not connect: ' . mysql_error()); if($query) { echo"<br/>Query went through without problems"; header("Refresh: 5;url=index.php?page=tester"); } } ?> This is the ajax part javascript of it which gets the information for index.php?page=tester&select=applications Code: [Select] <script type="text/javascript"> function showApplication(str) { if (str==""||str==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","tester/applications.php?q="+str,true); xmlhttp.send(); } </script>If you need any more information feel free to ask for it. Thanks in advance. Hello, I've been trying this for hours now, looking at different examples and trying to change them to work for me, but with no luck... This is what I am trying to do: I have a simple form with: - 1 input field, where I can enter a number - 1 Submit Button When I enter a number into the field and click submit, I want that number to be send to the php file that is in the ajax call, then the script will take that number and run a bunch of queries and then return a new number. I want that new number to be used to call the php script via ajax again, until no number is returned, or something else is returned like the word "done" or something like that, at which point is simply makes an alert or populated a div with a message... The point is, that depending on the number entered it could take up to an hour to complete ALL the queries, so I want the script that is called to only run a fixed amount of queries at a time and then return the number it is currently at (+1), so that it can continue with the next number when it is called again. I would like to use jquery, but could also be any other way, as long as I get this to work. I already have the php script completed that needs to be called by the ajax, it returns a single number when being called. Thank you, vb As the title say, I can not for the life of me get the "$bank" content to display, no matter HOW much I try... Does anyone see any errors. I am sooooooo wiped out at this! main page <? $body = ' <script type="text/javascript" src="change-content.js"></script> <div id="addSold"> <form action="'.$_SERVER['REQUEST_URI'].'" method="post" name="form" autocomplete="off"> <fieldset id="Vehicle"> <legend>Vehicle</legend> <ul> <li><label for="Year">Year</label>'.$Year.'</li> <li><label for="Make">Make</label>'.$Make.'</li> <li><label for="Model">Model</label>'.$Model.'</li> <li><label for="Trim">Trim</label><input type="text" name="Trim" id="Trim" size="10" value="'.$trim.'" disabled="disabled"></li> </ul> <ul> <li><label for="Mileage">Mileage</label><input type="text" name="Mileage" id="Mileage" size="5" maxlength="6" value="'.$row['mileage'].'"></li> <li><label for="VIN">VIN</label><input type="text" name="VIN" id="VIN" size="23" maxlength="17" value="'.$row['vin'].'" disabled="disabled"></li> <li><label for="Color">Color</label>'.$Exterior.'</li> </ul> </fieldset> <fieldset id="Deal"> <legend>Deal</legend> <ul> <li> <label for="soldDte1">Date</label> <input type="text" name="soldDte1" id="soldDte1" size="1" maxlength="2" onkeyup="return autoTab(this, 2, event)" value="08"> / <input type="text" name="soldDte2" id="soldDte2" size="1" maxlength="2" onkeyup="return autoTab(this, 2, event)" value="30"> / <input type="text" name="soldDte3" id="soldDte3" size="1" maxlength="2" value="'.$year.'"> <a href="#"><img id="date_'.$row[stock].'" src="images/Icons/dateOff.png" onfocus="this.select();lcs(this)" onmouseover="MM_swapImage(\'date_'.$row[stock].'\',\'\',\'images/Icons/dateOn.png\',1)" onmouseout="MM_swapImgRestore()" alt="Choose Date"></a> </li> <li> <label for="salesman">Salesman</label> <select name="salesman" id="salesman"> <option></option> '.$salesmen.' </select> </li> </ul> <ul> <li> <label for="dealType">Deal Type</label> <select name="dealType" class="select-content" onchange="getFile(this.value)"> <option></option> <option value="AL">Auto Loan</option> <option value="Cash">Cash</option> <option value="CAC">Credit Acceptance</option> <option value="IH">In House</option> <option value="SAL">Sensible Auto</option> </select> </li> <li> <label for="tradeDrop">Trade</label> <select name="tradein" id="tradeDrop" onchange="show_hide_trade(this.value);"> <option value="No">No</option> <option value="Yes">Yes</option> </select> </li> </ul> </fieldset> <div id="Bank" class="view">'.$bank.'</div> </form> </div> '; ?> get_Bank.php <? if ($_GET['dealType'] == "AL") { $bank = ' <fieldset id="AL"> <legend>Auto Loan Figures</legend> <ul> <li><label for="price">Price</label><input type="text" name="price" id="price" class="price" size="7" onchange="currency(this)"></li> <li><label for="down">Down</label><input type="text" name="down" id="down" class="price" size="6" onchange="currency(this)"></li> <li><label for="tax">Tax</label><input type="text" name="tax" id="tax" class="price" size="6" onchange="currency(this)"></li> <li><label for="reg">Plates</label><input type="text" name="reg" id="reg" class="price" size="4" onchange="currency(this)"></li> <li><label for="gap">Gap</label><input type="text" name="gap" id="gap" class="price" size="4" onchange="currency(this)"></li> </ul> <ul> <li> <label for="pymtNum">--------------- Payment ---------------</label> <input type="text" name="pymtNum" id="pymtNum" size="3" maxlength="3" onkeyup="return autoTab(this, 3, event)"> @ <input type="text" name="pymtAmnt" id="pymtAmnt" class="price" size="5" onchange="currency(this)"> per <select name="pymtType"> <option value="Weekly" selected="selected">Week</option> <option value="Monthly">Month</option> </select> </li> <li><label for="APR">APR</label><input type="text" name="APR" id="APR" class="rate" size="6" value="19.00"></li> </ul> </fieldset> '; } elseif ($_GET['dealType'] == "CAC") { $bank = ' Credit Acceptance stuff goes here '; } else { $bank = 'You must choose a bank before continuing'; } ?> change-content.js Code: [Select] window.onload = init; // finds all <select> tags will class="select-content" and activates function function init() { var sel = document.getElementsByTagName("select"); for (var i=0; i<sel.length; i++){ if (sel[i].className == "select-content") { sel[i].onchange = getFile; } sel[i].selectedIndex = 0; } } function getFile (url) { var url = "AJAX/get_Bank.php?dealType="+ this.value; if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");} xmlhttp.open("GET",url,false); xmlhttp.send(); // a loop that looks through all <div>s on the page // and then replaces the id with the value and gets that file var divs = document.getElementsByTagName("div"); for (var i=0; i<divs.length; i++) { if(divs[i].id == "bank") { divs[i].id = this.value; divs[i].innerHTML=xmlhttp.responseText; } } } Hey guys I am Posting data over to a server file in Json and I need to know how I can add to the XML file. here is both codes.
function validate() { $xml = simplexml_load_file("stock.xml"); $sxe = new SimpleXMLElement($xml->asXML()); for($i = 1; $i < 801; $i++) { $newItem->addChild("name" , "null"); } $sxe->asXML("stock.xml"); echo $sxe->asXML(); $response = $_POST; $response["items"] = "Test output"; $response["description"] = "test 42 "; $response["json"] = json_encode($response); echo json_encode($response); }The red text is what I want this json script to do. Do I have to return back to my form to add to the XML file? Can json add to a xml file on its own? Thanks for your time! have a good day! Please see http://www.socialnewsoffice.com/blog_posts?&display=2&api_key=b5cbd66dca99c49d1a6c3d which out puts a json response like this Code: [Select] [{ "blog_id":"3", "post_date":"Sat, 14 April 2012", "post_title":"Facebook's New Fan Page Learn How To Use Features", "article_img":"http:\/\/www.socialnewsoffice.com\/uploads\/17963.jpg", "post_content":"<p>This week saw the release of Facebook's latest functionality changes (Timeline for Businesses) that will shape the future of how businesses will market their campaigns, through the social media giant Facebook. A number of marketers are wondering how they will incorporate the new features in an attempt to progress and move forward with their online social media presence.<\/p>\r\n<p>Taking all the key changes in to consideration we have managed to create a guide on how to smoothly move with the times and embrace the new Facebook layout.<\/p>\r\n<p>Please read on below for helpful tips and tricks on how to excel with 'Timeline for Brands'<\/p>\r\n<h2>New Features Announced at the Facebook Marketing Conference:<\/h2>\r\n<p><strong>View and Apps:<\/strong> What was once known as Application pages has changed to 'Tabs'. These can now have customizable images linked with them and the order of them can be changed too. Below you can see from the screenshot what a customized Facebook Timeline looks like.<\/p>\r\n<p><strong>Pinning Content:<\/strong> With this new feature you can 'pin' a post to the very top of your Facebook Timeline. This is Very effective when working on a new campaign and is a great way to entice increased traffic to your tab or application page.<\/p>\r\n<p><strong>Featured 'Starred' Content:<\/strong> This feature allows you to select key content or imagery and extend it so it fits across your entire page. Therefore giving you featured content on your Facebook Timeline and making it more visible.<\/p>\r\n<p><strong>Cover Photos:<\/strong> Cover Photos are another great new feature that allow you to announce your latest campaign, welcome your following community or just simply show visitors to your timeline what you can do. There are some slight flaws with this feature though and will be addressed below.<\/p>\r\n<p><strong>Page Dimensions:<\/strong> Dimensions of application pages has now changed with the release of Facebook Timeline. If you happen to be an SML user then you have all the tools necessary to update your page on your own. If your using Involvers App Suite then those applications will be updated soon.<\/p>\r\n<p><strong>Removal of Default Landing Pages:<\/strong> The commonly used Facebook landing pages have been removed and replaced with various options to allow brands to drive content to application pages. These options allow you to use your cover photo and pinned content to attract users to your personal application pages. Despite the changes it is however still possible to link directly to application pages from ads, posts and outside of Facebook.<\/p>\r\n<h2>Getting Started with Timeline For Brand:<\/h2>\r\n<p>Firstly when accessing and logging in to your New Facebook Brand Page, you will see this admin message displayed below:<\/p>\r\n<p>When will my Page change to the latest design?<\/p>\r\n<p>To see a preview of what your new pages will look like, simply click on the green button at the top of your current pages. A second option is to wait until March 30th 2012 when all pages will be upgraded automatically.<\/p>\r\n<p>Where can I visit to learn more about how to use the new Pages?<\/p>\r\n<p><strong>There are a number of places you can visit to learn all you need to know about Pages:<\/strong><\/p>\r\n<ul>\r\n<li>To find out more about new features, download the Pages Overview guide by clicking here.<\/li>\r\n<li>If your wondering how to get started with Pages then download Facebook's full Pages Product Guide by clicking here.<\/li>\r\n<li>The Pages Learning video allows you to walk through the key features with Facebook's product experts.<\/li>\r\n<li>If you need answers to specific questions, visit Facebook's Help Centre.<\/li>\r\n<\/ul>\r\n<h2>How should I choose a cover photo for my Page?<\/h2>\r\n<p>Firstly select a unique image that represents your page. Facebook itself recommends using a photo of a popular menu item, album artwork or an image of your product being used by someone. You need to experiment with a number of different images that your audience responds positively to. Few key elements of Cover Images:<\/p>\r\n<p><strong>Each Cover image must be at least 399 pixels wide and must not contain the following:<\/strong><\/p>\r\n<ul>\r\n<li>Prices \/ Purchase information and displaying offers such as \"60% off this month\" are not permitted. Also 'Download this from our website' is not allowed.<\/li>\r\n<li>No email addresses, web addresses and any other contact information.<\/li>\r\n<li>References to clicking on or the use of Facebook interface elements such as Like or Share or any other Facebook Features.<\/li>\r\n<li>\"Tell your friends\" or \"Get it now\" or any other calls to action are not allowed in the latest version of Facebook Timeline.<\/li>\r\n<\/ul>\r\n<p>All Timeline cover imagery is public and therefore means anyone visiting your Page will be able to see exactly which image you have chosen. The photos you display must not be deceptive, false or misleading any way that infringes on third party intellectual property. You must also not encourage of incentivize other fellow users, friends or business associates to display the same cover image as yours on personal Timelines.<\/p>\r\n<p>To sum up we are extremely excited about the latest Facebook feature release this week. They constantly deliver new services that are amazing and incredibly innovative to the market place.<\/p>\r\n<p>Here at Northplanet we are commited to provide you with the latest information on the hottest online topics around, to keep you ahead in the game. We would love to hear some feedback from you on the brand new Facebook 'Timeline for Brands' release and invite you to visit our very own <a href=\"https:\/\/www.facebook.com\/northplanet\">Northplanet Facebook Timline page by clicking here.<\/a><\/p>", "tags":"facebook, new fan page", "views":"463", "categorie_id":"2", "post_url":"facebooks-new-fan-page-learn-how-to-use-features" },{ "blog_id":"2", "post_date":"Mon, 23 January 2012", "post_title":"Northplanet Engages New Talent!", "article_img":"http:\/\/www.socialnewsoffice.com\/uploads\/1263.jpg", "post_content":"<p>Big piece of news for the start of 2012 is…… I have landed a full time role in a leading Web Design and Development agency based in Greater Manchester. After a successful interview on New Years Eve, I had another reason to celebrate bringing in the New Year!!<\/p>\r\n<p>I was first attracted to Northplanet when I came across there website when searching for jobs online. I was impressed not only by the standard of web work but the direction the company where going in. Growing year by year and providing exceptional web solutions for a number of businesses spread across the UK.<\/p>\r\n<p>I contacted them instantly and have done some freelance work a few times in the last year for Directors Danny and Mike and was able to build up a strong working relationship that helped me land the interview at the end of the year.<\/p>\r\n<p>I begin my career at Northplanet next week and will post all offers\/promotions and deals on here in the nearfuture.<\/p>\r\n<p>Time to sign off and prepare for my new career!!<\/p>", "tags":"engages new talent, new staff, northplanet staff, christian thomas mizon", "views":"271", "categorie_id":"1", "post_url":"northplanet-engages-new-talent" }] here is my code that does this Code: [Select] if (mysqli_num_rows($r) > 0) { // Available. while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $results[] = array( 'blog_id' => ($row['ID']), 'post_date' => ($row['pd']), 'post_title' => (html_entity_decode($row['post_title'], ENT_QUOTES)), 'article_img' => ('http://www.socialnewsoffice.com/uploads/'.$row['article_img']), 'post_content' => ($row['post_content']), 'tags' => ($row['tags']), 'views' => ($row['views']), 'categorie_id' => ($row['categorie_id']), 'post_url' => ($row['post_url'])); } echo $json = Pretty_JSON(json_encode($results)); } i can access the json by using foreach($blog_posts as $post) { however what i need to do is add a value to the json like pages => 2 how could i do this? im trying to access code in Code: [Select] array(1) { [0]=> object(stdClass)#4 (1) { ["error"]=> array(1) { [0]=> object(stdClass)#5 (2) { ["message"]=> string(33) "no results found (error code 458)" ["code"]=> string(3) "458" } } } } ive tryed echo $blog_posts[0]->error->code; but all i get is Notice: Trying to get property of non-object in /home/sites/inspiredanceacademy.com/public_html/sno-blog-test/lib/social_news_office.php on line 173 My script is not acting like it should. I believe its because of the recent change in the api, (the new error array)? Before there was only one.... <?php $gamertag = 'l RaH l'; $url = "http://api.xboxleaders.com/user_api.php?gamertag=".str_replace(' ', '%20', $gamertag); $output = file_get_contents($url); // try to convert the response into a PHP object $obj = json_decode($output); if(!is_object($obj)) die("Error parsing JSON response\n"); //define variables $avatar = ($obj->user->avatar); $gold = ($obj->user->gold); print $avatar; print $gold; ?> if you print_r $object; it displays this {"error":{"code":200,"desc":"OK"}},{"user":{"gold":1,"gamertag":"l RaH l","avatar":"http:\/\/avatar.xboxlive.com\/avatar\/l%20RaH%20l\/avatarpic-l.png","gamerscore":12508,"reputation":20},"recent_games":[{"recent_game":{"title":"Halo: Reach","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1297287259&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/ih\/ew\/0Wdsb2JhbA9ECgR8GgMfVlohL2ljb24vMC84MDAwIAAAAAAAAP6fF5U=.jpg"}},{"recent_game":{"title":"Halo 3","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1297287142&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/Us\/3e\/1Wdsb2JhbA9ECgR8GgMfWSpVL2ljb24vMC84MDAwIAAAAAAAAPrxzU0=.jpg"}},{"recent_game":{"title":"AC Brotherhood","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1431504989&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/oK\/tp\/1Wdsb2JhbA9ECgUNGgMfVlonL2ljb24vMC84MDAwIAAAAAAAAPpGq78=.jpg"}},{"recent_game":{"title":"Fighters Uncaged","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1431504974&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/v+\/Au\/0Wdsb2JhbA9ECgUNGgMfVlsmL2ljb24vMC84MDAwIAAAAAAAAP4B4KA=.jpg"}},{"recent_game":{"title":"Assassin's Creed","link":"http:\/\/gamercard.xbox.com\/en-US\/GameCenter\/Achievements?titleId=1431504852&compareTo=l%20RaH%20l","image":"http:\/\/tiles.xbox.com\/tiles\/L3\/mu\/0Wdsb2JhbA9ECgUNGgMfWStXL2ljb24vMC84MDAwIAAAAAAAAP6BeTA=.jpg"}}]} Okay so i know this is going to sound really stupid i just got out of school and now im in the real world here is the problem I dont know very much about how to work with JSON via PHP all i am trying to do is have the Script read data into an array from some text boxes then from the array into a JSON file the reading and the listing is all fine and dandy but only if i want the entire file how do i read data from a JSON file and only have it display data according to what i want so for example if i wanted to return data that matched an ID like you would do in MySQL like this ("SELECT * FROM catagories WHERE ID = '$id'") so how do i do that without a Database using a JSON File as a source for the data Hi, I have two select boxes on my site like this: Language - Level and the user can keep adding more sets of select boxes. I need the data posted to be JSON encoded like this: {"LANG1":["German","Beginner"],"LANG2":["Polish","Advanced"]} etc How can i make this happen? I have some PHP which sends some user provided data to the client:
<?php header('Content-type: application/json'); $data=array( array('id'=>10,'firstname'=>'John','lastname'=>'Doe'), array('id'=>14,'firstname'=>'Jane','lastname'=>'Doe'), array('id'=>19,'firstname'=>'XSS!','lastname'=>'XSS!'), ); echo(json_encode($data)); ?>The client then displays the data: $.getJSON('getJSON.php', { something: 123 }, function(list) { var string = ''; for (var i in list) { string += '<li>< a href = "index.php?id=' + list[i]['id'] + '">' + list[i]['firstname'] + '</a></li>'; } $("#MyElem").html(string); });Does this represent any XSS risk? If so, how do I prevent it? Hello, I can't get a json call to work in my php... Hope some one can see where I am going wrong and push me in the right direction. I have 3 values I am trying to send from the php file to the html. The output looks as if it should work, but is does not... So here is the php variable that does give me a result, but I have no idea why it does not show in the div. <?php $choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d"); $con = mysql_connect("localhost","root","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$choice."' group by date"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); $dayPowerP = array( $row['choice']); ?> <?php $choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("localhost","root","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); $monthPowerP = array($row['choice']); ?> <?php $choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("localhost","root","xxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("inverters", $con); $sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); $row = mysql_fetch_assoc($res); $yearPowerP = array( $row['choice']); ?> <?php $outarr['dayPowerP'] = $dayPowerP; $outarr['monthPowerP'] = $monthPowerP; $outarr['yearPowerP'] = $yearPowerP; echo json_encode($outarr); ?> Now there are no errors, and this is what the output is so I would assume it should work as the right values are there and the right id..... Code: [Select] {"dayPowerP":["12.7240"],"monthPowerP":["145.0460"],"yearPowerP":["941.0370"]} I do not understand. Now the Jquery should be working as well... the ajax should be sending the post with json to carry the key data to make a clear result from the php and json should be doing it's job in the php file and the Jquery is do basic to have any issues, so that leaves my focus on the PHP at this time, but I do not see a proplem. Code: [Select] $(document).ready(function () { $('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) { var myDate = $(this).datepicker('getDate'); $('#apDiv1').html($.datepicker.formatDate('DD, d', myDate)); $('#apDiv5').html($.datepicker.formatDate('MM', myDate)); $('#apDiv7').html($.datepicker.formatDate('yy', myDate)); $.ajax({ type: "POST", url: "clickdates.php", data: {choice: dateText}, dataType: "json", success: function(json_data) { $('#apDiv2').html(json_data['dayPowerP']); $('#apDiv6').html(json_data['monthPowerP']); $('#apDiv8').html(json_data['yearPowerP']); } }) }}); }); The one thing that is odd. When I use 3 different php files, it works perfect, but that is not using json. Now that I am using json to return 1 call from the php, I am lost at this point, does anyone see what I can't... Thanks, Alan |