I have a little problem. I want to pass two variables from PHP to $.ajax success function
I have this code written in JS:
$.ajax({
type:"POST",
url:path,
data: "value="+info,
success:function(data,data1)
{
if(data==1)
{
$(id).css("backgroundColor","green");
$(id).attr("readonly","readonly");
$(image).attr("src",data1);
}
else
{
$(id).css("backgroundColor","red");
}
}
});
And my PHP code is :
if(isset($_POST['value']) and !empty($_POST['value']))
{
$result=0;
$image="src/photo1.jpg";
$value=trim($_POST['value']);
if($value=="Abracadabra" or strcmp($value,"Abracadabra")==0)
{
$result=1;
$image="src/abracadabra.jpg";
}
else
{
$result=0;
$image="src/photo1.jpg";
}
echo $result;
echo $image;
}
There, I want to "echo" two variables simultaneously to pass to $.ajax success function.
It is possible ? I don't refer to JSON, I refer only PHP with POST method.
Thank you
the response from php code will be something like:
0src/photo1.jpg
and you will have to parse it with the javascript (probably with regex or substring)
success:function(data,data1) {
var result = data.substring(0,1);
var image = data.substring(1);
// ... your code
}
keep in mind that it could cause you trouble if the $result variable is more than one character long :)
have PHP echo a string like "value1|value2|etc" (or whatever other character(-sequence) is unlikely to wind up in the actual data)
then on the javascript side do a string.split('|') to break the returned string up into a neat little array. you could even do key1:value1|key2:value2
and then use the solution presented here to split the key:value pairs up into an object.
Related
Im trying to print the result of a php function to specific html id or class
the php function is called by a button input
jQuery code:
function myfunction() {
$answer = 'random text <b>' + $radomvar +'more random';
$('#resultline').html($answer);
}
is there an equivalent for the
$('#resultline').html($answer);
in php?
What you're asking doesn't make sense. You can can embed PHP code alongside HTML code and it is processed by the server before the HTTP response is sent back to the client.
Therefore, why not do something like:
<span id="resultline"><?php echo myFunction(); ?></span>
Where myFunction is a PHP function that returns the string you want to embed?
You can write your javascript code in .php file and then use your JavaScript function like this:
function myfunction() {
$answer = 'random text <b>' + '<?php echo myfunc($radomvar); ?>' +'more random';
$('#resultline').html($answer);
}
No there isn't. PHP is server side so after the request is done it can't change the webpage anymore. If you want to do that the only option is an AJAX call with for example JQuery as framework.
You can't do proper DOM Manipulation with PHP. For the purpose of your question, you'd have to use jQuery's ajax function to request the variable value from the backend, and fill the container when you retrieve it.
js script:
jQuery.ajax({
url: 'myfunction.php',
data: {varname: randomvar},
type: 'POST'
}).done(function(response) {
$('#resultline').html(response);
});
myfunction.php
<?php
function myfunction($radomvar) {
$answer = 'random text <b>'. $radomvar .'more random';
return $answer;
}
echo myfunction($_POST['varname']);
Please note that you don't need PHP to interpolate variables in a string. That function doesn't need PHP whatsoever to run. If the only purpose of PHP here is to get $radomvar value, and you're positively sure you want to have PHP in your frontend, then it would suffice to do something like
<script>
function myfunction(radomvar) {
var answer = 'random text <b>' + radomvar +'more random';
$('#resultline').html(answer);
}
var randomvalue='<?php echo $radomvar; ?>';
myfunction(randomvalue);
</script>
Well their is no function equal to that in php, however you can easily achive the same effect rather easy by writing few more lines of code.
<div id="resultline"><?php echo $answer; ?></div>
instead you have to place php echo code where you want printed out on the html page, otherweise you have to use ajax or something else than 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.
Been playing with this for too long now!
I'm using codeigniter.
I am trying to get some data back from an Ajax get request. Simply I want to check a MySQL DB to check if there is some data in there mathcing a given date. A simple true or false will be fine for the return.
Here is my request, followed by the PHP. The PHP does return the correct result into $data, but when it gets back to the Ajax request, the alert(data) is called and shows up as blank... nothing there.
Any ideas what I'm doing wrong?
Thanks
function get_appointment_data(request_date){
$.ajax({
url: 'http://localhost/doctor_today/booking/retrieve_cal_data',
type: 'GET',
data: request_date,
success: function(data){
alert(data);
}
});
}
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
return $data==null;
}
I am not familiar with codeigniter but you must output the result of the function. Instade of 'return' you must use 'echo' to return result to ajax request.
You have to echo the result, otherwise your ajax won't receive a result and the success handler won't execute. Here is what I'm going to use for this case, I'm using the simpler .post function for that task with one key difference - I specify 'json' at end of it which means I'll get a json object as a result from my .post (you can search Google for this). The next key is to use encode the result I wanna get in json format using PHP's json_encode function and echo its result. We don't really need to return a result via the normal 'return' statement. So...
The script:
var url = 'http://example.com/ajax_function';
var data = null;
$.post(url, data, function(data) {
if(data.ok)
alert('Everything is fine!');
else
alert('Ops!');
}, 'json');
The server side:
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
echo json_encode(array('OK' => $data==null));
}
If you call directly the PHP function it should output something like
{ "OK": "true" }
which later on will be translated to an javascript array
data[OK] = true;
which you can use as you wish.
Cheers,
Stan.
P.S. I haven't tested the code but it should pretty work.
So far, I have got the following:
$.getJSON('getinfo.php', { id:id }, parseInfo);
function parseInfo(data) {
$('div#info').fadeOut("fast", function() {
$('div#info').html(data.desc);
}
}
I am able to print the results (data.desc) inside the div#info html tag, but before I do so, I want to format data.desc with my php function. So, basically I want to do something like this,
function parseInfo(data) {
$('div#info').fadeOut("fast", function() {
<?php
$formated = some_php_function(data.desc);
?>
$('div#info').html(<?php echo $formated ?>);
}
}
You won't be able to call a PHP function in the middle of a Javascript function. You'll have to format this value before you send it through as a JSON value, or you'll have to duplicate your PHP function in Javascript and use it client-side.
Like I say, why not do that formatting function within getinfo.php?
Another option would be to write a JavaScript function instead of a PHP one to format your variable. What sort of formatting do you need to do on it?
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!