Embed javascript in PHP echo - php

echo "<td> + manuf + </td>";
Is this above ever going to work??
I'm pulling results from a mysql db to edit the contents but need the jQuery functionality to edit it, hence the embedded javascript variable...
EDIT:
Sorry for the lack of context, its related to another question i've asked on here Mysql edit users orders they have placed
this is the end goal. To edit the order i place, i need to pull the results into an environment similar to how the user placed the order. So my thinking was to include the jQuery functionality to add items to a cart etc, then they could press submit and in the same way i used .Ajax to post the data to an insert php script i would post the values to an update php script! Is this backwards thinking, any advice welcomed!

I suggest you take a look at the follwing.
json_encode
Ajax
JSONP
Now your simplest solution under you circumstances is to do go for the json_encode method. Let me show you an example:
$json_data = array(
'manuf' => $some_munaf_data
);
echo "<script type=\"text/javascript\">";
echo "var Data = " . json_encode(json_data);
echo "</script>";
This will produce an object called Data, and would look like so:
<script type="text/javascript">
var Data = {
munaf : "You value of $some_munaf_data"
}
</script>
Then when you need the data just use Data.munaf and it will hold the value from the PHP Side.

Try just emitting the MySQL content with PHP:
echo "<td id='manuf'>".$manuf."</td>"
Then get the contents with jQuery like this:
var manuf = $('#manuf').text();

Would you not echo out the jQuery within a Javascript code island? You need the client-based code (jQuery) to be able to execute after the server-side code (PHP).
echo '<td><script language = "JavaScript" type = "text/JavaScript">document.write("");</script></td>';

Is this above ever going to work??
Nope. You'd need to output valid JavaScript for the browser to interpret:
echo "<script>document.write('<td>'+manuf+'</td>')</script>";
But that is a dreadful construct, and I can't really see why you would need this, seeing as the td's contents are likely to be static at first.

Consume you have the table echoed with php:
<table id="sometab">
<tr>
<td>
</td>
<tr>
</table>
The jquery for printing resuls in any td is :nth-child(2) takes 2 table td object :
<script type="text/javascript">
$(function(){
$("#sometab tr td:nth-child(2)").html("bla");
})
</script>

Is "manuf" a JS variable or part of a PHP output e.g. part of generated ?
Basically this can easily be done by:
mysql thru PHP(*I can't put table tag..sorry.):
while($row = mysql_fetch_object($result)) {
echo 'tr';
echo 'td a href="#" class="myres"'.$row->manuf.'/a /td';
echo '/tr';
}
then on your JS just attach a "click" handler
$(function() {
$(".myres").click(function() {
//my update handler...
});
});

i think you cant embed the jquery variable in the php like this .
you just give the class name here from here when edit will be click you will get the variable as in submit click in other questions .

Related

Pass dynamic data from to div to another div on same page

I am stuck in a problem and in need of support from you guys.
My problem is I want to pass a php variable(dynamically called through database in loop) to another div on the same page without page refresh
//This is a loop
<td><a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a></td>
//The div which should get the above php variable
<div class="tabright" id="existingcase">
<?php
$c_id = $_GET['case_id'];
echo $c_id;
?>
</div>
//the javascript code for calling divs on the same page
<script>
$(".linkright").click(function(){
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
});
</script>
It shows in the url like this index.php#existingcase?case_id=2012001 but never passes the case id to #existingcase. And also #existingcase div does not load either but without passing caseid value, #existingcase loads.
Any suggestions would be great.
I think you want to print clicked case_id in div without page load. To do this, you don't want to pass it using url. you can simply achieve it using javascript.
If your div id existingcase is just change your code like this below.
you are printing that same case_id as a text of anchor tag using $row_mycases['case_id'];. So, you can easily get that text using javascript and you can easily print it in your #existingcasediv.
<td><a class="linkright" href="#existingcase"><?php echo $row_mycases['case_id']; ?></a></td>
I don't know about your other scripts. in .linkright click function place this code like this
$(".linkright").click(function(){
$('#existingcase').text($(this).text()); //if your div id is existingcase it will print your case id.
});
try this code. And let me know the result.
SEE THIS FIDDLE DEMO
UPDATED:
To pass client side value to serverside without page reload, you can use jquery.post() method.
Place this PHP code at the top of your page.
<?php
if (isset($_POST['id'])) {
$caseid = $_POST['id'];
return print_r($caseid);
}
?>
$caseid will contain currently clicked case_id value. So, you can use this $caseid wherever you want in this page. If you click on the another case id, it will update with respect to currently clicked case_id
replace your js with below code,
$(".linkright").click(function () {
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
$.post("yourPHPFile.php", { //use your current php file name instead of "yourPHPFile.php"
id: $(this).text()
}, function (caseid) {
$('#existingcase').text(caseid);
});
});
id : $(this).text() means, get the current element .text() and assign it to $_POST variable name of id. It will post to yourPHPFile.php. And you can retrieve that value like $caseid = $_POST['id'];.
In function (caseid) {, caseid contains the value of $caseid. So, only in this code, I assigned $caseid = $_POST['id'];
By this you can directly print clicked case_id text to your #exixtingcase div.
Any values after # are not sent to the server. Since PHP is a server technology you php code will never see the values after #
<a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
try doing
<a class="linkright" href="existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
instead and your php code should fill the div.
In my understanding of your explanation I think you are making a mistake. You are trying to mix Javascript and PHP with out page refresh. This is not possible through your code as PHP is server side and only works on the server. You can't do href within the same page and expect PHP code inside this div to be executed. The PHP code will not be there. You can try "view source" in your browser and check it out.
I think the only way to solve your problem is to make AJAX call using Javascript, get the response and put wherever you want (without refreshing the page)
Hope this helps and excuse my English
EDIT : Here is a working example for making a simple AJAX call using Jquery.
Your table should be some thing like this:
<td>
<a class="linkright" href="#" data-id="<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a>
</td>
You will notice I added "data-id" attribute. We will use this id in our AJAX call. Put this in your JS :
// Create Jquery ajax request
$("a.linkright").click( function() {
$.get("example.php", // Put your php page here
{ case_id : $(this).attr("data-id") }, // Get data, taken from the a tag
function(data) { // Call back function displays the response
$(".tabright").html("<p>" + data + "</p>");
}); // Get
}); // click event
}); // Document Ready
I tested the code and it is working. You will need to customize it to work for you. If all of this AJAX is new to you I suggest these links for you :
http://www.w3schools.com/ajax/default.ASP
http://learn.jquery.com/ajax/

Set the value of a button to equal the answer of an SQL query

My code has a text input and submit button which on return hides that form and displays a new button, which works. The problem I'm having is setting the value of the button (or innerHTML) to the answer in my query (which will always only be one). I have the following code:
echo '<form><button id="HCP_Btn" name="HCP_Btn" style="display:none"></button></form>';
$HCP_num = $_POST['HCP_num'];
$HCP_Query="SELECT * FROM HomeCareProviders WHERE Number='". $HCP_num."'";
$HCP_result= mysql_query($HCP_Query) or die(mysql_error());
if (mysql_num_rows($HCP_result)==0){
echo 'Sorry there are no Home Care Providers with the number entered.';
}
//HCP_Btn.innerHTML='.$row["name"].';
else {
$row = mysql_fetch_array($HCP_result);
echo '<script type="text/javascript">
HCP_Btn.style.display="";
document.form.HCP_Btn.innerHTML='.$row["name"].';
</script>';
}
You can use this Javascript code
echo '<script type="text/javascript">
document.getElementById("HCP_Btn").style.display="";
document.getElementById("HCP_Btn").innerHTML="'.$row["name"].'";
</script>';
For first change it like this
echo '<script type="text/javascript">
//HCP_Btn.style.display="";
document.form.HCP_btn.innerHTML=\''.$row["name"].'\';
</script>';
for second check if $row["name"] gives you the right value and at last check you javascript console for errors.
Also HCP_Btn.style.display=""; mean nothing like this.
The problem is probably because Your button's id is HCP_Btn but in the JS further You are accessing it like HCP_btn - the problem could be small b. Also You are missing quotes for the innerHTML value.
Change the line
document.form.HCP_btn.innerHTML='.$row["name"].';
to
document.form.HCP_Btn.innerHTML="'.$row["name"].'";
^ ^ ^
make the b uppercase add quotes ----------^
EDIT: Have You ever tried jQuery? It is commonly and widely used JavaScript framework that makes JS programming so much easier (after You know it)... With jQuery, You could just do:
echo '<script type="text/javascript">
$("#HCP_Btn").css({"display":""}).html("'.$row['name'].'");
</script>';
How is the information from your JavaScript call returned to the innerHTML itself? When does it get called and changed? I think you should do that first.
You have an user pressing a button. Then you go to the database using PHP (need a new request response for that), with AJAX or JavaScript you could make it work client side.
I think that you are mixing up server side and client side issues. You should at least need a function call on the onClick event to toggle the display of the button and show the information. That onClick event should call a JavaScript function and that will handle the change.

How to highlight ajax loaded table rows?

I'm creating a web page that search users in the database. When I'm typing a username in the search box, it perfectly loads results using Ajax in a table (this table is in another PHP file). But I need to select those rows when I press arrow keys or with mouse over (like Google search engine), when we are pointing to that row, it highlights. I tried with onmouseover function but no luck, but in normal PHP web pages onmouseover works. Here's what I normally used to select rows in a table.
I'll give you a very basic example, that how I use this.
<html>
<head>
<script type="text/javascript">
function f1(x){
document.getElementById(x).style.backgroundColor="#FF0000";<br/>
}
function f2(x){
document.getElementById(x).style.backgroundColor="#FFFFFF";
}
</script>
</head
<body>
<?php
echo "<table border='1'>";
echo "<tr id='tr1' onMouseOver='f1(this.id)' onMouseOut='f2(this.id)'> <td>Elephant</td></tr>";
echo "<tr id='tr2' onMouseOver='f1(this.id)' onMouseOut='f2(this.id)'><td>Snake</td></tr>";
echo "<tr id='tr3' onMouseOver='f1(this.id)' onMouseOut='f2(this.id)'><td>Spider</td></tr>";
echo "</table>";
?>
</body>
</html>
My problem is, this does not work in an Ajax loaded table. Please help me...
The mouseover event doesn't work, because you register the event before inserting the HTML.
The way around it, is by attaching an event handler to the body tag, and then looking at the original source of the element, which is basically what the jquery live method does. That would look like this:
$(".hoverme").live("mouseover mouseout", function(event) {
if ( event.type == "mouseover" ) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
}
});
I'll see if I find the time to edit this answer for the keyboard control stuff too.

grabbing POST values with javascript

Forgive me for asking a seemingly obvious question, but all of my searching is turning up guides on how to create POST values with JS, not how to grab (and utilize) them.
What I want to do:
step1.php -- form POSTing to step2.php
step2.php -- also a form, JS grabs one particular POST value and does some work with it, then updates this new form accordingly
for reasons not worth getting into, the process needs to be a 2 step//2 page process.
The obvious solution is just to do something like:
<script type="text/javascript">
function damn_ugly () {
var shameful = <?php echo $_POST['desiredDatum']; ?>;
do more stuff...
}
</script>
but that seems a bit dirty to me.
Is there a better way? or is that really how I'm supposed to do it?
var postData = <?php echo json_encode($_POST); ?>;
You can obviously change that to include only certain fields from $_POST by passing a custom array to json_encode.
var desiredDatum = <?php echo json_encode($_POST['desiredDatum']); ?>;
There is no nicer way to do it - and using json_encode ensures no matter what's contained in the POST variable nothing will break (at least not during the assignment).
That is how you are supposed to do it, JavaScript cannot access the POST values in another way.
Offcourse you can make it a bit more beautiful: have your php-script put the POST variables in an array, and print the array in JSON format. Now your javascript has the array.
POST values are being sent to the server. Once submitted only the server can work with those values. Your example is pretty much the only option you have to "access" POST values that have been sent to the server in the previous request.
JS has no access to POST values, it can only retrieve GET values. However, since you're using a PHP script and you're able to pass the data to JS - why not give your JS functions data in JSON format? You can use PHP's json_encode function to encode all POST values to JSON that you can use then easily in your JS code.
Try this
On second step Page 2:
Set hidden text box on page:
<input type='hidden' name='text1' id = 'text1' value='<?php echo $_POST['desiredDatum']; ?>' />
Now if you use jQuery the wirite below given code
$(document).ready(function() {
var shameful = $('#text1').val();
});
if not using jQuery Then
var shameful = document.getElementById('text1').value;
I hope this is what you are looking for.

PHP variable as part of a jQuery function doesn't work, but plain text does

I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.

Categories