How to send PHP variables and retrieve them with Jquery (without echo)? - php

I'm building a search function to retrieve XML data for a google map.
In addition to that, I want to display how many results were actually found.
I thought about doing an echo inside the actual document, however that might mess with my marker data. How would I take a PHP variable and retrieve it in Jquery after a success call?
If my PHP looked like this:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
And Jquery like this:
$.ajax({
type: "POST",
url: "MapSearchxml.php",
data: {
dataFromDate: FromDate,
//lalala
dataHasPatio: HasPatio
},
beforeSend: function (html) { // this happens before actual call
$("#results").html('Please Wait');
$("#searchresults").show();
$(".phpFromDate").html(FromDate);
},
success: function (data, status, jqXHR) {
//Success?
},
dataType: 'xml'
});

Might find it easier to create array in php and send JSON. At client is easy to loop over response object/array
$output=array('status'=>'', 'results'=>array());
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
if( $num_rows){
$output['status']='ok';
/* push row data to $output['results'][]; in while loop*/
}else{
$output['status']= 'No results';
}
echo json_encode( $output);
Then in jQuery:
success:function( data){
if (data.status != 'No results' ){
/* count array length*/
var count= data.results.length;
/* loop over data.results array*/
}
}
/* change dataType to "json"*/
I forgot about count and added it in jQuery...can also add a count property to the $output php array and use $num_rows to populate

Just trying out a JSON example for you, this has echo but you can do complex things with it?
Not sure if that is what your after? I get that you don't want to do echo on each variable, and you wont if using JSON.
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>

You see, what AJAX gets on success is an html code. If you AJAX a complete html page you will get it back, starting with <html> and ending with </html>. You can just make a special markap on your return html data, like [sepcial_info : 'INFO'] or somthing and then just to filter it.

Okay, I needed a bit to decipher your question, probably I'm still wrong, let's try:
What you try to do is not technically possible with what you have in mind. In short: If you do one Ajax request, you return one response. The moment the success function is called, your PHP script is already gone. So you can only pass one return value.
However what you can do is, that you make that return value a nested one, e.g. containing two parts:
The XML document you already returned
The count
That is probably your solution. If you ask how, I would add the count as a namespaced value to the XML and then process it with javascript.
As you have not shown any code here, I can not give a quick example (and I leave that as a pointer for your future questions) for your case. Add a namespace element, like an attribute is pretty simple with DOMDocument in PHP.

Related

JS and Ajax: how to dismantle JSON object consist of multiple DB records

I try to learn JS together with jQuery and Ajax, and until now it was more or less painless, but now I faced myself with some obstacles about getting result from called PHP script, initiated by Ajax. What is my problem here? I have a MySQL table and I wanted to pull some data from JS by Ajax call. I tested my query to check is it correct and make result and with same query I built PHP script. Here is my JS file:
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<script>
callphp(12,14);
//
function callphp(par1, par2) {
$.ajax({
type: "POST",
url: "_ajax2php2.php",
cache: false,
dataType: "json",
data: { "po1": par1, "po2":par2 },
success: function(data, status, jqXHR){
jss=JSON.stringify(data);
alert(jss);
//
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " +data[key] + "\n"); }
}
alert(strBuilder.join(""));
},
error: function(data) {
alert( "params error" );
}
});
// end of JS
and here is my PHP script:
<?php
$eol="<br/>";
$uuu= isset($_POST['po1']) ? $_POST['po1'] : '';
$zzz= isset($_POST['po2']) ? $_POST['po2'] : '';
$con=mysqli_connect("localhost","root","some_password","mydbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Fail to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"mydbase");
$query4 = "SELECT * from mytable WHERE uc_id='$uuu' AND pr_id='$zzz' ";
$result4 = mysqli_query($con, $query4);
$row4= mysqli_fetch_assoc($result4);
if(mysqli_num_rows($result4) > 1) {
while($row4[]=mysqli_fetch_assoc($result4)) {
$data = $row4; }
}
else
{$data=$row4;}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
/* free result set */
mysqli_free_result($result4);
mysqli_close($con);
//end of php
?>
and it seems that it works good when PHP query return just one record, if there are 2 or more then I'm unable to "dismantle" JSON object by this JS code, because for example if my query return 3 records, in alert it appears like
Key is 0, value is [object Object]
Key is 1, value is [object Object]
Key is name_of_field1, value is 1
Key is name_of_field2, value is 12
Key is name_of_field3, value is 2
Key is name_of_field4, value is 1
Key is name_of_field5, value is 14
Key is name_of_field6, value is 2015-09-10
and I need to be able to get each particular record fields of each record in order to fill with it some HTML table. How to write this part of code that resolve JSON response consist of two or more records made by PHP? I tried examples I found here but no one met my needs. Thanks.
In your while loop after the DB query, you are just overwriting the value for $data with every iteration. I would suggest not having different logic for cases with one row in result set vs. more than one row, as this does nothing but add complexity to your code. Just return an array every time and you will be better off. Your code around the query might look like this:
$data = array();
$result4 = mysqli_query($con, $query4);
if($result4) {
while($row = mysqli_fetch_assoc($result4) {
$data[] = $row;
}
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
This simplifies this section of code and will also simplify the client-side code since now you can write it to simply expect to work with an array of objects in all cases.
This means that in javascript your code might look like (ajax success handler code shown):
success: function(data, status, jqXHR){
// data is an array, with each array entry holding
// an object representing one record from DB result set
var recordCount = data.length;
console.log(recordCount+' records returned in response.');
// you can iterate through each row like this
for(i=0;i<recordCount;i++) {
// do something with each record
var record = data[i];
// in this example, I am just logging each to console
console.log(record);
// accessing individual properties could be done like
console.log(record.name_of_field1);
console.log(record.name_of_field2);
// and so on...
}
}
You should get in the habit of using console.log() rather than alert() or similar for debugging your javascript, as alert() actually interrupts your javascript code execution and could introduce problems in debugging more complex javascript (particularly when there are asynchronous activities going on). Using the javascript console functionalty built into your browser should be fundamental practice for any javascript developer.

How to create multidimensial arrays with PHP and access with jQuery?

So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.

Putting mySQL Database Information into a JavaScript Array

What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.

Insert retrieved data of image paths via json jquery and insert in img tag src

i m grabbing image paths from MySQL via php and then json_encode and with response data i m using below code to display image but not working
My PHP Code
$imgurl=array();
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl = $row['imgurl'];
}
}
echo json_encode($imgurl);
else
{
echo "No results matching family \"$family\"";
}
The Code at my Jquery side
success: function( data ){
$('#pgwrapid').html(data);
}
the data is giving below output which are actually image paths
["images\/zara\/shoes\/thumbnail","images\/hermes\/shoes\/thumbnail","images\/hermes\/shoes\/thumbnail"]
now how to remove the backslashes and insert it in img src=""
Try Below :
success: function( data ){
$.each(data,function(index,val){
$('#pgwrapid').append("<img src='"+val+"' alt='Thumbnail'/>");
});
}
But please check first if you are getting value in val or not.
You have wrong quotes there. You need to use single quotes for alt='Thumbnail' or escape the double quotes you are already using alt=\"Thumbnail\"
try this code:
success: function( data ){
var evaluateddata = eval('('+data+')');
$.each(evaluateddata,function(index,val){
$('#pgwrapid').append("<img src="+val+" alt="Thumbnail"/>");
});
}
the data is treated as a string after the request, but when it comes json I love to use the hard coded iterative way in javascript (not really fund of using .each() api of jquery so I have a doubt on the above code though not sure if it should be val or should I still identify the variable to access such as val.<variablename>) like this:
success: function( data ){
var evaluateddata = eval('('+data+')');
for(val in evaluateddata)
{
$('#pgwrapid').append("<img src="+evaluateddata[val]+" alt="Thumbnail"/>");
}
}
this is the direct javascript approach to iterate on the json object but it depends on you which one is ideal for you (somehow it would be better if you post the original json string response from your application).
I see the code. how about if you try this code:
if(mysql_num_rows($result) > 0){
//Fetch rows
$output = array();
while($row = mysql_fetch_array($result)){
$output[] = $row['imgurl'];
}
echo json_encode($output);
}else{
echo "No results matching family \"$family\"";
}
your code is actually trying to output a separate json value for each imgurl definitely it won't work because the json value that your application will be returning would be evaluated as one and your code is printing several json values which may cause errors when your javascript code receives it.

Unable to retrieve data using jQuery.post

I'm trying to use jQuery.post() function to retrieve some data. But
i get no output.
I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.
My scriptfile looks like this:
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.
jQuery.post("../functions.php", { storeID: "storeID" },
function(data){
alert(data.name); // To test if I get any output
}, "json");
});
});
My PHP file looks like this:
<?php
inlcude_once('dal.php');
//Get store data, and ouput it as JSON.
function getStoreInformation($storeID)
{
$storeID = "9";//$_GET["storeID"];
$sl = new storeLocator();
$result = $sl->getStoreData($storeID);
while ($row = mysql_fetch_assoc($result)) {
{
$arr[] = $row;
}
$storeData = json_encode($arr);
echo $storeData; //Output JSON data
}
?>
I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.
since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
I don't think I'm passing the storeID parameter correctly. What is the right way?
How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" }
Is the getNameAndTime the name of the function in test.php ?
I have gotten one step further.
I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.
My js script now looks like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data);
}, "text");
});
This results in an alert window which ouputs the store data as string in JSON format.
(because I have changed "json" to "text").
The JSON string looks like this:
[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten#brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]
Now, what I really want, is to ouput the data from JSON.
So I would change "text" to "json" and "alert(data)" to "alert(data.name)".
So now my js script will look like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data.name);
}, "json");
});
Unfortunately, the only output I get, is "Undefined".
And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".
So how do I output the name of teh store?
In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ?
(currently I have hardcoded the storeID, for testing)
Lose the quotes around "storeID":
Wrong:
jQuery.post("../functions.php", { storeID: "storeID" }
Right:
jQuery.post("../functions.php", { storeID: storeID }
bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.
However, a couple more notes:
It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
EDIT As far as your reply, if you break down what you are returning:
[
{
"id":"9",
"name":"Brandstad Byporten",
"street1":"Jernbanetorget",
"street2":null,
"zipcode":"0154",
"city":"Oslo",
"phone":"23362011",
"fax":"22178889",
"www":"http:\\/www.brandstad.no",
"email":"bs.byporten#brandstad.no",
"opening_hours":"Man-Fre 10-21, L",
"active":"pending"
}
]
This is actually an array (the square brackets) containing a single object (the curly braces).
So when you try doing:
alert(data.name);
This is not correct because the object resides as the first element of the array.
alert(data[0].name);
Should work as you expect.
Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]
so this would work.
wrong: alert(data.name);
right: alert(data[0].name);
Hope that helps.
D
Ok, thanks to Darryl, I found the answer.
So here is the functional code for anyone who is wondering about this:
javascript file
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML }, // this.cells[0].innerHTML is the content ofthe first cell in selected table row
function(data){
alert(data[0].name);
}, "json");
});
});
get_storeData.php
<?php
include_once('dal.php');
$storeID = $_POST['storeID']; //Get storeID from jQuery.post parameter
$sl = new storeLocator();
$result = $sl->getStoreData($storeID); //returns dataset from MySQL (SELECT * from MyTale)
while ($row = mysql_fetch_array($result))
{
$data[] = array(
"id"=>($row['id']) ,
"name"=>($row['name']));
}
$storeData = json_encode($data);
echo $storeData;
?>
Thanks for all your help guys!

Categories