run php query in onchange event - javascript

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.

Related

Overwrite HTTP REFERER with PHP

I am trying to overwrite custom value to HTTP REFERRER. I got success with javascript but my client want in PHP and i need help in rewriting Javascript to PHP.
JS code :
var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
document.write(document.referrer);
I am trying to rewrite this code in PHP or maybe finding a similar solution with PHP. i tried multiple way to do in PHP. these are some example.
PHP Try 1 :
$reff = new Arr("http://example.com", "http://example.net", "http://example.org");
$randomreff = get($reff, call_method($Math, "floor", to_number(call_method($Math, "random")) * to_number(get($reff, "length"))));
_delete(get($window, "document"), "referrer");
call_method(get($window, "document"), "__defineGetter__", "referrer", new Func(function() use (&$randomreff) {
return $randomreff;
}));
PHP with variable :
$var = 'var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
';
PHP with header referer :
header("Referer: https://www.example.com/");
None of them worked. Help me to rewrite Javascript code or alternative solution with PHP.
You won't be able to do this with PHP exclusively. document.referrer is a DOM property that is set by the browser when the page loads by reading the referrer header on the request. Since the request is generated by the browser you can't really touch it with PHP since that is executed on the server and not in the browser, if you want to execute something in the browser you will need javascript.
In your examples you are just trying to run javascript-code from PHP it seems, and that just won't work. The last sample that sets the referrer-header will set it on the response back from the server, but as I said, referrer is a request variable so it will just be ignored.
The only thing you could do from PHP is to tell the browser to redirect to the page again (by setting the location-header), but as far as I know these days this won't reset the referral-header (if so then redirects from http to https for example would loose it all the time).
I'm not exactly sure are you trying to acomplish here. Setting document.referrer is only valid for the current page and won't affect what the next page sees. If executed early it might fool some tracking scripts at most.

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'

dynamically change select options with php

Okay, so I have this function in PHP that gets an attribute and returns an array. Something like this:
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
Everytime the parent select changes, the function getProvinces() should be executed with the new ID and the arrayWithProvince should be included as options in the child select.
I'm using jquery to handle the events, as I found somewhere. I need to do something like this.
$("#selectCountry").change(function() {
var parent = $(this).val(); //get option value from parent
var prov = <?php echo json_encode($pagina->getProvinces( <PARENT> )); ?>;
list(prov);
My problem is that I don't know how to tell the getProvinces($countryID) php function which is the new value of the parent.
Thanks in advance.
You should use javascript for that in order to refresh part of your page with dynamic content.Below is an example using jquery's ajax function.When the select with id #parent_select changes you call your php script and you append the returned data (the html of the child select in the example) in a div you want.
Javascript part would be something like this:
$("#parent_select").change(function() {
$.ajax({
url: "your_script.php?cid="+$(this).val(),
success: function(html){
$("#child_select_container").append(html);
}
});
});
And your_script.php code would look something like :
<?php
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
$countryID=(int)$_GET['cid'];
$provinces=getProvinces($countryID);
echo '<select id="child_select">';
foreach($provinces as $key=>$province){
echo '<option id="'.$key.'">'.$province.'</option>';
}
echo '</select>;
I havent tested the example.It is just a basic how to example.You should be able to work your way from here.But if you have any problems let me know.
As far as I know, you cannot execute the function without reloading entire page (I mean php should recompile it and pass it to the client).
You should use only JavaScript for that purpose. Store you arraylist in JS code, and validate it once upon form submission (just to be sure).
You need to make an Ajax request to the server.
Look at it this way: Your Javascript/jQuery is running on the client side (web browser) and you PHP is running on your web server.
So to communicate between the browser(jQuery) and the server(PHP) you need to make a Ajax request.
jQuery has a ajax function you could use, your best bet is to do some research on the subject as Ajax is something you will use all the time and understanding how it works is crucial.

Executing PHP script with button in 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.

script tag hack + how do I communicate after the second level of AJAX

I want to provide an embeddable javascript which will get a script from my server . Which in turn will get some details from the user(the page which which has my embeddable js) and put it back onto my server . How do i go about achieving this .
This is the embeddable js i provide .
<script>
(function() {
read="This is the data which is entered by the user";
var istreet = document.createElement('script'); istreet.type = 'text/javascript'; istreet.async = true;
istreet.src = 'http://xyz.com/a.php;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(istreet);
})();
</script>
And this is the code on http://xyz.com/a.php
$('<div id="content"></div>').appendTo('body');
$('#content').html('
Some html to inject to the page\'s dom .
');
$.get("http://xyz.com/process.php?dataToProcess="+read,function(data){
alert(data);
});
But I see that the $.get("http://xyz.com/process.php?dataToProcess="+read,function(data){
// leads to a cross domain ajax request
I do not want to solve the cross domain ajax problem .
I want to be able to communicate between the two parties(the one with the embeddable script and my server) seamlessly .
If all you need to do is a GET request, you can use JSON-P(http://en.wikipedia.org/wiki/JSON#JSONP).
In your JavaScript, the syntax would be something like this:
$.getJSON("http://xyz.com/process.php?dataToProcess=" + encodeURIComponent(read) + "&callback=?",
function(result){
alert(result);
});
The "callback=?" property tells JQuery that this is a JSON-P request. JQuery will substitute some arbitrary string for the "?" (more details here: http://api.jquery.com/jQuery.getJSON/).
To make this work properly, you also need to change your process.php handler. The PHP handler should first read the value of the "callback" query parameter, and then wrap the response in that value.
For example, if $.getJSON() sends the parameter "callback=abcd" to the php page, the php page should return:
abcd({"data": "json object with the result"});
A few things to note:
Be sure to escape any user data you send to the server using encodeURIComponent();
If process.php modifies user data, you should be careful when using GET requests, as that could lead to XSRF attacks (http://en.wikipedia.org/wiki/Cross-site_request_forgery).
I used this the cross domain iframe hack to commmunicate between the two different domain . I recommend reading this
http://softwareas.com/cross-domain-communication-with-iframes

Categories