Run PHP from within TPL - javascript

I am trying to modify a module TPL file and face some difficulties.
I have a dropdown list and want to run an SQL query when the user selects an item from the list.
So far I have tried to run a PHP file through Ajax in order to run the query but without any success.
I have seen various examples but can't understand how it should be done.
Nevertheless here is what I have done so far.
This is the code I use on the TPL file:
<select id="statusSelect" onChange="updateStatus({$order.id_order|escape:'html':'UTF-8'})">
<option value="1"> test1 </option>
<option value="2"> test2 </option>
<option value="3"> test3 </option>
</select>
This is the JS function I use to call the PHP file, through Ajax:
<script type="text/javascript">
function updateStatus(order_id_sent)
{
//TEST
//alert(document.getElementsByTagName("option")[selectedIndex].value + " " + order_id_sent);
$.ajax({
url: 'setStatus.php',
type: 'get',
data: 'ajax=true',
success: function()
{
alert("It worked");
}
});
}
</script>
And here is my setStatus.php file which I want to call:
<?php
include_once('../../../../../config/config.inc.php');
include_once('../../../../../init.php');
public function doStuff()
{
echo "alert('test');";
return 1;
}
if ($_GET['ajax'])
{
echo function doStuff();
}
?>

use
$( document ).ready(function() {
$("#statusSelect").change(function(){
statusUpdate($(this).val());
});
}
in your code the name of the function is statusUpdate and in the select you call updateStatus
i wish this can help you

Finally I've got a solution for the problem, by using the following script to run the PHP file.
It seems that I had to import the JQuery from google-apis and use {literal} before and after my script.
Here is the updated javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
{literal}
<script type="text/javascript">
function setStatus(order_id_sent)
{
var selectedIndex = document.getElementById("statusSelect").selectedIndex;
// test
// alert(document.getElementsByTagName("option")[selectedIndex].value + " " + order_id_sent);
var data = document.getElementsByTagName("option")[selectedIndex].value + "-" + order_id_sent;
$.ajax({
data: data,
type: "post",
url: "setStatus.php>",
success: function(data){
alert("data sent" + data);
}
});
}
</script>
{/literal}
And here is my PHP file, which is not complete yet but the point was to run the query and now it works properly.
<?php
include_once('../../../../../config/config.inc.php');
include_once('../../../../../init.php');
include_once('../../../../../classes/Db.php');
if(isset($_REQUEST))
{
error_reporting(E_ALL && ~E_NOTICE);
$words = explode('-', $_POST['data']);
//add code to update db
}
?>

Related

how to use JavaScript variable in php

I have an onClick event in my test.php file:
for($i=0;$i<4;$i++)
<tr><td onclick="testfun(".$i.")"></td></tr>
Script:
<script>
function testfun(i)
return i;
<script>
Now I want to use that $i in PHP to see on which <tr> the mouse is clicked on so I can perform my other functionalities in the PHP file. e.g
<?php echo $i?>
How can I do that? I saw some AJAX tutorials but I didn't get how its gonna work on my code.
in your html add this to your javascript
$('#clickhere').click(function(){
//get value here from your function
// do the ajax
$.ajax({
url: "path/of/your/php/file.php",
dataType: 'JSON',
data: value_that_you_fetch,
type: 'POST',
success: function(data){
// do something here
}
});
});
and don't forget to add a jquery CDN
and in your file.php
<?php
echo $_POST['value_that_you_fetch'];
the rest is up to you.
your php code should be like this
<?php
for($i=0;$i<4;$i++){
?>
<tr><td onclick="testfun(<?php echo $i ?>)"></td></tr>
<?php } ?>
and javascript code
<script>
function testfun(i){
return i;
}
<script>
So, if this is your onClick event handler:
function testfun(i){
return i;
}
The quickest way to get on to the next step is to have it be something like:
function testfun(i){
$.ajax( {
url: "/ajaxtest.php?i=" + i,
type: 'GET',
// ... other options depend on what you want returned.
} );
}
This is a deep rabbit hole your are looking down into here.

How to assign AJAX JSON response to jquery variable?

When some one clicks the category button an AJAX request send to category.php in this php file i am encoding a JSON response.
Jquery Onclick Function
$('#Category').change(function(){
var j;
$.ajax({
url:'categories.php',
success: function(results){
var obj = JSON.parse(status);
alert(obj);
}
});
});
category.php File
<option value="" selected="">Select Sub Category</option>
<option value="Cars">Cars</option>
<option value="Motorbikes & Scooters">Motorbikes & Scooters</option>
$status = array('type' => 'yes');
echo json_encode($status);
Now how to assign yes to a JQuery variable on AJAX success? i tried some codes (in Above JQuery codes) but that didn't work please suggest me a solution.
According to your, you are getting the response from php page in results not in status and results itself is a jquery variable. So change status to results.
$('#Category').change(function () {
var j;
$.ajax({
url: 'categories.php',
success: function (results) {
var obj = JSON.parse(status);
alert(obj);
}
});
});
Fixed this problem.. thanks for the effort guys..
$('#Category').change(function () {
$.ajax({
url: 'categories.php',
success: function (results) {
if (results.indexOf("yes") >= 0) {
var j = 'yes';
alert(j);
}
}
});
});

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

Trying to pass POST from JavaScript to PHP

For a few days now I have been trying to pass a simple POST call to a php script from JavaScript. I've done countless amounts of searching online without any positive results.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function successHandler(location) {
var dataString = '?lat=' + location.coords.latitude + '&long=' + location.coords.longitude + '&accuracy=' + location.coords.accuracy;
alert(dataString);
if (location.coords.latitude == '0') {
} else {
alert("AJAX made");
$.ajax({
type: "POST",
url: "updatepos.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
setTimeout(navigator.geolocation.getCurrentPosition(successHandler),15000);
}
}
function getLocation() {
navigator.geolocation.getCurrentPosition(successHandler);
}
getLocation();
</script>
Above is my JavaScript file. The datastring gets made, and it alerts it out to my browser. No problem there. The problem is, my variables don't get passed to PHP whatsoever.
Here is the PHP that is in the same directory as the JavaScript.
<?php
include 'wp-load.php';
/*global $current_user;
get_currentuserinfo();
echo $current_user->user_login;*/
include('dbconnect.php');
global $current_user;
get_currentuserinfo();
$lat = $_POST['lat'];
$long = $_POST['long'];
$accuracy = $_POST['accuracy'];
/*$lat = $_GET['lat'];
$long = $_GET['long'];
$accuracy = $_GET['accuracy'];*/
$query = "UPDATE ltc_users SET lat='$lat',accuracy=$accuracy,lon='$long' WHERE name='$current_user->user_login'";
mysqli_query($GLOBALS['DB'],$query);
echo mysqli_error($GLOBALS['DB']);
echo $lat;
echo $long;
echo $accuracy;
echo $current_user->user_login;
?>
I may note that before the script would return mysql syntax errors as it was echoed in php due to missing variables. The syntax works if I use the $_GET method and just type in the data into my browser address bar for testing. It just doesn't get the JavaScript variables for whatever reason.
You're passing a string to jquery. When you do that, the string is sent out as-is by jquery. Since it's just a bare string, and not a key:value pair, there's no key for PHP to glom onto and populate $_POST with.
In fact, you shouldn't ever have to manually build a string of key:value pairs for ajax - jquery will take an array/object and do it all for you:
var stuff = {
lat : location.coords.latitude,
long : location.coords.longitude,
accuracy : location.coords.accuracy
}
$.ajax({
data: stuff
});
Here is your code combined with #Marc B
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > </script>
<script type="text/javascript">
function successHandler(location) {
if (location.coords.latitude == '0') {
} else {
alert("AJAX made ");
$.ajax({
type: "POST",
url: "updatepos.php",
data: {
"lat":location.coords.latitude,
"long":location.coords.longitude,
"accuracy":location.coords.accuracy
},
dataType: "json",
async:true,
cache: false,
success: function(html) {
alert(html);
},error: function(a,b,c){
console.log(a.responseText);
}
});
setTimeout(function(){navigator.geolocation.getCurrentPosition(successHandler);},15000);
}
}
function getLocation() {
navigator.geolocation.getCurrentPosition(successHandler);
}
$(function(){
getLocation();
});
</script>
code in jsfiddle http://jsfiddle.net/y7f1vkej/ it seems to be working for me

Select list not getting populated (jQuery Ajax)

Update: Got this working by disabling CodeIgniter Profiler which was interfering with the Ajax success response. I think it adds a div to the JSON response.
I am trying to populate a dependent select box with data from mysql database. The problem is that the dependent select box is not getting populated in spite of getting data in the correct format in response to Ajax request.
Please help me as I am totally clueless about what's happening here. Below is my JavaScript code.
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
$("#cities > option").remove();
var form_data = {
country: $('#country').val(),
csrf_token_name: $.cookie("csrf_cookie_name")
};
$.ajax({
type: "POST",
url: "http://localhost/outlets/get_cities",
data: form_data,
dataType : "JSON",
success: function(cities)
{
$.each(cities,function(id,name)
{
var opt = $('<option />');
opt.val(id);
opt.text(name);
$('#cities').append(opt);
});
}
});
});
});
</script>
And here is the HTML. I am using Codeigniter.
<form id="form">
<?php $cities['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</form>
Here is the controller:
function get_cities(){
$country = $this->input->post('country');
$this->load->model('city');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->city->get_cities($country)));
}
& the Model:
function get_cities($country = NULL){
$this->db->select('id, name');
if($country != NULL){
$this->db->where('countries_id', $country);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->name;
}
return $cities;
}else{
return FALSE;
}
}
Change your ajax success callback to:
success: function (cities) {
for (var id in cities) {
var opt = $('<option />');
opt.val(id);
opt.text(cities[id]);
$('#cities').append(opt);
}
}
Because your ajax result is not a array but an json object.
Alright everyone, I managed to get this working by disabling CodeIgniter Profiler. Codeigniter profiler, that otherwise is a handy tool, breaks javascript on any page with Ajax. If you can't do without profiler, use the solution provided on Making CodeIgniter’s Profiler AJAX compatible

Categories