JQuery post to REST service - javascript

I have looked at a bunch of different Q/A on stack and I can not seem to solve my issue for why my rest interface is not getting called on the button submit. I would appreciate it if you guys could look and see where the issue could be.
The goal is to have a form input values (for now they are hard coded until I get it to work), and submit to change the database they are in via a REST call.
EDIT: On button click, no errors in console, nothing shows up in DB.
<?php
$id = "123456";
$auth = "XYZ123"; //this will change daily
$url = "http://update/this/id/$id"; //this will change based on user
?>
<script >
const URL = <?php echo json_encode($url);?>;
const auth = <?php echo json_encode($auth);?>;
const data = {
"flag":"Y" //in the database flag has a value of N want to change to Y
}
$.ajaxSetup({
headers: {
'auth-key': '${auth}',
'api-version': '1.0',
'Content-Type': 'application/json',
'Accepts': 'application/json',
'Verbosity' : '4'
}
});
$('.btn').click(function(){
$.post(URL, data, function(data, status){
console.log('${data} and status is ${status}')
});
})
</script>
<button type="submit" class="btn">Send it!</button>

The JavaScript executes before the DOM is loaded (<script> tags interrupt the DOM parser). By the time the script executes there is no .btn element yet.
Either
move the script to the end of the body (or at least after the submit button),
or add the event listener after the DOM has been loaded,
or use the global event listener
$(document).on('click', '.btn', function() { ... }

Related

Disabling button breaks php post

I have a button that A) executes a PHP script and B) has a function to hide/show a loading indicator while the script is running.
While the script is running I want to disable the button. The problem I'm running into is that I can disable the button, but this prevents the PHP stuff from running.
Button
<form method="post">
<button id="CheckConnectionBtn" name="CheckConnectionBtn" class="CheckConnectionBtn" button onclick="ShowWaiting()">Test connection</button>
</form>
PHP
<?php
if(isset($_POST['CheckConnectionBtn'])){
$output = shell_exec("/script.sh");
$_SESSION["CONNECTION_CHECK"] = "$output";
}
?>
Function
<script>
function ShowWaiting() {
document.getElementById("loader_id").style.display = "block";
document.getElementById("loader_text_id").style.display = "block";
}
</script>
I tried adding $("#CheckConnectionBtn").attr("disabled", true); to the function but this causes the loader to show up indefinitely, it appears the PHP is not triggered.
I also tried adding a onclick disabled to the button but this only causes a refresh of the page (loader shows up for a sec) and also does not appear to trigger the PHP.
Finally I tried adding
<script>
$("#CheckConnectionBtn").attr("disabled", true);
</script>
To the PHP but this causes a page that doesn't display anything even before clicking the button.
How can I disable the button on click but still trigger the php and my function?
Consider the following code.
$(function() {
function showWaiting() {
$("#loader_id, #loader_text_id").show();
}
function endWaiting() {
$("#loader_id, #loader_text_id").hide()
}
$("#CheckConnectionBtn").click(function() {
var self = $(this);
$.ajax({
url: "this.php",
data: {
CheckConnectionBtn: true
},
method: "POST",
beforeSend: showWaiting,
success: endWaiting
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="CheckConnectionBtn" class="CheckConnectionBtn">Test Connection</button>
Making use of $.ajax(), you can setup the beforeSend callback to start the loading images and then in success callback, turn them off. This does not require a form since it's operating with AJAX. Obviously, replace this.php with the URL of your connection script.
First, replace the button with input type = button,Input attempts to add onclick = "return sub ();"function sub() {document.getElementById('btn').disabled = true;//The ID I'm looking for here is the ID of the input tag//document.forms[0].submit();}

Trigger file_get_html on click using dynamic url each time

On my page I have a list of users. Each user has a profile page on an external site (not the same domain name). To save my client updating their profile details in 2 places, I am using PHP simple HTML Dom Parser. This gets the content of the users external profile page and returns it on my site.
What I am trying to do is load the users profile information into a div on my site only when the users name is clicked.
Each user looks like this:
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="http://placehold.it/500x500" />
</div>
To get the contents of the external page I use this code:
$html = file_get_html('http://www.spotlight.com/5094-1276-6177');
echo $html->find('div.credits', 0);
Obviously this works at the minute as it is hard coded. However I need to make it dynamic so that the external profile info for each user is loaded when the relevant user is clicked.
Update from answer below:
I added this script to the top of the user list:
<script>
jQuery(function ($) {
$(".actor_container").load(function () {
return "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url");
});
});
</script>
then in my.php
<?php
$html = file_get_html($_GET["url"]);
echo $html->find('div.credits', 0);
Currently, when I click on a user, nothing happens
UPDATE
OK I've moved to using AJAX to access my.php. Here is what I have so far:
<script>
jQuery(document).ready(function ($) {
$('.nial_actor').on("click", function (e) {
e.preventDefault();
$.ajax({
url: "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url"),
type: 'GET',
success: function(res) {
var data = $.parseHTML(res);
// append all data
$('#all_data').append(data);
}
});
}); //on
}); // ready
</script>
However this returns the following error:
GET http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=undefined 500 (Internal Server Error)
So for some reason the url in data-url is not adding to the end of my ajax url. Have I missed something obvious?
Something like this works?
$(function () {
$(".actor_container").load(function () {
return "my.php?url=" + $(this).data("url");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="...actor profile img..." />
</div>
And in the PHP file, you can add url as your GET param:
$html = file_get_html($_GET["url"]);
Note that there are lots of vulnerabilities in this methods. Keep this just as a guidance.

how get a php value inside a self-invoked jquery function?

I have a page that generates n links in a foreach loop:
...some html and php code
<?php foreach ($tables as $table):?>
... some elements generated ...
<td><a onclick="setPortalId(<?php echo $table['id']?>);$('#fileupload').trigger('click');" class="btn-success btn-sm"><i class="icon-plus white bigger-125"></i>Add / Change</a></td>
... another elements ...
<?php endforeach;?>
As you can see, the onclick event in each link execute 2 js functions,the first sets a js var with the php value $table['id'] because i will need this value to determine my zend route and the last function trigges the input fileUpload of the type file:
<input id="fileupload" type="file" class="hidden" multiple="" name="files[]">
and in the scripts i have this:
<script src="/js/vendor/jquery.ui.widget.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="/js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="/js/jquery.fileupload.js"></script>
<!-- Bootstrap JS is not required, but included for the responsive demo navigation -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
var idPortal;
function setPortalId(valor) {
idPortal = valor;
}
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '/precos/upload/id/'+ idPortal;
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name + " adicionado").appendTo('#files');
window.alert(file.name + " Adicionado.");
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
My question is how I can get the idPortal of the clicked link in the last self-invoqued funtion?Any sugestions?
This is horrible design. You should try to keep your JS as unobtrusive as possible, ie. don't use event handler attributes like onclick. Attach the event handler via JS. There are times when this is impractical but I don't see any evidence that that is the case here.
What I would do on the PHP side is to add some classes and a data attribute that I can hook in to from JS:
<?php foreach ($tables as $table):?>
<td>
<a data-portal-id="<?php echo $table['id']?>" class="btn-success btn-sm btn-upload"><i class="icon-plus white bigger-125"></i>Add / Change</a>
</td>
<?php endforeach;?>
Now on the JS side I would simply read the data-portal-id from the clicked link, use it to set the URL on the file uploader, and then trigger the click to begin the upload workflow:
$(selectorForTheTable).on('click', 'a[data-portal-id].btn-upload', function (e) {
// pull the portalId from the link's data-portal-id attribute
var portalId = $(this).data('portalId'),
$uploader = $('#fileupload');
// set the url for the upload based on out portalId
$uploader.fileupload('option', 'url', '/precos/upload/id/'+ portalId);
// invoke the click
$('#fileupload').trigger('click');
});
The one thing missing here is that you might want to set something up so that when the uploader is closed or all the uploads complete the URL is set back to null or a URL of no consequence. This would help to ensure something going wrong on the client cant mistakenly upload files to the wrong endpoint.
Here is an example Fiddle that works as much as a Fiddle can :-)
You need to make your url global and update it later in that context. Use it like
var idPortal;
var url;
function setPortalId(valor) {
idPortal = valor;
url = '/precos/upload/id/'+ idPortal;
}
The easiest approach to seperate PHP (serverside business logic) and Javascript (non-business critical GUI enhencement), is to put all variables from PHP into the DOM and then later work with it:
<script>
var phpValues = <?php echo json_encode($yourPhpValuesArrayOrObject); ?>;
</script>
....
<script>
The attributes connected with business data from inside the HTML (=semantic structure) should go with a data-* attribute as already mentioned.
You're setting url when the page is first loaded, not after the user clicks on the link. Add that to the setPortalId function:
function setPortalId(valor) {
idPortal = valor;
url = '/precos/upload/id/'+ idPortal;
}
thank you everyone,but I used another approach to get the correct value of the clicked element.like was said,the function is self-invoked in the page loading,so in this moment the global var still null.I as using the blueimp jquery file upload,so reading the documentation I saw that is possible send another values during the ajax request just adding news inputs in the form.with this I solved my problem.

wordpress/php: create an upvote button that does not refresh page

Beginning developer here, making a website using wordpress as a platform. I would like the user to be able to click an upvote button and upvote a post without refreshing the page. I figure I should probably use javascript to highlight the button once clicked as well as change the vote number. However, I am having trouble figuring out how to run a php script (to update the database) without refreshing the page.
Thanks in advance,
sample upvote php for posts add this to your functions file....
add_action('wp_ajax_upvote', 'upvote');
add_action('wp_ajax_nopriv_upvote', 'upvote');
function upvote() {
$postid= $_POST['id'];
$direction = $_POST['direction'];
$votes= get_post_meta($postid, '_votes', true);
if($direction='down') {
$votes--;
} else {
$votes++;
}
update_post_meta($postid, '_votes', $votes);
echo $votes;
exit();
}
The above needs security like any form submit of $_POST variables. Dont leave these out in your code!!
jQuery Code
jQuery(document).ready(function($){
$('.arrow').click(function(){ //if your upvote has class arrow?
//you need someway of passing postid to here!
//if you want up / downvote -- logic needed here, if not remove direction from below!
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'upvote',
id: id,
direction: direction //remove if not needed
},
success: function (output) { //do something with returned data
console.log(output);
jQuery('#postupvote').text(output); //write to correct id - maybe use postid in the id of the vote count on the page e.g. id="vote23" jQuery('#vote'+postid)
}
});
});
})
google wordpress ajax for more information

Animate on table that is generated dynamically

I want to apply a plugin on a certain table that is being generated dynamically through a php script. This is the plugin : CLICK
Now from what i read in the comments i should You first need some form of server side component, say a PHP script, which generates the html table from the data in the database. Then pass the URL of this PHP script into a jQuery ajax call. In the "success" callback, set the innerHTML of some holding div to the response of the ajax call, then select this newly created DOM table element and put it into the plugin.
Hope that makes sense!
Here's what i got so far.
HTML
<div class="testin">
<script>
testin();
</script>
</div>
JS
function testin(){
var load = $.get('functions.php',{gameNo:"1",function:"testin"});
$(".testin").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".testin").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".testin").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
php
if($_GET['function']=="testin")
{
echo '<table class="template" style="display:none"><thead><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr></thead><tbody></tbody></table>';
$gamenumber = $_GET['gameNo'];
echo'<table border="1" class="actualTable"><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr>';
$sql = mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gamenumber' ORDER BY round_name")
or die(mysql_error());
$i=1;
while($row = mysql_fetch_array($sql))
{
$tempSnumber = getcurrentshot($row['round_id'],$row['player_id']);
echo'<tr>';
echo'<td>'.$gamenumber.'</td>';
echo'<td>'.$row['round_name'].'</td>';
echo'<td>'.$row['player_id'].'</td>';
echo'<td>'.$row['target_name'].'</td>';
echo'<td>'.$tempSnumber.'</td>';
echo'<td>'.$row['round_score'].'</td>';
echo'<td>'.$i.'</td>';
echo'</tr>';
$i++;
}
echo'</table>';
}
The function fills the div just fine. I also create the template table in the php script.
Now my problem is how to invoke the plugin and what should i pass ass objects?
Invocation is like $(oldTableElement).rankingTableUpdate(newTableElement) but i'm confused due to the fact that it's being generated dynamically.
I'm new to JS so any help would be appreciated.
First off, I would put your javascript outside the div with class "testin".
Below you JS function you can add the jquery call like in the code below.
See this link for more info: http://api.jquery.com/on/
$(document).ready(function(){
$("table tr").on( "click", function() {
//your custom code goes here.
});
});
What this does is make sure then any element that matches the "table tr" will get an click handler, no matter when it gets created.

Categories