Executing PHP script with button in Javascript - javascript

Here's the break down: My problem is two fold, i want to use a button to call to my php script, which in turn calls to my nodejs script running on my little internal test server (this is all done local for now).
Here is my html + script pull:
<input type="submit" value="Save Sketch" id= "run_system">
</body>
<script>
$('#run_system').on('click', function(){
$.ajax({
url : 'exec.php',
type : "GET"
}).done(function(data){
console.log(data);
});
});
</script>
and here is my php script:
<?php exec('node screenshot.js //place holder url that gets dumped into js file// "); ?>
so my problem is that the previous call to this php is not executing this. Everything i've googled says that this exec("") should run my nodejs script. What am i missing?
I am guessing the type : GET is incorrect, tried not having that line, putting POST in there, nothing seems to work though
Oh one more addition, so when i run the above all it does is print what was in the php file to the console, doesn't actually run the script

One of the issues is that the exec is executing the command, but you're not capturing / returning the output of that command. You can probably add an echo or print before exec to return the output to the AJAX request.
You might also want to bind to the submit event to handle form submissions as well as submit button clicks, but that would be bound to the form itself.
Ultimately though, I would recommend that you contemplate handling this exec by adding a simple HTTP server to your screenshots.js node script (or something that wraps it) and handle the AJAX request with that. Will likely need to add a Access-Control-Allow-Origin exemption.

Related

How to replace php function with ajax

I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

Javascript Value of Variable not updating in Servlet

I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/

run php query in onchange event

I am newbie here and i having difficulty to construct the mysql query in the javascript. The idea is to run the mysql query when the dropdown value change.
Below are the code:
html code
<select name="cmbStatus" id="cmbStatus" onchange="check()">
<option value="All" selected>All</option>
<option value="New">New</option>
<option value="In Progress">In Progress</option>
<option value="Down">Down</option>
<option value="Complete">Complete</option>
</select>
<label>
<input type="text" name="textfield" id="textfield">
</label
JS code
<script>
function check()
{
document.getElementById("textfield").value = document.getElementById("cmbStatus").value;
}
</script>
PHP code
$query="SELECT * FROM incident_ticket where Status = 'cmbstatus.value' ";
$result=mysql_query($query);
$num=mysql_numrows($result);
Php code runs on the server, while javascript (if not server-side javascript) runs on the client.
This means that you can not run php code directly in a javascript function on javascript events, cause its already ran on the server before the page is even loaded on the client.
What is usually used in cases like this, is called AJAX.
With ajax you send a request to a php script on the server (with the data that you wish to update), and in the php script you run the query.
There are a few different javascript libraries that makes sending requests like this easy, most people would probably recommend using jQuery, in which a simple ajax post request would look something like:
$.ajax({
type: "POST",
url: "thephpscript.php",
data: data,
success: function(){/*onsuccess*/}
});
But this would require you to load the jquery library before doing the request. Which is another question and for which i would recommend reading the jquery docs: http://www.jquery.com
Furthermore:
I would really recommend that you do NOT use the mysql_* functions in PHP either.
The mysql_* api is deprecated and will be removed in future versions of php.
The code you got in your example is also open for sql-injections, which is very bad.
Use mysqli or PDO instead, and either escape the data before using it in query or use prepared statements.
The only way to do that is using AJAX (or similar, but with other data encapsulation methods, like JSON), which is a very broad topic. Too broad to be explained here in detail, but I will give an overview.
Basically AJAX (Asynchronous Javascript And XML) is a way of asynchronously requesting server information by using XML encoding. As the name suggest you will be using Javascript. The Javascript API in most browsers provide in this need with the XMLHttpRequest object (or ActiveXObject in older IE's). So lets create a new object:
ajax = new XMLHttpRequest();
This object provides a few methods and fields, but we will only discuss the most important ones: open(), send(), onreadystatechange, readyState, status and responseXML. To load a webpage (can be anything, but usually this is xml or generated xml from a php page, in your example we are reading nothing, but just requesting to trigger a PHP script) we use the open() method, like this (just an example):
ajax.open("GET", "some_php_file.php");
Now we have built a request we can send it:
ajax.send();
Done! This will most likely trigger your PHP script, but if we want to do it right, we should check for any errors by registering a (anonymous) status change function (the onreadystatechange field). This function will be triggered when the status of the request chances (e.x. from LOADING to DONE)
ajax.onreadystatechange = function()
{
if (ajax.readyState != 4 || ajax.status != 200)
{
// Do some error handling, like displaying a user visible error message or something
// The requested information is available as an XML object in the responseXML field
}
}
readyState = 4 means that the file has been requested (state is DONE) and status is the HTTP response status code for success (200 OK).
You can also use the jQuery library, which simplifies this, but implements essentially the same process.
Hope this helps!
You need to use ajax to execute php code when user change dropdown value on html page.
Use Ajax. you cant directly run MySQL from Javascript. What you can do is, on its on change, using ajax transfer it to a different PHP page, where you can run your SQL script
Use ajax to transfer value to a php file and execute query in that php file on changing the select value
$("#cmbStatus").onchange(function(e) {
jQuery.post("runquery.php", {
selcval:$("#cmbStatus").val()
}, function(data, textStatus){
});
});
in runquery.php execute the php code what you want to perform on change of select value like this
$query="SELECT * FROM incident_ticket where Status = '".$_POST['selcval']."' ";
$result=mysql_query($query);
$num=mysql_numrows($result);
As already mentioned, problem is that PHP script runs on the server while JS runs "real-time" in the browser. You're goal can be acomplished quiet easily though.
The idea is that you'll bind the AJAX call to the onchange event. I recommend using jQuery for that.
JS
$('#cmbStatus').change(function() {
$.post("script.php", { value: this.value });
$('#textfield').val(this.value);
});
script.php
$query="SELECT * FROM incident_ticket where Status = '" . $_POST['value'] . "' ";
$result=mysql_query($query);
$num=mysql_numrows($result);
Replace script.php with the valid url of the script.
I didn't test it so you'll maybe need to change something but I think you'll get the idea.

How do I doa Jquery.get on a JS file without executing it?

So I'm trying to make an Ajax request to pull down a js file, just to check the version number recorded inside its comments. However, if I run a jQuery.get, and the file pulled down is a javascript it automatically executes it, when I DON'T want the JS to be executed, I just want to read it and look at parts of the text of the script. How do I alter this:
jQuery.get("somefile.js", function(data) { console.log("Do stuff here.") });
So that I can run that success handler WITHOUT first executing somefile.js?
Set the dataType argument to $.get() to "text" to tell jQuery that the data is a string and it should not guess the type.
$.get("file", function(data) { alert(data) }, "text");
See here: Jquery get javascript file without running

Categories