I am doing a basic jQuery ajax call on a PHP file and I can't seem to figure it out, why it isn't working. Any help is appreciated.
jQuery
<script>
$(document).ready(function(){
$('#approve').click(function(e){
e.preventDefault();
var email=$("email_address").text();
changeTable(email);
});
return false
});
function changeTable(email){
$.ajax({type:"post",
url:"DB_Update.php",
data:{email:email},
success:function(response){
alert(response);
}
});
}
</script>
PHP
$email=$_POST['email'];
updateTableApproval($email);
public function updateTableApproval($email){
$query_string="UPDATE users SET approved = b'1' WHERE email='$email'";
$result=mysqli_query($this->db->connect(),$query_string);
return $result;
}
PHP MAIN
echo "<td id='email_address'>".$email."</td>";
echo "<td id='approve'>"."<input type='radio' ".($row['approved']==1?'checked':'unchecked').">"."</td>;";
You are not returning data back from php function. Change one of this.
updateTableApproval($email); to echo updateTableApproval($email);
OR
return $result; to echo $result;
Related
I use ajax to fetch data from DB. And I chose alert(valData) in success function to test the data, but unlucky nothing return from
ajax. Then I tested
select contact from IDC WHERE id='5';
It works fine in mysql cmd line.
Here is my js code:
var stNum = 5;
$.ajax({
dataType:'json',
type:"POST",
url:"get_ajax_csc.php",
data:{stNum:stNum},
success:function(data)
{
var valData = data;
alert(valData);
$('#stContact').val(data.stCnt);
$('#stPhone').val(data.stPho);
}
});
Here is my html code:
<div class="divFir">
<label>Contact:</label><input type="text" id="stContact" ><br />
<label>Phone:</label><input type="text" id="stPhone" ><br />
</div>
Here is get_ajax_csc.php code:
<?php
if(isset($_POST['stNum']))
{
include("DB.php");
$q=$_POST["stNum"];
$sql="select contact,phone from IDC WHERE id='".$q."';";
$sel = $conn->query($sql);
$arr = $sel->fetch(PDO::FETCH_ASSOC);
$tmpArr = array(
'stCnt'=>$arr['contace'],
'stPho'=>$arr['phone']
);
echo json_encode($tmpArr);
}
if(isset($_POST['htmlCnt']))
{
include("DB.php");
$htcnt=stripslashes(".$_POST['htmlCnt'].");
........
}
?>
Here is DB.php code:
<?php
session_start();
$pwd=$_SESSION['password'];
$user=$_SESSION['user'];
try
{
$conn = new PDO('mysql:host=x.x.x.x;port=3306;dbname=hpc',$user,$pwd);
}
catch (PDOException $e)
{
echo "account or pwd wrong <meta http-equiv='refresh' content='1;url=index.html'>";
exit;
}
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
?>
It seems nothing wrong in my code, but I cann't fetch data from database
I have found that stripslashes() made ajax return nothing. When I shielded this method (//stripslashes()), it worked fine. Why stripslashes can influence my ajax return data?
I found that:
$htcnt=stripslashes(".$_POST['htmlCnt'].");
change to:
$htcnt=stripslashes($_POST['htmlCnt']);
I am using Googles reCaptcha API for form validation.
I have opted to have the submit button show once the validation has been complete by using a little bit of JS.
<?php
if(isset($_POST['Login'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = '6LerNA0UAAAAAEReb9rS5JXjtvNSYlMjKiocUv_O';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true){
//show submit button
echo '<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="visible";
}
</script>';
}
else{ // stay hidden
'<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="hidden";
}
</script>';
}
}
?>
<div id='logDiv' style='visibility:hidden')
<?php
echo $form->add('Login',array('type' => 'submit'));
?>
</div>
Currently, the solution isn't working; when the Captcha is validated the div remains hidden.
Is this a result of a syntax error or have a made a logical error?
What is the bug in my code?
Are there any more robust solutions?
Why not simply use a php condition to show the div? I think your JS isnĀ“t working because you never call myFunction().
Try something like this but it will become complex over time and amount of code:
if(isset($data->success) AND $data->success==true){
$showButton = true;
}
......
if($showButton) { ?>
<div id='logDiv' style='visibility:hidden'
<?php echo $form->add('Login',array('type' => 'submit'));
?> </div> <?php }
......
Or a simple Solution:
if(is_bool($data -> success) && $data -> success){
echo '<div id="logDiv">'.$form->add('Login',array('type' => 'submit')).'</div>';
}
Echo the HTML Elements only if validition was successful otherwise simply dont ouput any HTML for the Div.
Hope this Helps.
I am trying to call a PHP function using AJAX to check if the pressed button is the right button.
But I can't seem to figure it out.
I am using this as <input> code :
<?php
$i=0;
while ($i<4){
?>
<input style="background-color: <?php echo $buttonColors[$i]; ?>" onclick="echoHello(<?php echo $i?>)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php $i=$i+1; } ?>
and I'm trying to call a PHP function when the button is clicked. I tried this :
<script>
function echoHello()
{
alert("<?php hello(); ?>");
}
</script>
<?php
function hello() {
echo "Hello World";
}
?>
This worked so I tried to change this to :
<script>
function echoHello(num)
{
alert("<?php hello(num); ?>");
}
</script>
<?php
function hello($num) {
if($num == 1) {
echo "Correct button!!!";
} else {
echo "WRONG BUTTON";
}
?>
But this didn't seem to work. What am I doing wrong?
I think you have quite some thing mixed up here.
I would suggest just writing out the buttons, and pass the buttons value to the javascript:
<?php
$i=0;
while ($i<4){
?>
<input onclick="echoHello(this.value)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php
$i=$i+1;
} ?>
and then in your javascript (after adding all the jQuery goodness):
function echoHello(btnValue) {
$.ajax({
type: "POST",
url: "formhandler.php",
data: { buttonValue: btnValue }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
The javascript above will send the button value to your 'formhandler.php' page, using AJAX.
In the 'formhandler.php', you could then check what the value of $_POST["buttonValue"] is.
Using your setup, together with jQuery, PHP and JSON, it could be something like this:
function echoHello(btnValue) {
$.getJSON('page.php', {
choice: btnValue
})
.done(function(data) {
// based on $_GET["choice"], your PHP could render some JSON like:
// {"background":"image.jpg","fields":["newValue1", "newValue2", "newValue3"]}
// clear the current html
$("#form").html('');
// load a new background
$('body').css({'background-image':data.background})
// set up the new fields:
$.each(data.fields, function( i, item ) {
$("#form").append('<input type="text" value="' + item + '"/>');
});
});
}
This is just a sample, to give you an idea! It's untested also ;)
This script displaying the dynamic content for once thereafter its not working
Here is the code:
$(document).ready(function(){
$('.getmore').on('click',function(){
var last_id = $(this).attr('id');
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/getmore.php',
data: 'last_id='+last_id,
beforeSend: function(){
$('.getmore').html('<img src="../images/loader.gif" alt="Loading..." />');
},
success: function(data){
$('.getmore').remove();
$('#comments').append(data);
}
});
});
});
Here is the complete php code:
<?php
mysql_connect('localhost','root','') or die('Error... Couldnt connect..');
mysql_select_db('mydb') or die('Error... Couldnt select the Db..');
$records = mysql_query(' SELECT * FROM `compare_post_comments` WHERE `post_id`=37 limit 5 ');
if(mysql_num_rows($records)){
echo '<div id="ajax_comment">';
echo '<ul id="comments">';
while($data = #mysql_fetch_array($records) ){
echo '<li>'.$data['comments'].'</li>';
$last_record = $data['sno'];
}
echo '<li class="getmore" id="'.$last_record.'">Get More</li>';
echo '</ul>';
echo "<span id='cmmnts'></span>";
echo '</div>';
}
?>
getmore.php code
<?php
if( ( isset($_POST['last_id'])!=null ) && $_POST['last_id']!="" ){
$last_id = $_POST['last_id'];
//echo "::".$last_id;
$qry = " SELECT * FROM `compare_post_comments` WHERE `post_id`=37 and sno > ".$last_id." limit 5 ";
//echo "::".$qry;
$comments = mysql_query($qry) or die('Error..');
if( mysql_num_rows($comments) ){
while( $data = mysql_fetch_array($comments) ){
echo "<li>".$data['comments']."</li>";
$last_id=$data['sno'];
}
echo "<li class='getmore' id='".$last_id."'>Get More</li>";
}else{
echo "<li class='nomore'>No More</li>";
}
}else{
echo "<li class='nomore'>No More</li>";
}
?>
ajax call working for once, thereafter its not clickable.
I dont have much knowledge about ajax and javascript, explanation is appreciated.
Try the deferred syntax of on instead:
$(document).on('click', '.getmore', function...
This will survive DOM changes. This answer presumes that your loaded data contains an object with class="getmore", as you are removing it from the DOM on success. If not you need to remove the remove as suggested by NewInTheBusiness, but probably replace it with empty() instead to remove the loading progress.
Note I have recently found problems with the version of on that only takes the event and function. In jQuery 1.10.3 it seems to not be firing when it should.
It's because you remove the getmore class after success.
Remove this line of code:
$('.getmore').remove();
Check your firebug console for any error
Remove this line $('.getmore').remove();
Delegate the click event to the element's static parent or to the document.
Try,
$(document).on("click",'.getmore', function( event ) {
});
Just try live or bind in-place of "on" :
$('.getmore').live('click',function(){
}
or
$('.getmore').bind('click',function(){
}
In my PHP I am returning and updating a online users box however as it Echos each line out I also want it to activate a Jquery function. So if there is data there it will then echo it out and a Jquery function will take place.
example of php code ...
if($count1 > 0) {
foreach (user_list($user_name) as $user){
echo $user . "<br />";
};
echo ;// a message to activate a jquery function called userdisplay;
};
and the jquery code would look something like this...
function userdisplay(){
//do some amazing code like slide picture in from left fade text in at the top etc.
};
(I am not asking for help on the code which the function will do this is just an example)
Many thanks to anyone with an idea of how i should go about this my mind is completely blank.
just echo the call to the jquery function between a <script> tagfor example:
this is the page:
<html>
<head>
<script>
$(document).ready(function(){
//some jquery code here
});
//here is your function
function userdisplay(){
alert("triggered");
}
</script>
</head>
<body>
....
<?php
if($count1 > 0) {
foreach (user_list($user_name) as $user){
echo $user . "<br />";
};
echo "<script>userdisplay();</script>";
};
?>
....
</body>
</html>
if($count1 > 0) {
foreach (user_list($user_name) as $user){
echo $user . '<br />';
};
echo '<script>userdisplay();</script>';
};
You just have to make sure the function userDisplay() has been "echoed" before.