Hi I am adding dynamic validation to a form on my webpage to stop unnecessary page reloads. The form is for registring an account, and I want to be able to check if the username that the user selects is already taken, however as far as I know I can only retrieve data from mysql in php. How should I go about this?
Use PHP to load a list of existing users into an array when the registration page loads and then use that array to do the Javascript validation.
you can using ajax.
this is function in php:
function check_registration() {
if ($_POST['val']) {
$query = "select user from member where user = '" . $_POST['val'] . "'";
$row = $this->countRow($query);
if ($row > 0) {
echo "user has been taken";
}
}
}
and this is ajax that u can put in html
<script>
$(document).ready(function(){
$('#input1').keyup(function(){
var values = $('#input1').val();
var dataString = 'val='+ values;
$.ajax
({
type: "POST",
url: "http://localhost/authentication/check",
data: dataString,
cache: false,
success: function(html)
{
$("#error1").html(html);
}
});
});
});
</script>
Related
I have a very simple sql query:
case 'getFeedbackIvr':
$idClient = $_GET['idClient'];
$query = "SELECT COUNT(idClient) AS _callsNumber
FROM table
WHERE idClient = {$idClient}";
$callsNumber='_callsNumber'
First, I'm trying to understand if this:
$callsNumber='_callsNumber'
is correct
What I need is that when a field in a php form is filled, query is executed and an Ajax request reads the value in $callsNumber and if this value>0 a field (field) in a php form has to appear, else hidden if $callsNumber=0
After several attempts and searchs I'm doing this (but it's incomplete and that's why I'm making this ask):
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "html",
url: '<?=$requestUrl?>' + "?ivrChoiceId="+$(this).val()+"&qType=getFeedbackIvr",
success: function(data){
$("?").html(data);
},
async:true
$('#field').closest('tr').hide();
if ($callsNumber>0)
{
$('#field').closest('tr').show();
}else{
$('#field').closest('tr').hide();
});
});
});
</script>
I have more than 100 users in my database and all are displaying with a check box.
When user click on check box then Id value will pass to PHP with the help of AJAX and it will display the image of the user.
Above statement is working perfectly because I am passing the single id to PHP.
Now the issue is How can I pass the multiple Id to PHP with the help of AJAX and display the images which are select by the user?
If I checked the single Id then it will display the single image, if I select 2 check box then it will display the two images and up to Three.
I think I have to use SESSION and ARRAY.
Would you help me in this?
<input type="checkbox" value="<?php echo $id;?>" name="display_id" id="display_id" />
AJAX
$(document).ready(function() {
$("[type=checkbox]").click(function() {
var user_id = $(this).val();
$.ajax({
type: "POST",
url: "process", //
data: 'id=' + user_id,
success: function(msg) {
$("#display_id").html("<img src='images/profile/" + msg + "' alt='' />");
},
error: function() {
alert("failure");
}
});
});
});
process
$_SESSION['id_user']=$_POST['id'];
$sql_compare="SELECT * FROM register WHERE Id=".$_SESSION['id_user'];
$compare_query=$conn->query($sql_compare);
if ($compare_query->num_rows > 0) {
while($userdata12=$compare_query->fetch_assoc()){
$compare_pic=$userdata12['profile_pic'];
}
}
echo $compare_pic;
exit();
First you should do this,
arr = [];
$("[type='checkbox']:checked").each(function(){
arr.push($(this).val());
});
Then you should do this,
var params = {
users : arr
};
Then your ajax will be,
$.ajax({
type: "POST",
url: "process", //
data:params,
.
.
.
.
Now check whether all checked user ids are getting on server side. if yes,
Then fetch all data and return it as response back to ajax.
EDIT 1
$sql_compare="SELECT * FROM register WHERE Id IN (".implode(',',$_SESSION['id_user']).")";
i want to make like/unlike system with PHP and jQuery/AJAX..
Here is my form in PHP foreach... Here i have own id's for every form;
<?php foreach ($vid as $var) { ?>
<form class="classform" action="functions/videolike.php" method="post">
<input type="text" name="id" value="<?php echo $var['video_id'];?>">
<button class="submitbuttonclass"type="submit">Like</button>
</form>
<?php } ?>
Here is my Ajax script;
<script>
// this is the id of the submit button
$(".submitbuttonclass").click(function() {
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: $(".classform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
the codes are working but not correctly;
When i click "like" button is working good, i cheked the database, caunting, inserting, deleting , working good...
But I want to make this with AJAX becouse, refreshing page is stopping the video when user watching video if he click the like button. Video is preloading becouse page refresh...
After i add my ajax script its working. But when i am clicking the like button, AJAX is posting to PHP, only the last id in the foreach loop,
THE Question?
How to make AJAX to get all of the id's in PHP foreach loop ??
And this is my videolike.php if you want to check;
<?php
session_start();
if($_POST['id'] && #$_SESSION["userid"]){
require_once "connectdb.php";
$id = $_POST["id"];
$VLcheck = "SELECT count(*) FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
$VLrow = $reslike->fetchColumn();
echo $VLrow;
if ($VLrow > 0){
$VLcheck = "DELETE FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
} else {
$curentsess= $_SESSION["userid"];
$INSlike = $conn->prepare("INSERT INTO videolikes(user_id, liked_vid_id)
VALUES('$curentsess','$id')");
$INSlike->execute();
}} else {die;}
?>
As you have a lot forms with class .classform, so how do you think your script should select the proper one?
The asnwer is - script can't, you should help it). Use .closest function to find closest <form> for a clicked button:
$(".submitbuttonclass").click(function() {
var form = $(this).closest("form");
// or find closest element with class `classform`
//var form = $(this).closest(".classform");
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
I am trying to make a like/dislike system on the posts of my social networking website with each post having an pid(auto-increment). I run a while loop that fetches the post from database and show it and also give an option to like/dislike below each post. I am not using any input radio or checkbox button, instead I have used an icon for which the colour should change when clicked and also an AJAX function is called using onclick event on the same icon.
The AJAX function should go to a file likes.php where the a search is done for the row having that post id and the likes column of that row is updated or incremented by 1 and then the result is returned by echo. All this should work but not working.
The AJAX function takes post id (pid) as a parameter and pass it to likes.php where likes field corresponding to that post id is incremented. The like icon for each post has been assigned an id = post id so as to select that like button which is clicked and for which the post id is passed in AJAX function. The result is returned to a span element having an id = "like"+ post pid.
My code
index.php - to show posts and like button
$q = $conn->prepare("SELECT * FROM posts ORDER BY pid DESC");
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)) {
#my post representation using div and all...
#like/dislike button
<span class=\"right floated\" id=\"like".$row['pid']."\" >
<i id=\"".$row['pid']."\" class=\"heart icon\" onclick=\"like(".$row['pid'].")\"></i>
</span>
}
ajax-function
'a' is a parameter-local variable
<script>
$(document).ready(function(){
function like(a) {
$("#"+a).css('color','red');
$.ajax({
url: "likes.php",
data: ({pid: a}),
type: "POST",
success:function(data){
$("#like"+a).html(data);
},
error:function (){}
});
}
});
}
</script>
likes.php file
<?php
session_start();
include 'db.php';
$j =$_POST['pid'];
$sql = "UPDATE posts SET likes = likes +1 WHERE pid ='" . $j . "'";
$r = $conn->prepare($sql);
$r->execute();
$sql = "SELECT * FROM posts WHERE pid ='" . $j . "'";
$r = $conn->prepare($sql);
$r->execute();
$ry=$r->fetch();
if($r)
{
echo $ry['likes'];
}
?>
Please tell me why doesn't it work; at least it should detect the icon click using onclick but I think even that's not working. The AJAX function is not getting executed as nothing happens on clicking.
The problem here, that you declare the like function inside the document ready so outside of that scope your function is not defined.
Posible solutions:
Declare your function before the document ready scope
Create a var outside of document ready
Use jQuery .click (or .on('click',) instead of the onClick html property to call your function
Declare your function before the document ready scope
script:
function like(a) {
$("#" + a).css('color','red');
$.ajax({
url: "likes.php",
data: {pid: a},
type: "POST",
success:function(data){
$("#like" + a).html(data);
},
error:function (){}
});
}
Create a var outside of document ready
var like;
$(document).ready(function(){
like = function(a) {
$("#" + a).css('color','red');
$.ajax({
url: "likes.php",
data: {pid: a},
type: "POST",
success:function(data){
$("#like"+a).html(data);
},
error:function (){}
});
}
});
(This can cause some problem, because until the document is not ready this function not gonna work)
Use jQuery .click (or .on('click',) instead of the onClick html property to call your function
index.php
<span class=\"right floated\" id=\"like".$row['pid']."\" >
<i id=\"".$row['pid']."\" class=\"heart icon action-like\"></i>
</span>
script
$('.action-like').on('click', function(){
var pid = $(this).attr('id');
$("#" + pid).css('color','red');
$.ajax({
url: "likes.php",
data: {pid: pid},
type: "POST",
success:function(data){
$("#like" + a).html(data);
},
error:function (){}
});
});
This should work. But use mysqli instead mysql and do not pass parameters to a query like you do (read about sql injection). And do not echo long static strings instead close php tag and open when needed to echo out a dynamic data.
I have a function in view used to transfer a value from a text box to a table displayed on a page. Basically it updates the URL and goes into a function called update_verified_phone(). There is another function which is used to update the records using a model named user_info_model() and uses controller named users_info().
Problem is when when I use an AJAX function to post to the controller function named update_verified_phone(), the browser freezes and hangs up. I was wondering why it is happening?
Sorry just new to AJAX.
Here is the code :
$(document).ready(function()
{
$('#btnVerify').click(function(event)
{
event.preventDefault();
var uid = $('#user_id').val();
var verified_phone = $('#textNum').val();
if (isNaN(verified_phone))
{
alert("Please enter only numbers for user verified_phone");
}
else
{
$('#textNum').val('');
//$.post(base_url+'users_info/update_verified_phone', {uid:user_id,verified_phone:textNum}, function(response)
//{
$.ajax
({
type: "POST",
url:base_url+'users_info/update_verified_phone',
data: {uid:user_id,verified_phone:textNum},
//async: true,
dataType: 'json',
success:function(data)
{
if(data)
{
var headingHtml = headingTemplate
({
'verified_phone':data[0].verified_phone,
'verified_timestamp':data[0].verified_time
});
$('.userinfo').html(headingHtml);
$('.userinfo tr td:eq(4)').html(data[0].verified_phone);
$('.userinfo tr td:eq(5)').html(data[0].verified_time);
}
}
});
}
});
});
I think you missed to specify JS variable base_url correct it out. After that once you check your AJAX request URL response by direct hit from browser address bar and check what if issue is there OR not.
Let me know if you require any more information regarding this.
Thanks!
This is pretty difficult but I try to solve it.
Query 1: Insert query with SELECT statement
//If history_verified_phone:id is auto incremental then no need to cover it into INSERT statement so removed.
$instVerified = "INSERT INTO history_verified_phone(lastverified_phone,lastverified_time,verified_phone,verified_time)
SELECT users.verified_phone,users.verified_time,'". $textNum ."',NOW() FROM users WHERE id = '". $user_id ."'";
Query 2: Update query
$updtUser = "UPDATE users SET verified_phone = '" . $textNum . "', verified_time = NOW() WHERE id = '" . $user_id . "'";
Query 3: Select query
$selUser = "SELECT verified_phone,verified_time from users WHERE id = '" . $user_id . "'";
Please replace variable with your query, $instVerified for Query 1, $updtUser for Query 2 and $selUser for Query 3 and after that please check what happen. Because I have some doubt with your given query may failed and that is the reason for issue.
Please let me know what is outcomes here.