Run PHP with jQuery and use variable - javascript

I'm making a website where you can find manuals of different brands of cars.
I have a table with ID, NAME, LINK, and CATEGORY. I want that if you click the DIV with the attribute "ford", you select all from the table where category is ford. This is my code:
jQuery
$('div').click(function(){
var cat = $(this).attr('category');
});
and the SQL:
$connect = new PDO('mysql:host=localhost;dbname=manuals', 'root','');
$cmd = $connect -> query("SELECT * FROM `manuals` WHERE `category`='ford'");
$resultado = $cmd->fetchAll(PDO::FETCH_ASSOC);
I know that PHP is a server side language and JS not, and JS is event driven, and all the story, but what is the easiest way to achieve this? Do I need to use forms and stuff?
Sorry for bad english!

Use an $.ajax or $.post call and pass in the variable as a post (or get) variable.

U can use AJAX() to get HTTP communication with PHP in backend.
see more in [link]http://api.jquery.com/jQuery.ajax/

Related

If the PHP variable change, update div by using Ajax

I want to update a div by via Ajax if a php variable changes. My setup looks like this:
I'm using 2 files:
index.php (displays the div that needs updating):
<?php include('variables.php?>
<div id="apples">
Apples: <php echo "$applescount"; ?>
</div>
<div id="oranges">
Oranges: <php echo "$orangescount"; ?>
</div>
variables.php (where the variables are defined)
$applescount = 2 (ex: value obtained from db)
$orangescount = 3 (ex: value obtained from db)
I need a simple jQuery function that checks if the variables ($applescount or $orangescount) change and then updates the divs (apples and oranges respectively).
Create an javascript interval that makes an AJAX request every few seconds to your back end, return the results as JSON. Parse the JSON in the front end to update to user interface.
Might want to consider making this using javascripts new 'promise' system.
PHP does not allow two-way data binding without polling.
You could consider creating a socket connection that 'connects' to something on your backend, then there might be a library that can integrate with your database to notify of certain values changing, not sure if this would be with PHP though.
Something like this:
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
Try this.
$.post('update.php', function(response) {
$('#apples').text(response.apples);
$('#oranges').text(response.oranges);
});
While this seems to be on the right track... you should use a medium PHP handler to handle whatever you wish to do with the data.
This is the general direction (you need jquery to be loaded)
HTML
Apples : <span id="apples"></span>
Oranges : <span id="oranges"></span>
JS
$.post('handler.php',function(data){
$('#apples').html(data.apples);
$('#oranges').html(data.oranges);
})
PHP - handler.php
<?php
// get from db etc...
$apples = get_from_db();
$oranges = get_from_db();
echo json_encode([
"apples" => $apples,
"oranges" => $oranges
]);
?>
The JS will call PHP and the response should come back in an object.
if you wish a non-jquery version you should look into youmightnotneedjquery.com

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.

How to use php inside of javascript?

I am using javascript to retrieve a bunch of values from the Riot API, however I want to store them in my own database using php. For example, I'm trying to store the gameID and this is what I'm trying right now.
<?php
$insrt = "INSERT INTO game (gameId)
VALUES (".<script>b.gameId</script>.")";
mysqli_query($dbc, $insrt);
?>
I'm pretty sure that I'm not even close to correct but I'm not sure how to do this.
You need to take a different approach. You can make an ajax call to a php script to do this for you. But the initiator will be javascript from the client side. Using jQuery(let me know if you can't), you can do
$.ajax({url: "insert_game_id.php", data: {gameId :b.gameId} });
and your php script
<?php
$gameId = $_POST['gameId'];
$insrt = "INSERT INTO game (gameId)
VALUES ($gameId)";
mysqli_query($dbc, $insrt);
?>
See jQuery Ajax POST example with PHP

Hiding get variables in url?

I want to hide get variables in url
I want this
"dem/?p=user"
instead of whatever i passed like
dem/?p=user&act=stored
dem/?p=user&act=changed
dem/?p=user&act=deleted
Mates please help for me.
Advance thanks.
If you want to hide GET variables or values you should not use GET. In GET methods the data will always be send as part of the url. If you want to 'hide' the data (or not show it in the URL) from the user you should use a POST method.
You may use any one of the following:
Use POST method instead of GET
Use Ajax, with either POST or GET method
Use encryption and decryption if you really wish to send secured way i.e dem/?p=ENCRYPTED_STRING. Here ENCRYPTED_STRING will have all the GET data
Obviously since you did not take the time to tell us how you page structure is and how you are storing your values I can only guess.
Server side
If you store the data on a post-redirect page you can store it in a $_SESSION
session_start();
if (isset($_SESSION['message']))
{
$_SESSION['message'] = "succes";
}
Then on your confirmation page
session_start();
echo $_SESSION['message'];
Client side
You can create hidden inputs and add these to your form, set your form to post and handle these $_POST values on your form action page.
var x = document.createElement("INPUT");
x.setAttribute("type", "hidden");
x.setAttribute("name", "message");
form.appendChild(x);
Then on your confirmation page
if (isset($_POST['message']))
{
echo $_POST['message'];
}
modify .htaccess file to make short URLs the way you want them to look like

Executing PHP code from javascript

I am developing a php page containing a drop down select button. On changing its value, I am calling a javascript method and passing value selected in drop down. Now I want to use the value passed to get further details from MySql using PHP. How can I write PHP code withing javascript?
I am a beginner to PHP. Suggest me a simple and easiest way to do this
For onchange event of dropdown, you can call php page using ajax and passing your params and get the output.
Try to use ajax like this (http://www.w3schools.com/php/php_ajax_database.asp)
and this (http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t)
Front-end client side script (Javascript) can't directly 'invoke' or run PHP code. This is because of the separation between client side (browser) and server side (server) components of a web page. When you make a normal request to a server to return a page (eg. index.html), it will return the content of the page and terminate the execution.
What you're trying to achieve is something called AJAX, which is described on Wikipedia. There's also a pretty good and basic example of how to run a PHP script from Javascript.
In basic terms, AJAX is an asynchronous execution of the server side component of a web page. You can target a page 'test.php' with an ajax request, much the same was as you would when you open the page in your browser, and the content of the page would be returned.
To get the additional content, you can use either a POST ($_POST) or GET($_GET) request to send details back to the server. Typically when you're performing a search, you would use GET. If you're performing an update or create, you would use POST.
So your page URL might be something like http://mywebsite.dev/ajax.php?select=apples (where mywebsite.dev is the development URL). If you have a table of apple types, your MySQL query would be:
$type = $_GET['select'];
// Do some filtering on $type, eg. mysql_real_escape_string() and a few others
SELECT fruit.types FROM fruit WHERE fruit.main_type = '$type';
And then return a formatted JSON object back to the browser:
$return = Array(
0 => 'Pink Lady',
1 => 'Sundowner',
2 => 'Granny Smith',
...
);
$json = json_encode($return);
// expected result
{['Pink Lady'],['Sundowner'],['Granny Smith']};
You can always give extra indexes to arrays (multi-dimensional) or use stdClass to give better structure.
Then in your Javascript you use a for loop to iterate over the json object to build a new list of options.
var output = '';
for (var i = 0, k = json.length; i < k; i++) {
output += '<option value="' + json[i] + '">' + json[i] + '</option>';
}
Hope that helps.
Hi for this you need to use ajax.
try :
index.php code : This script will grab data from from using jquery and post it to search.php file via ajax
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#userid').change(function(){
userid=this.value;
$.ajax({
url:'search.php',
data : 'userid='+userid,
type:'POST',
success:function(result){
$('#result_div').html(result);
}
});
});
});
</script>
</head>
<body>
<form name='getUserData' id='getUserData' action='#' method='GET'>
Select User : <select id='userid' name='userid'>
<option value='1'>Lokendra</option>
<option value='2'>Amit</option>
<option value='3'>Nitin</option>
<option value='4'>Rishabh</option>
</select>
</form>
<div id='result_div'></div>
</body>
</html>
search.php code : This file will contain you business logic . and return value to ajax success method. You can fill retrun result any container.
<?php
$userArray=array(
1 => 'Lokendra',
2 => 'Amit',
3 => 'Nitin',
4 => 'Rishabh',
);
$postedData=$_REQUEST;
// Fire your select query here and diplay data
if(isset($postedData['userid'])){
echo "Selected User name =>".$userArray[$postedData['userid']];die;
}
?>
Dont forget to accept answer if it helps you. :)

Categories