jQuery AJAX post to PHP everytime a click is fired off - javascript

I want to keep a record of every click that occurs within a specific DIV and child DIVS on page. The client should not be aware of this. Inside of the div is a link to an external website.
Client clicks link inside div > ajax inserts record in db > client is sent to site of link clicked
PHP on page
include('quotemaster/dbmodel.inc.php');
if(isset($_POST['dataString'])) {
clickCounter();
}
PHP Model Function
function clickCounter() {
global $host, $user, $pass, $dbname;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$stmt = $DBH->prepare("INSERT INTO clickcounter (counter) VALUES (1)");
$stmt->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
AJAX POST
$(function() {
$("body").click(function(e) {
if (e.target.id == "results" || $(e.target).parents("#results").size()) {
//alert("Inside div");
ajax_post();
}
});
})
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: dataString });
}
The problem I am having (I think) is that the AJAX post is not being sent. Any ideas? Thanks!

on your PHP you have
if(isset($_POST['dataString'])) {...
you are expecting a parameter named dataString so you can fix it on your javascript ajax_post function with something like
var postData={dataString:true, CC:1}
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: postData });
this way jQuery will create the proper dataString parameter.
Hope this helps

Try changing the POST check to:
if(isset($_POST['CC'])) {
clickCounter();
}
Also, if your DIV contains a link that navigates away from the page, clicking the link may cause the page location to change before the event bubbles down to the body tag. If so, you could try attaching an event to the link which calls preventDefault and therefore allow the event to bubble. If so, you could then detect that the user clicked the link and perform the navigation manually after recording the click. To show code as to how this can be achieved you need to post your full div code (including the link).
To add callbacks to the ajax call:
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({
type: "POST",
url: "tq/--record-events.inc.php",
data: dataString,
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

Related

AJAX won't load new page content without page refresh

I executed an AJAX request to load content into my page. Here's the function I created for this request:
function displayForums() {
var session = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/threads/display_forums.php',
data: 'POST',
data: {session: session},
success: function(data) {
console.log("display successful");
$(data).appendTo("#forums-container");
}
});
}
Then, I call this function I just declared (displayForums()) when the document loads:
$(document).ready(function() {
displayForums();
});
Finally, I have an AJAX call that submits user input from a form into a database.
$("#start-thread-form").on("submit", function(e) {
e.preventDefault();
var forum_title = $("#start-thread-form input").val();
var forum_message = $("#start-thread-form textarea").val();
var id = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/threads/insert_forums.php',
type: 'POST',
data: {forum_title: forum_title, forum_message: forum_message, id: id},
success: function(data) {
console.log(data);
$(".success-msg").append("Thread created successfully" + "<br>").show();
setTimeout(function() {
$(".success-msg").hide();
$(".success-msg").text('');
}, 2000);
$('input[type="text"],textarea').val('');
displayForums();
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
});
The problem is that when the AJAX call that inserts data into the database completes, the original AJAX call doesn't load the new data into the page unless I refresh the page. I tried placing the displayForums() function inside of the success function, but it didn't work. How can I adjust the AJAX calls to load the newly inserted data without refreshing the page?
You run your JavaScript when the submit event of a form fires.
The default behaviour of a form submission is to make an HTTP request to the action and load the response as a new page.
If you don't want the form to submit, then you have to stop it.
$("#start-thread-form").on("submit", function(event) {
event.preventDefault();
$(document).ready(displayForums());
this is WRONG, it should be:
$(document).ready(function() { displayForums() });

AJAX post method working in one area but not another

I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!

Is it possible to load content of page without Refreshing the whole page

Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );

JQUERY/ AJAX Request not going through and conflicts

I have included a contact form in my page. In the same page I have a script that gets prices depending on the value of a dropdown. Now when I try to submit the contact message I have a conflict with the script for prices. Basically it tries to run it and I have no clue why. Also the contact form when submitted never works...I just get a new page to open with URL..?message=blablabla
Any idea what is going wrong?
I am working on Laravel 4.2 and so the route you see redirects to my php function.
Here is the JSfiddle and here is the php code:
public function postSendMessage() {
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span><br><br>";
}
Cancel the click so the form will not submit
$("button#send").click( function(evt){
evt.preventDefault();
New error, form has an id of contact, not a class
data: $('form.contact').serialize(),
needs to be
data: $('form#contact').serialize(),
This is what I do for the same situation
//For your drpbox use this code
$(document).on("change", "#yorDropBoxId", function(){
dropBoxValue=$("#yorDropBoxId").val();
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: {
ObjEvn:"dropBoxEvent",
dropBoxValue: dropBoxValue //You will use $myVar=$_POST["dropBoxValue"] to retrieve the information from javascript
},
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP sent by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//To submit your form use this code. You must use Prevent default if you are using a button or using a <a> link tag to trigger the evenrmrnt
$(document).on("click", "#btn_sendForm", function(e){
e.preventDefault();
var dt={
ObjEvn:"FormEvent",
input1:$("#txt_input1").val(),
input2: $("#txt_input2").val(),
input3: $("#txt_input3").val()
};
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: dt,
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP send by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//In the samePagePHPcript.php you can do this:You will return your information from PHP using json like this
$event = $_POST["ObjEvn"];
if(event==="FormEvent"){//Event to insert in your form
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
elseif(event==="dropBoxEvent"){//Event to your dropbox - if you want
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}

jquery problem with live

I have code like this:
$(".delete").live('click', function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000')
});
});
});
}
});
return false;
});
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
When activated for the first time it is working (when I try to delete message, question is asked and if I say yes, message is deleted). When data again shown, when I click delete it is deleting message without asking. What is the problem?
It looks like you'll have to register the confirm plugin after every ajax load as it isn't using live internally.
Easiest way would be to move the code into its own function and call that inside the load callback and on page load.
function deleteConfirmSetup() {
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
}
$(".delete").live('click', function() {
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000');
deleteConfirmSetup(); // Add function call here
});
});
});
}
});
return false;
});
deleteConfirmSetup(); // Also call function here to setup initially
Clearly the "confirm" plugin doesn't operate with live and instead is using bind.
When the element is added, it doesn't have the confirmation bindings but does have the live ones, so it'll just delete.
You could attempt to re-call the confirm plugin in your success function after the new content is loaded, modify the plugin, do it yourself manually, or find a new plugin that's a bit better thought-out.
I haven't used the confirm plugin, but a slightly irritating hack to make this work as you want might be to do this:
var bindBackup = jQuery.fn.bind;
jQuery.fn.bind = jQuery.fn.live;
before you run .confirm(). Then just restore it afterwards:
jQuery.fn.bind = bindBackup;
I haven't tried it, but the live function doesn't implement bind in it's source, so I don't see a reason why it won't work.

Categories