Show php variable value in confirmation box in php - javascript

I have following code i want to show name that is the result of the query.
function lead_delete(del_id)
{
<?php
$lead_name = mysql_query("select lead_name from business_lead where id=" .
$del_id) Or die(mysql_error());
while ($nt_lead_name = mysql_fetch_array($lead_name)) {
$crm_lead_name = $nt_lead_status['lead_name'];
}
?>
var name=<?php $crm_lead_name; ?>;
var confirmation;
var confirmation=confirm("You Really want to Detele Leader "+name );
}
</script>
how can i print the name that get from above query...

You can't use <?php echo $del_id;?> tag in this function (because you may change del_id when call function), but you can create del_id on your page, if you have $del_id php value:
<script type="text/javascript">
var del_id = <?php echo $del_id;?>;
function lead_delete(del_id) {
var confirmation;
var confirmation=confirm("You Really want to Detele Leader " + del_id);
if(confirmation==true)
{
return true;
}
else
{
return false;
}
}
</script>

If del_id is php variable then it should be $del_id instead of del_id
var confirmation=confirm("You Really want to Detele Leader "+ <?php echo $del_id;?>);
As you passing del_id as a function parameter then no need to use php . you can easily get variable like below
var confirmation=confirm("You Really want to Detele Leader " + del_id);
As per updated question:-
var name=<?php $crm_lead_name;?>;
it should be
var name= '<?php echo $crm_lead_name;?>';
And also you want pass del_id lead_delete() function on click event then you have to use AJAX here.
For your reference
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php

Related

Change Jquery variables to PHP

I need to put a Javascript variable into php variable, I dont know how to do that. Possible answers are appreciatable.
<script type="text/javascript">
$(document).ready(function(){
$('#number_of_inwards,#number_of_outwards').each(function(){
var product_name,total_stock;
$('#product_name').change(function(){
product_id = $('#product_name').val();
});
var hello = "13";
<?php $d = '<script>hello</script>' ?>
total_stock = <?php echo $st[$d]; ?>;
console.log(total_stock);
$(this).focusout(function(){
var inward = parseInt($('#number_of_inwards').val());
var outward = parseInt($('#number_of_outwards').val());
$('#overall_stock').val(parseInt(inward+outward));
console.log("Inside the Loop"+ inward + outward);
})
})
});
</script>
Here from the code.I added dummy variable
hello="13"
And tried to get it into php variable but It won't work, It returns empty value.
Thanks in advance

PHP MySQL JS AJAX - Loop issue

I have PHP loop. I take the id, lat, lon data from record, passed it to script to do some calculations, then I passed this data to AJAX which will save the results of that calculation in MySQL DB, if it's successful then it will add the line of confirmation text to a results div.
My Code (I did trim it to keep focus on the issue)
<div id="distance_results"></div>
<?php
$result = $mysqli->query("SELECT * FROM test")
while($row = $result->fetch_array()) {
$id = $row['id'];
$city = $row['city'];
$lat = $row['lat'];
$lon = $row['lon'];
$driving_from = "51.528308,-0.3817765";
$driving_to = "$lat,$lon";
?>
<script>
var id = '<?php echo $id ?>';
var city = '<?php echo $city ?>';
var start = '<?php echo $driving_from ?>';
var end = '<?php echo $driving_to ?>';
// code
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// code
var mi = response.routes[0].legs[0].distance.value;
console.log(id);
console.log(city);
console.log(mi);
//Ajax Begin
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {'updateid': id, 'distance': mi},
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
}
});
//Ajax End
} else {}
});
</script>
<?php } ?>
AND CODE FOR "test-dc-upd.php"
$id = $_POST['updateid'];
$distance = $_POST['distance'];
$result = $mysqli->query("UPDATE test SET distance='$distance' WHERE id='$id' LIMIT 1");
So PHP is looping thru MySQL DB, when but when I look at console:
'mi' values are calculated well according to lat / lon;
PROBLEMS:
1) 'id' and 'city' values stay the same (values of last record in the loop);
2) AJAX is updating value of last record in the loop only
So it obvious there is a some issue with the loop.
Any suggestion to what i do wrong?
Change this
$("<p>"+ html +"</p>").append("#distance_results");
To
$("#distance_results").append("<p>"+ html +"</p>");
Your jquery code is wrong. First you have to put selector and in append function the html code.
Nita, change the success function from:
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("<p>"+ html +"</p>").append("#distance_results");
}
});
To
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("#distance_results").append(<p>"+ html +"</p>);
// this will append the dynamic content to #distance_results
}
});
Explanation:
To put a dynamic content is some html object you have to first prepare
the content than select the html object and put the content into it.
In a loop calling ajax request is not a good practice we can easily pass array of values to javascript using the function implode like this
this implode function is for single dimensional array,
var ar = <?php echo '["' . implode('", "', $ar) . '"]' ?>;
For your question you need to create a multi dimensional array for the result like this ..
<?php
$result = $mysqli->query("SELECT * FROM test");
$arr= array();
while($row = $result->fetch_array()) {
$arr[]=array('id'=>$row['id'],'city'=>$row['city],'lat'=>$row['lat']...etc);
}
?>
afetr that you can pass each item in the array to javascript like this
var idArray= <?php echo '["' . implode(', ', array_column($arr, 'id')); . '"]' ?>;
var cityArray= <?php echo '["' . implode(', ', array_column($arr, 'city')); . '"]' ?>;
you can get each tag as array in javascript after that using a sing ajax request pass all javascript array to php script. and manipulate in the server side .
Your ajax request is like this
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {
'idArray':idArray,
'cityArray':cityArray, //etc you need pass all array like this
},
success: function(data) {
// your success code goes here
}
});
Note that array_column() function only supported by php 5.3 or above
I manage to do it a little different way i was hoping for ( But distance and travel time has been calculate for more then 3000 locations).
So what i did is to make sure mysql (test-dc.php) finds record where distance and travel time has not been calculated, makes calculation, update record with Ajax. Ajax on succesion opens the (test-dc.php) again, And is looping thru all results till there is nothing else to calculate. Had to refesh few times but thats fine, job done.
Adjustment to Mysql query:
$result = $mysqli->query("SELECT * FROM test WHERE distance='' LIMIT 1")
and to AJAX:
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
location.href = "test-dc.php"
}
So that did the trick, but i still belive there is a better way of achiving the same result, i will be happy if someone could help me to figure it out.

Ajax function on button press

I am trying to get information to post via PHP on button click, everything in my code looks right, and when I view the page source everything is filled in the way it should be. When I pull up the debugger when the button is clicked it does not make any calls at all, here is my button
<button type="button">Continue</button>
here is my ajax call
$(document).ready(function() {
$("button").click(function(){
var Id = <?php echo $give ?>;
var Ids = <?php echo $rec ?>;
var ex = <?php echo $exchange ?>;
var ret = <?php echo $tost ?>;
var email = <?php echo $email ?>;
var name = <?php echo $name ?>;
var pe = <?php echo $pe ?>;
var re = <?php echo $re ?>;
$.post("postts.php", {
Id: Id,
Ids: Ids,
ex: ex,
ret: ret,
email: email,
name: name,
pe: pe,
re: re
}, function(data){
alert(data);
$("p").text(data);
}, 'json' );
});
});
all of my vars will populate with the correct information, I just don't know why when I click the button it does nothing. I am not sure if I have made a typo, or if my syntax is wrong, this is only the second time I have done something like this.
You have error in writing variable values from PHP to JavaScript, you must wrap PHP output by quotation marks, so JavaScipt will "see" string ;)
instead of:
var email = <?php echo $email ?>;
write:
var mail = '<?php echo $email ?>';

Unable to show php variable in javascript?

I am unable to show php variable in javascript;
this is my code here:
<script type="text/javascript">
$(document).ready(function (){
var n=<?php echo json_encode($count)?>;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('wrapper').appendChild(div);
<?php
$query="select * from shop_product where shop_uniqueid='$unq'";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$product=$row["in_product"];
?>
var product=<?php echo $product?>;
$('#'+div.id).html(product);
<?php
}
?>
}//for loop ends
});//ready ends
</script>
here i am trying to pass var product in html() of which value is coming from php like: var product=<?php echo $product?>;
but when doing so php value is not coming in Javascript's var product.
when I pass $('#'+div.id).html("abcd"); abcd value is showing in divs.
please help me.
Compare the first place you take data from PHP and put it in JavaScript:
var n=<?php echo json_encode($count)?>;
with your attempt to assign the product value:
var product=<?php echo $product?>;
You haven't converted the data from plain text to JavaScript in the second line. Use json_encode there too.

delete sql row after echo onClick

I am making a program for a quiz show in our school programme. I have a table that contains WHO asked the question (among the teachers), WHAT is the question and another table as to what the answer to that question is. So, I have a table with THREE COLUMNS.
Now, what I was trying to do is that when the page loads, it will display a number of links labeled . I echoed each link such that when you click any of them, a random row will be taken from MySQL table and the "Question" as well as who asked that particular question will be displayed publicly.
so far, i was able to do all that just fine. But here's the problem.
I want to do it in such a way that after clicking the question, (after displaying it, to be exact,) that specific row will be DELETED from the MySQL table. I didn't want to use a timer because the time allotted for each question differs. I was wondering if there is some kind of "after click" function (or some way to do it) in javascript and AJAX. or perhaps a PHP code?
sorry for the noobish question. History teacher here. :)
by the way, here is a part of my code:
<?php
$checkrow = $db->query("SELECT * FROM questions WHERE `who` = $teachers");
while ($row = $checkrow->fetch(PDO::FETCH_ASSOC))
{
$who = $row['who'];
$question = $row['question'];
$date =$row['date_asked'];
$ask = $db->query("SELECT COUNT(*) FROM teachers WHERE science = $from AND who = $teachers");
$count = $ask->fetch(PDO::FETCH_NUM);
if($count[0] == 0) {
echo ' MYSTERY QUESTION ';
$fromwho = "From science Department.";
echo "<br>";
} else {
echo ' MYSTERY QUESTION ';
$fromwho = "From your Arts Department.";
echo "<br>";
}
}
?>
and here is my javascript.
<script language="javascript">
function readmsg(){
var qst = "<?php echo $question; ?>";
var dte = "<?php echo $date; ?>";
var frm = "<?php echo $fromwho; ?>";
document.getElementById("displaymsg1").textContent = qst;
document.getElementById("displaymsg2").textContent = dte;
document.getElementById("displaymsg3").textContent = frm;
}
</script>
1st, you have to make page delete_question.php (or method like this):
<?php
$db->query(('DELETE FROM questions WHERE ID=' . $_GET['uid']); // make it safer
echo '{result:"done"}';
?>
2nd, make delete onclick handler function with ajax sends UID to specified
function delete_question(el) {
$.ajax({
url : 'delete_question.php',
dataType : 'json',
data : {
uid : el.dataset.uid
},
success : function(response) {
// remove line?
$(el).parent().remove();
alert(response.result);
}
});
3nd: add handler to element
<a href="#" onclick="delete_question(this)" data-uid="<?php echo $row['ID'] ?>">

Categories

Resources