submitting form with parameter from a link in jquery - javascript

I am trying to save data in database in background through a link, and to give download functionality to that link in front end. but it gives an error.
my script is -
<script>
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(me);
});
function saveData(me){
$.ajax({
type: "POST",
url: "download_counter.php",
data: { client_id: "<? echo $client_id;?>", candidate_id: me }
});
}
});
</script>
this is the link (It looks fine)
<button name="download"></button>
download_counter.php looks like -
<?
if (isset($_POST['candidate_id'])) { // Form has been submitted.
$candidate_id = $_POST['candidate_id'];
$client_id= $_POST['client_id'];
$date = date("Y-m-d");
echo "client - ".$client_id;
echo "candidate - ".$candidate_id;
$query = "INSERT INTO `downloads`(`client_id`, `candidate_id`, `download_date`) VALUES ('".$client_id."', '".$candidate_id."', '".$date."')";
$result = mysql_query($query);
}
?>
when i click the link, it lets download the file but database do not updates.
Please help.

There is an error with passing parameter to function saveData, so your ajax request not occur:
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(data); // was me
});

Check jquery click event handler, which says
// say your selector and click handler is somewhat as in the example
$("some selector").click({param1: "Hello", param2: "World"}, some_function);
// then in the called function, grab the event object and use the parameters like this--
function some_function(event){
alert(event.data.param1);
alert(event.data.param2);
}

database is updating now, but it is not getting value of candidate_id.
i did this -
<script>
$(document).ready(function(){
$("#download").click(function(){
$("#count").hide();
var me = $(this), data = me.data('params');
saveData(data); // was me
});
function saveData(data){
$.ajax({
type: "POST",
url: "counter.php",
data: { client_id: "2", candidate_id: data.ca_id }
});
}
});
</script>

I think on click the data you are reading is a string and in the given format.
And you are passing that as data, but since it is not an valid id,
that value in the database is not updated.
Check this out

Related

Like system using AJAX, jQuery and PHP

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.

How to structure jquery ajax to be flexible to in and outputs?

I have a one-page structured website. I am trying to use Ajax to update my data on user demand.
I am trying to figure out how to structure my ajax code, so that it will be flexible to my in and outputs = I want to run different function depending on the clicked link, and I want to return the right output to the right div.
HTML links:
<a href="#page-a" class="dbLink" data-variable="funcA">
<a href="#page-b" class="dbLink" data-variable="funcB">
<div id="page-a">
<div id="a-result"></div>
</div>
<div id="page-b">
<div id="b-result"></div>
</div>
JS, ajax (I am passing a data-variable along the link to controle the action):
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
dataType: 'json',
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
});
});
functions.php:
include 'dbconnect.php';
function funcA($mysqli){
$result = $mysqli->query("select * from database");
$row = mysqli_fetch_assoc($result);
echo $row['column'];
}
function funcB($mysqli){
$result = $mysqli->query("select * from database2");
$row = mysqli_fetch_assoc($result);
return $row['column'];
}
if (isset($_POST['action'])) {
$resp = null;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#page-a";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#page-b";
break;
default:
break;
}
echo json_encode($resp);
}
add another data-* variable set to the id of the place you want to output the data. To control the format of the returned data provide the dataType option in the ajax options, and of course make sure the pointed to url actually outputs that type of data. dataType It will tell jQuery how to parse the incoming data.
var theContainer = $(this).attr("data-container");
...
dataType:"json" //or text, or xml etc etc
success: function(data){
//if data is upposed to be json
//and datType is set to json
//data will be an object, same with xml
//process data how you need to
$("#"+theContainer).html(whateverYouHaveDone);
}
If you need to control the target of the returned data within your php script then turn your returned data into json and send the selector for the target to it
$resp = new stdClass;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#someContainer";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#someContainer";
break;
default:
break;
}
echo json_encode($resp);
Then in your ajax success
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
And of course set dataType:"json"
To return just the mysql row, do the same thing as above but in the ajax success resp.data will be an object. So just access the properties of resp.data with the column names of the row
success: function(resp){
if(resp.data){
//if say you have a column named "username"
var username = resp.data.username;
}
}
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var target = $(this).attr('href');
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(data){
$(target).html(data);
}
});
});
there are many ways to do this.
I see you have understood the custom data-* attributes. I would add one more attribute: data-target=""
<a href="#page-a" class="dbLink" data-variable="funcA" data-target="a-result">
<a href="#page-b" class="dbLink" data-variable="funcB" data-target="b-result">
<div id="page-a">
<div class="a-result"></div>
</div>
<div id="page-b">
<div class="b-result"></div>
</div>
Then inside your JQuery, you do like you do with your data-variable, only that you add the new data-* attribute:
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var theTarget = $( this ).attr("data-target");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(){
/* Here you have to change the data[] to match the JSON return from your PHP-script. You can of course do it without JSON, but I would use http://www.php.net/manual/en/function.json-encode.php on an array from PHP.*/
$("input[class="+ theTarget +"]").html( data["foo"][0]["bar"] );
}
});
});
If you want to play with a real life example, I made this fiddle for another guy on stack overflow a while back: http://jsfiddle.net/Olavxxx/Mu66h/
Put a number in the left box (like 5006), it's postal codes. The target then is the postal adress in the right input box. The concept is very much the same as you are after, with data-targets.

redirect after alert message not working

this is a snippet of a js file>
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList',
type: 'POST',
data: {id: id, userT: usertype},
success: function(html){
$('[data-id='+id+']').parents('tr').remove();
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
as you can see there is an alert message after deleting a user from a list.
I want to refresh the page after ok on alert message is pressed so i added the line>
window.location.reload();
but it's not working, why is this? how can i fix it?
I've been trying to use alternative to this like
location.href = '....';
window.location = '/some/url';
but nothing seems to work!
this is in my admin.php, the code for deleting user from the database:
public function deleteUserFromList(){
if ((isset($_POST['id']) && (isset($_POST['userT'])))){
$rowId = $_POST['id'];
$userType = $_POST['userT'];
$result = array();
if($userType == 'front'){
$front = UserManager::getInstance()->getUser($rowId);
UserManager::getInstance()->deleteItem($front);
}else{
$back = UserBackManager::getInstance()->getUser($rowId);
UserBackManager::getInstance()->deleteItem($back);
}
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
}
In order to simulate redirect in your browser try to:
Javascript way:
window.location.replace("http://stackoverflow.com");
jQuery way:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
Try this and let me know it it works for you or not.
EDIT:
Inside ajax success. Try to close modal window and try to replace method.
EDIT 2:
Put this part of code inside of your document ready block and check is it fired or not if it is fired it means your form is reloading correctly.
$( window ).unload(function() {
alert( "Bye now!" );
});
Elaborating on #charlietfl's comment, could you try something like this?
Return the count from the ajax script and insert it into your page:
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList', // this returns the user count as data
type: 'POST',
data: {id: id, userT: usertype},
success: function(data){
$('[data-id='+id+']').parents('tr').remove();
$('#countDisplayElement').text(data); // insert new count into current page
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
That would eliminate the need to refresh the page entirely and be a bit more friendly to use.

How to retrieve list of users from mysql in javascript

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>

Jquery post method

I have a jquery post method that sends name , password and email to register.php
function postData()
{
thisBtn = $(this);
parent = $(this).parent();
name = parent.data('name');
password = parent.data('password');
email =parent.data('email');
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) ;
parent.next('#message').html(data);
}
The button that performs the function onclick:
<button onclick = 'postData()' class='regular' name='save'>
However nothing seems to be happening when the button is cicked
Since you call postData with no associated object, inside the function this is the same as window so none of the elements you access are the ones you expect.
Don't use intrinsic event attributes, bind your handlers using JavaScript. Since you are already using jQuery you should use the methods it provides for that.
This syntax looks mangled
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) ;
parent.next('#message').html(data);
// no {} for function, no closing ) for $post, and premature ;
Try
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) {
parent.next('#message').html(data);
});
you have 2 options ...
either pass and object in the onclick :
<button onclick='postData(this)' class='regular' name='save'>
or attach the click handler using jQuery - preferred method when using jQuery :
$('input[name="save"]').click(function() {
// your post code here
}};
there would then be no need for the onclick='postData(this)'
Send the post data like this you will get proper output
name = 'demo';
password = '123456';
email = 'demo#gmail.com';
$.post('register.php',{ 'name': name, 'password': password, 'email': email},function(html){
alert(html);
},"html");
//register.php
echo $_POST['name'];
Use jQuery to bind to the button click as well if you want things to work properly. (EDIT: also, let's use a non-deprecated element)
<input type='button' class='regular' name='save' id='btnPost' value='Post' />
Javascript:
$(document).ready(function() {
$("#btnPost").on("click", function() {
var thisBtn = $(this);
var parent = thisBtn.parent();
// Replacing this by serializing the parent form -
// not sure what parent.data is going to give without seeing the rest
// of the html
// name = parent.data('name');
// password = parent.data('password');
// email =parent.data('email');
$.post('register.php', thisBtn.closest("form").serialize(),
function(data) {
parent.next('#message').html(data);
});
});
});
});
You could try this :
$(document).ready(function(){
var $this = $('id_of_button');
$this.click(function(){
//ajax logic here
$.ajax({
type: 'POST',
url: url,
data: data,//data to send to serverside
success: success, //function to call on success
dataType: dataType//datatype eg.text,json etc.
});
});
});

Categories

Resources