JQuery Functions loading prematurely - javascript

What my aim here is when a button is pressed, it replaces the content of the div with a textbox and a button. And when the button is pressed, it posts the text to a script, which handles the request and stores the inputted data from the textbox into the database.
It is then set to call another function called Reset(); which is supposed to restore the old contents of the div. However, the idea that I had in mind it calls the DB Query to find what's CURRENTLY in the database. But, it's not doing that, it's just getting the old value. Which makes me think that the function is running at the start of the page, and not when it is called.
It definitely updates the value because when I refresh the value is updated. Here's my code:
<script>
$(function () {
$('#button').on('click', function(e) {
var myVar = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<div class='span12'><h2>Revision Notes</h2><form id='revisionnotes' name='revisionnotes' method='POST'><textarea style='width:100%;height:290px; padding:10px;' id='notes' name='notes'>" + myVar + "</textarea><br/><button onclick='Button();' name='submit' id='submit' class='btn btn-primary'>Change Revision</button></div></form></div>");
});
});
function Reset() {
var myVar2 = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<h2>What's new?</h2><div class='well'>" + myVar2 + "</div><input type='button' value='Change Revision' id='button' name='button' class='btn btn-primary'>");
});
function Button() {
$('#revisionnotes').on('submit', function(e) {
var data = $(this).serialize();
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: data, // $('form').serialize(),
success: function (data, textStatus, jqXHR) {
Reset();
alert("Delta - POST submission succeeded");
}
});
e.preventDefault();
});
}
</script>
Is there any way to stop the function from retrieving the value from the database until it is called from the Success of the Button function?
Many thanks, Jarrod.

$(function () {
$('#button').on('click', function(e) {
var myVar = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<div class='span12'><h2>Revision Notes</h2><form id='revisionnotes' name='revisionnotes' method='POST'><textarea style='width:100%;height:290px; padding:10px;' id='notes' name='notes'>" + myVar + "</textarea><br/><button onclick='Button();' name='submit' id='submit' class='btn btn-primary'>Change Revision</button></div></form></div>");
});
});
this is not "exactly" a function, it is a closure around a piece of code that runs only once, onload of page.
If u want to load a changing value from your server, you would need to use AJAX, same as u use for the data submission.

Related

Ajax Call in Javascript Function On Button Click

I am getting an error in this code which says Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick.I cannot figure out where i am going wrong.
Here is my code which contains a while loop which fetches data from the database and $xyz goes to the javascript function called myFunction().
Here is my file:
if($rs->num_rows>0)
{
while($row=$rs->fetch_object())
{
$xyz=$row->judged_id;
$my="SELECT DISTINCT first_name,picture from user1 where id='$xyz'";
$hj=$con->query($my);
if($hj->num_rows>0)
{
while($rz=$hj->fetch_object())
{
echo $name=$rz->first_name;
$pic=$rz->picture;
echo"<img src='$pic' height=100 width=100>";
?>
<button type='button' class='egf' onClick="myFunction('xyz')">Chat</button>
<br><br>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var xyz=<?php echo $xyz; ?>;
function myFunction('xyz')
{
$.ajax({
type: 'GET',
url: 'chat/public/01_index.php?id2=xyz',
success: function(data) {
$('.chat-list').html(data);
}
});
});
}
</script>
<?php
}
}
What is the content of the PHP variable $xyz? If it is a string, for example,
this:
var xyz=<?php echo $xyz; ?>;
Would result in a JavaScript like:
var xyz=ABCDEFG;
Which is not valid. Instead it should then be:
var xyz = '<?php echo $xyz; ?>';
Furthermore your function defintion seems not right, should be something like this instead, since you can not specify a string as a parameter name:
function myFunction(varNameHere)
{
alert(varNameHere);
}
Click me
Also you are using jQuery ready() function inside your function, which will probably not fire at anytime.
I think what you are looking for is something like this:
function myFunction(xyz)
{
$.ajax({
type: 'GET',
url: 'https://httpbin.org/get?q=' + xyz,
success: function(data) {
$('.chat-list').html(data.args.q);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
<div class="chat-list">
</div>
First of all: you don 't need jQuery. The jQuery library is just a wrapper written in native javascript. It would be more performant to use native javascript.
After that as I mentioned in the comments, you should use a click event listener on the parent element, which contains all your buttons. Just have a look at the following example.
<div class="parent-element">
<?php
while ($row = $resource->fetch_object())
{
echo '<button id="' . $row->id . '">' . $row->title . '</button>;
}
?>
</div>
<script>
var parent = document.querySelector('.parent-element'),
xhr = new XMLHttpRequest();
parent.addEventListener('click', function( event ) {
let target = event.target;
if (target.tagName.toLower() == 'button' && target.id) {
// your xml http request goes here
xhr.open('GET', yoururl + target.id);
xhr.onload(function() {
if (xhr.status === 200) {
// do something with the response
let response = xhr.responseText;
}
});
xhr.send();
}
}, true);
</script>
The while loop adds the buttons to your HTML markup. Further a click event listener was added to the parent div element. On every click it checks, if the target element is a button and if this button has an id attribute. If so an asynchronous request is executed.

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.

Updating data with Ajax loading does not work

I have an admin page which can insert, update and delete data. I want to display a simple loading gif while doing any of these operations. All of the 3 operations work perfectly, but when I try to make some Ajax with it, it stops working.
Below is my Ajax code. This code simply shows a div which has the loading gif within it, right after submitting the form, and if it's successfully accomplished, hides it again. That easy.
$("#form").submit(function(e) {
e.preventDefault();
$("#loading").show();
$.ajax({
url: "Operations.php",
dataType: "HTML",
success: function() {
$("#loading").hide();
}
});
});
Now, the Operations.php, that is executed by every form, contains the 3 database operations. It stores the name of the class sent by a hidden field, receives the value from the button of the submitted form and depending on its value, it instantiates the ServiceDatabase passing the class and perform one action.
$class = filter_input(INPUT_POST, "class");
$id = filter_input(INPUT_POST, "id");
#require_once "../../php/Connection.php";
#require_once "../../php/ServiceDatabase.php";
#require_once "../../php/" . $class . ".php";
$Operation = new ServiceDatabase($connection, new $class);
switch ($_REQUEST["submit"]) {
case "insert":
$Operation->setPostVariables();
$Operation->insert();
break;
case "update":
$Operation->setPostVariables();
$Operation->update($id);
break;
case "delete":
$Operation->delete($id);
break;
}
And finally, just the form.
<form id="form" class="center-block" action="Operations.php" method="post">
<h3>Alterar - <small><?php echo $class ?></small></h3>
<input type="hidden" value="<?php echo $class ?>" name="class"/>
<input type="hidden" value="<?php echo $id ?>" name="id"/>
<?php echo $Table->generateAdminTables($id); ?>
<button type="submit" name="submit" value="update" class="btn btn-success btn-update">Atualizar</button>
</form>
What happens is that the database operation, in this case, the update, doesn't work, like if it is not reaching the Operations.php file.
You need to set the POST data which you get from the form.
$.ajax({
url: "Operations.php",
method: "POST", // defaults to get
data: $(this).serialize(), // get the form data and send it
dataType: "HTML",
success: function() {
$("#loading").hide();
}
});
It seems $_REQUEST doesn't work with Ajax. What a surprise.
My solution is: I created a new hidden in the forms to receive via jQuery the value of the clicked button:
btnValue = "";
$("#form button").click(function() {
btnValue = $(this).attr("value");
});
Then right before the $.ajax, I set the hidden value:
$(this).find("#action").attr("value", btnValue);
In my Operations.php, a new $_POST value is received
$action = filter_input(INPUT_POST, "action");
And in the switch block, I just check $action
switch ($action) {
case "insert": ...
case "update": ...
case "delete": ...
}
Worked perfectly.
Try this one. I have not tested but it will work.
$("#form").submit(function (e) {
e.preventDefault();
$("#loading").show();
$.ajax({
url: "Operations.php",
dataType: "HTML",
success: function () {
$("#loading").hide();
},
error: function (data) {
},
complete: function (data) {
$("#loading").hide();
//A function to be called when the request finishes
// (after success and error callbacks are executed).
}
});
});

Reload an AJAX loaded page after update

I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.

how can I make one button correspond to different clicked div html jquery php?

You can see my code below. I face a challenge that I don't know how to use one button to correspond different click. On the php, if I put the button inside the foreach loop, it will create a lot of button, that's not what I want. In the js, if I put the on.click button inside the foreach elements loop, it will also create a lot of on.click button, so I click one button, it will run many times depends on the number of label_name. I think about addClass, if I clicked the heart div, I use js to add a class, and then get the attr('id') inside button.on.(click), so I can differentiate them in my server php and mysql can request the correspond data. But the problem is that if a user click every div, then every div add classes, then problem again.
var current_page = 1;
var elements_body = {
"heart": "1",
"eye": "2",
"ear_nose_throat": "3",
"hand_foot_mouth": "4"
};
jQuery.each(elements_body, function (label_name, label_num) {
var disease_label = $('#' + label_name + '_d');
disease_label.on('click', function () {
var data = {
action: 'body_part_keyword', //wordpress loading url
postSearchNonce: MyAjaxSearch.postSearchNonce,
current_page: current_page,
label_name: label_name //this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function (data) {
disease_menu_result.append(data);
current_page++
}
}); //ajax
});
}); //jQuery.each
$('#loadmorebutton_body').on('click', function () {
//I dont know how can I make this button to correspond above code
});
<div id="disease_menu">
<?php
$arr = Array(
'heart'=>'heart',
'eye'=>'eye',
'ear_nose_throat'=>'ear nose throat',
'hand_foot_mouth'=>'hand foot mouth'
);
foreach ($arr as $key=>$value) {
?>
<div class="disease_li" id="disease_li_<?php echo $key;?>">
<span class="disease_span" id="<?php echo $key;?>_d"><label>(<?php echo $value;?>)</label>diseases</span>
</div>
<!--disease_li-->
<?php }?>
</div>
<!--disease_menu-->
<button id="loadmorebutton_body">Load More</button>
Use javascript functions :
function MyFunction() {
jQuery.each( elements_body, function( label_name, label_num) {
var disease_label= $('#'+ label_name + '_d');
disease_label.on('click',function(){
var data={
action: 'body_part_keyword',//wordpress loading url
postSearchNonce : MyAjaxSearch.postSearchNonce,
current_page:current_page,
label_name:label_name//this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data: data,
success: function(data){
disease_menu_result.append(data);
current_page++
}
});//ajax
});
});
}
$('#loadmorebutton_body').on('click',function(){
MyFunction();
}

Categories

Resources