PHP - How Return Json Object, Not String To Ajax?
I 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? Similar Tutorials
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>
Hello all, I'm trying to change the end of a javascript call based on the end of the url string. The common part of all the url strings is sobi2Id=, I'm trying to do this with strstr but am having no luck. I'm new to php so my syntax knowledge is terrible! at the moment i've got Code: [Select] <?php $url = $_SERVER['REQUEST_URI']; $tag = strstr ($url, 'sobi2Id='); echo $tag; ?> but this returns an unexpected T_STRING, expecting ',' or ';' Can anyone debug this? I may well be being really silly! 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 $m=json_decode($html); print_r($m); stdClass Object ( [requestGuid] => [orderId] => [statusCode] => SUCCESS [statusMessage] => SUCCESS [response] => stdClass Object ( [amount] => 100 [currencyCode] => INR [status] => 1 [message] => ACTIVE [ownerGuid] => 7898980 [walletType] => USER [ssoId] => 9op09 [txnPinRequired] => [otpPinRequired] => ) [metadata] => )this is json decoded object and want to get property of amount .plz help me Edited by ShivaGupta, 04 December 2014 - 04:17 AM. This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=315198.0 Hi!
I have this code above:
// Submit Data to ncbi. // Sends form's data to classController.php function NCBI_submit_data() { $formData = $('#blastx_form').serialize(); $php_method = 'ncbi_request'; $finalData = $formData + "&php_method=" + $php_method; $aR = ajaxReq('POST','../../classes/classController.php',$finalData,'json'); console.log($aR); } // General Ajax function function ajaxReq($method,$url,$data,$dataType) { $.ajax({ type: $method, url: $url, async: 'false', data: $data, dataType: $dataType, success: function(json, textStatus, jqXHR) { return json; }, error: function(jqXHR, textStatus, errorThrown) { console.log('Ajax call error: '+jqXHR.status+' '+errorThrown) } }); }Server returns a json object and i want to save it in aR variable. But console.log($aR); returns undefined Any idea on how to fix it ? //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; });
This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=322125.0 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] I need to return a specific key from the object converted to array but it seems that it dosent work Code: [Select] $toarray = (array)$tmp; $name = array_keys($toarray,'name'); print_r($toarray); print:Array ( [id] => 9 [name] => dfd [text] => fdsf [rating] => 0 [totalv] => 0 ) and when i try to return the key Code: [Select] print_r($name); Array ( => rating [1] => totalv ) But I only need the key whit the 'name' value Hello everyone.
please I have problem with printing out a value from inside an array of a nested json. ive tried several ways its always returns "index not define". $valr= "https://ice3.com/api/v1/orderbook/ticker"; ////////////////////////////source $valrGet = file_get_contents($valr); $valrD = json_decode($valrGet, true); $valrSell = ["ask"] ["price"]; Here is the structure of the json from the source : {"errors":false,"response":{"entities":[{"pair_id":3,"pair_name":"BTC\/ZAR","ask":{"price":"179382.54","amount":"0.05357142"},"bid":{"price":"177229.4286563","amount":"0.0011"}},{"pair_id":4,"pair_name":"BTC\/NGN","ask":{"price":"8890000.00","amount":"0.10"},"bid": my target is to output the value of ("price") from "pair_name" BTC\/ZAR please help. Thanks in advance I'm trying the fetch some geocode data from mapquest. Google doesn't like me right now. I keep running into the query_limit. So I want to set a back up that will go into production when I get that error from the big G. I have my api key and I can put the string in a var. Code: [Select] $geocode = file_get_contents($url) I selected json as the output and when I echo $geocode... here is the first portion of the string....(I want lat & lng) Code: [Select] renderOptions({"results":[{"locations":[{"latLng":{"lng":-112.35984,"lat":34.58752},..... Now for the life of me, I can't do anything with it. I've tried json_decode() with the true argument there and not. Code: [Select] $output = json_decode($geocode, true); $output = json_decode($geocode); vardump($output) is NULL. So, I thought, well maybe I don't need to decode it, but I can't figure out how to parse it. I'm lost. This admittedly is my first attempt as trying to work with a jason object, but jeesh, it doesn't seem like it should be that hard. Can someone start me in the right direction? I got a response from an api in json. How do i echo out the account_name in string. Thanks as usual. The response is below...
{ "status": true, "message": "Account number resolved", "data": { "account_number": "2067483918", "account_name": "BABALOLA MAYOWA ABEL", "bank_id": 18 } } "status": true, "message": "Account number resolved", "data": { "account_number": "2067483918", "account_name": "BABALOLA MAYOWA ABEL", "bank_id": 18 } }
I need parse the JSON string below into an associative array, sort it by the 'age' field and output the sorted array as an HTML table. Here is what I have done so far but it just returns me 'Array': Code: [Select] <?php $json='[{"name": "John","age": 23},{"name": "jim","age": 19},{"name": "jason","age": 34}]'; $array = json_decode( $json, true); function cmp( $a, $b){ if( !isset( $a['age']) && !isset( $b['age'])){ return 0; } if( !isset( $a['age'])){ return -1; } if( !isset( $b['age'])){ return 1; } if( $a['age'] == $b['age']){ return 0; } return (($a['age'] > $b['age']) ? 1 : -1); } usort( $array, 'cmp'); foreach ($array as $key => $value) { echo $key.":".$value."\n"; } ?> I call a web service and it retuens the values in the following format
$response = $client->submitRequest($requestParams);Which returns stdClass Object ( [return] => stdClass Object ( [result_code] => 0 [result_data] => City[0]=Chicago [message_text] => ) )what I want is just the value for [result_data] => City[0]=Chicagoassigned to a variable Psedo Code $city = [result_data] => City[0]=Chicago;so that $city = Chicago; Hello everyone, Pretty much what I am trying to do is run a query and based of the queries result, return a string - as of now it is turning up blank and cant seem to pass any strings through the function. Current function: function addNewBookmark($hash,$url,$title,$username){ Code: [Select] $query = "INSERT INTO bookmarks (hash,url,title,username) VALUES '".md5($hash)."', '".$url."', '".$title."', '".$username."')"; $result = mysql_query(query, $this->connection); $message = ''; if(mysql_affected_rows($this->connection)!=1) { $message = 'This URL already exists in the database!'; return $message; } else $message = 'The URL was shared!'; return $message; } The above code seems to run fine, just cant seem to pass a string...read that you can possibly use a __toString function? but that keeps throwing errors when I try to work with it. Thanks all! I apologize if I am using the wrong terminology here... I am trying to take an image that is dragged and dropped and then uploading the image to a server to do other things with it. I've found very generic example(s) that can just move the file, but I need to be able to manipulate it on the server. AJAX cut-out code: Code: [Select] var xhr = new XMLHttpRequest(); if(xhr.upload && file.type == 'image/jpeg' || file.type == 'image/png'){ xhr.open('POST', 'path/to/script.php', true); xhr.setRequestHeader('X_FILENAME', file.name); xhr.send(file); }The above part works but when I try to manipulate it with PHP it doesn't see it as a typical $_FILES variable. Ideally I would like to get it to be like that, if not I understand I will have to change stuff. Here is my PHP that handles the above call: Code: [Select] <?php $slide = new Slide(); //echo gettype($_SERVER['HTTP_X_FILENAME']); //str $file = file_get_contents('php://input'); $image = base64_decode($file); if($slide->add_image_to_slide($_GET['sid'],$image)){ echo 'yay'; }else{ echo $slide->error; } Object Code: Code: [Select] <?php public function add_image_to_slide($id,$image){ //Verify image before proceeding forward $accepted_file_types = array('jpg','png'); $ext = explode('.',$image['name']); if(array_search($ext[1],$accepted_file_types) !== false) { //variables $this->id = $id; $this->select_slide($this->id); //make sure that the folders for the images to go actually exist, if not, create them $this->create_folders(); $this->generate_thumbnail($image); $this->thumbnail = $this->upload_directory.$this->rand_id.'_thumb_'.$this->filename; $this->full_img = $this->upload_directory.$this->rand_id.'_'.$this->filename; // thumbnail is moved automatically by function above, just move full image move_uploaded_file($image['tmp_name'], BASE_ROOT.'/'.$this->full_img); if($stmt = $this->_db->prepare('UPDATE slides SET full_img = ? , thumbnail = ? WHERE id = ?')){ $stmt->bind_param('ssi',$this->full_img,$this->thumbnail,$id); $stmt->execute(); $stmt->close(); return true; } return false; } $this->error = 'File Extension Error: .jpg, .png allowed only'; return false; } Right now it's skipping straight to $this->error since it's not an image object. I'm not really sure what to pursue from here. I did try this line once but it also skipped to the error line: Code: [Select] <?php $image = createimagefromstr(file_get_contents('php://input')); Any help would be greatly appreciated! Thanks, Justin |