Having Multiple Variables in POST search? - php

I'm trying to do a Jquery Ajax search with multiple conditions, and this is my first time. I did some research and found ways to send data to a php file, however it's only with one variable. I'm not sure how to implement all of my 6 variables into data: data.
here they are:
var FromDate
var ToDate
var MusicStyles
var Locations
var FromPrice
var ToPrice
Now here is where I got stuck, I should do a post with some data. When I have multiple variavbles, can I do data: dataFromDate, dataToDate, dataMusicStyles,?
$("#SearchButton").click(function() {
var dataFromDate = 'dataFromDate='+ FromDate;
var dataToDate = 'dataToDate='+ ToDate;
var dataMusicStyles = 'dataMusicStyles='+ MusicStyles;
var dataLocations = 'dataLocations='+ Locations;
var dataFromPrice = 'dataFromPrice='+ FromPrice;
var dataToPrice = 'dataToPrice='+ ToPrice;
$.ajax({
type: "POST",
url: "do_search.php",
data: dataFromDate, dataToDate, dataMusicStyles, dataLocations, dataFromPrice, dataToPrice,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
});
Where the MySQL would look like this:
<?php
//if we got something through $_POST
if (isset($_POST['dataFromDate'])) {
include('db.php');
$db = new db();
// never trust what user wrote! We must ALWAYS sanitize user input
$word = mysql_real_escape_string($_POST['search']);
$word = htmlentities($word);
// build your search query to the database
$sql = "SELECT
events.ID,
events.EVENT_NAME,
events.start_datetime,
events.end_datetime,
events.VENUE_LOCATION,
events.ENTRANCE_PRICE,
venues.VENUE_NAME,
GROUP_CONCAT(music_styles.MUSIC_STYLE_NAME) AS MUSIC_STYLE_NAME
FROM events
INNER JOIN venues
ON events.VENUE_LOCATION = venues.ID
INNER JOIN events_music_styles
ON events.ID = events_music_styles.event_id
INNER JOIN music_styles
ON events_music_styles.music_style_id = music_styles.id
WHERE start_datetime >= '$phpFromDate'
AND end_datetime <= '$phpToDate'
AND ENTRANCE_PRICE >= '$phpFromPrice'
AND ENTRANCE_PRICE <= '$phpToPrice'
GROUP BY events.ID";
// get results
$row = $db->select_list($sql);
if(count($row)) {
$end_result = '';
foreach($row as $r) {
$result = $r['title'];
// we will use this to bold the search word in result
$bold = '<span class="found">' . $word . '</span>';
$end_result .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
}
?>
I am 100% certain that it doesn't work like this, but I think I got it almost right. I would love it if someone could at least please let me know what I could do to fix the code.
Thanks!

You send it as an object, like so:
$.ajax({
type: "POST",
url: "do_search.php",
data: {dataFromDate : FromDate,
dataToDate : ToDate,
dataMusicStyles : MusicStyles,
dataLocations : Locations,
dataFromPrice : FromPrice,
dataToPrice : ToPrice
},
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html) { // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});​
Where the firs value is the key, and the second is the value, so {key: value} would be accessed on the server as $_POST['key'], which your values would be accessed the way you seem to want :
$_POST['dataFromDate']
Also, you don't need all those variables at the start, just use them directly in the object.

Try to concatenate your strings with a "," and explode them on the server.

Related

Trying to have pass variables on select change action

I am trying to to an on the fly database update of a select field but there can be more than one instance on the page of this field. I had this working for a single on change select field change, but with more than one I am simply passing the values for the first one.
I have in the past dealt with creating unique DOM ids for these on the page, but in this instance with a select field and using the change function I am a bit befuddled. Also most of the situations I found in searching this were not for select fields or dealing with passing variables in this way. I am fully aware this is crude and probably there is a much better way to accomplish this task.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $('.preferenceData').val(), data2: $('#userID').val()}, // this second data element not really needed but is passing var
dataType: 'text',
success: function(html){
if(html) {
$("div#updateDisplay").replaceWith('<div id="updateDisplay">' + html + '</div>');
}
})
});
The form bit:
echo '<div id="userPref"><select class="preferenceData" name="preferenceData'.$row['uid'].'">';
$prefs = enum_select($db,'db_table_name','email_preferences');
foreach($prefs as $pref)
{
echo '<option value="'.$pref['value'].'-'.$data['topicid'].'-'.$row['uid'].'"'.($row['email_updates'] == $pref['value'] ? ' selected' : '').'>'.$pref['display'].'</option>';
}
echo '</select></div>';
The function it's passed to:
function save_preferences()
{
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
$db = new db(0);
$vars = $_POST['data1'];
$data = explode("-", $vars);
// Update Database
$data = $db->Exec('UPDATE km_vendors_users SET email_updates = "'.$data[0].'" WHERE vid = "'.$data[1].'" AND uid = "'.$data[2].'"');
if($data==false)
{
echo $db->log;
//return false;
}
else
echo '<img src="/images/icons/success_check_animated.gif">';
}
}
For your code, you are trying to pass $('.preferenceData').val() for data1, which will be fairly unexpected results (and usually not a value).
Instead you can use $(this).val() which refers the specific element that changed, and its value.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $(this).val()},
...etc...
});
});

How to manage Ajax success function?

if (isset($_POST["getCanvas"]) ) {
$projectName= mysqli_real_escape_string($db2, $_POST['whichProject']);
$query = "SELECT objectsList FROM projectObjectstable WHERE projectName='$projectName'";
// $query = "SELECT objectsList,backgroundImage FROM projectObjectstable WHERE projectName='$projectName'";
$jsonCanvas= mysqli_query($db2,$query);
$row = mysqli_fetch_row($jsonCanvas);
$myLine=$row['0'];
echo $myLine;
}
With code above i get one column from table. I need two columns. I woud like to try next:
$query = "SELECT objectsList FROM projectObjectstable WHERE projectName='$projectName'";
$jsonCanvas= mysqli_query($db2,$query);
$row = mysqli_fetch_row($jsonCanvas);
$myLine=$row['0'];
echo $myLine;
$query2 = "SELECT backgroundImage FROM projectObjectstable WHERE projectName='$projectName'";
$jsonBackground= mysqli_query($db2,$query2);
$row2 = mysqli_fetch_row($jsonBackground);
$myLine2=$row['0'];
echo $myLine2;
}
For it I need next solution here. How to modificate ajax success function to get two variables (projectList and backgroundImage) on canvas?
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage3/PgetJson.php',
data: {
"getCanvas":1,
"whichProject":whichProjectToSave
},
datatype: "text",
success: function(strdate){
canvas.loadFromJSON(strdate, function() {
canvas.renderAll();
});
}
});
An extra information would e appreciated. What options exists to debug php code in browser, as it is possible to do with js ?
Thank you
As it was said before, you need to use json_encode function to send parameters in JSON format to your JS. You have to put your variables inside an array before calling to echo. As it's used below.
$query = "SELECT objectsList FROM projectObjectstable
WHERE projectName='$projectName'";
$_row= mysqli_query($db2,$query);
$row = mysqli_fetch_row($_row);
$jsonCanvas=$row['0'];
$query2 = "SELECT backgroundImage FROM projectObjectstable
WHERE projectName='.$projectName.'";
$_row2= mysqli_query($db2,$query2);
$row2 = mysqli_fetch_row($_row2);
$jsonBackground=$row['0'];
$to_json['jsonCanvas'] = $jsonCanvas;
$to_json['jsonBackground'] = $jsonBackground;
echo json_encode($to_json);
exit();
And in your JS, you collect your information in the success function:
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage3/PgetJson.php',
data: {
"getCanvas":1,
"whichProject":whichProjectToSave
},
datatype: "json",
success: function(strdate){
/*Here on data you will receive
strdate['jsonCanvas'] & strdate['jsonBackground']
*/
});
}
});
I would also recommend making your sql calls in one query if your calling to the same table and passing the same variable as an argument.

MySQL get data from a query result

I am a newbie to PHP and MySQL development. I have built an app in Cordova using Visual Studio. The app works in the following way:
User selects a serial number from a drop down
After selecting a serial number, the data is showed on the chart
There is a toggle switch in the app, through which i am inserting the on or off state in the database based on the serial number
What I want to do?
When a user select any serial number, the switch will show the last ON or Off state based on Command Name of that particular serial number.
For this, I have generated a msql query and this query shows me the last command name of selected serial number
Below is my PHP code:
<?php
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
mysqli_close($con);
echo $cmd_Name;
?>
Below is my AJAX call in JavaScript:
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt.Command_Name == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt.Command_Name == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
But it doesn't show the required result and gives error as shown in below image:
Updated Code:
Bellow is my php updated code
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
//$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
mysqli_close($con);
echo $row["Command_Name"];
Bellow is the ajax
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
//dataType: "json",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
Now when running the code i am not getting any error but still i am not getting my required result i.e. the toggle doesn't change it's state
For more information please see the image bellow
I don't know what's the problem, any help would be highly appreciated.
This error means, that AJAX didnt send Command_Name via GET. You will have to check variable tData if it contains some value.
First step: dont send command_name with AJAX to PHP script (This causes Error on Line 5!!), it is not needed. Second step: in Php script you will have to change echo $command_name, to echo result from DB based on $dsn. So echo result from DB.
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row["Command_name"]; //This should show ON/OFF state from DB to AJAX.

onchange F(x) to php to Highchart on same page

I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.
I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Display Online users in a chat application

I have a chat application and in this application, i want to show online users in a chatroom. I have a database that records online users and it keeps changing whenever a new user comes. Whenever a users leaves, it is deleted from the database. Database consists of two columns: username and room. Database side works fine.
onlinelar.php:
<?php
$data = array();
$current = $_GET['current'];
$room = $_GET['room'];
$getRoomUsers = mysql_query("SELECT * FROM `chat_users_rooms` WHERE `room` = '".$room."'");
if(mysql_num_rows($getRoomUsers) != $current)
{
$data['numOfUsers'] = mysql_num_rows($getRoomUsers);
}
else
{
$data['numOfUsers'] = $current;
}
echo json_encode($data);
?>
online.js:
var numOfUsers = 0;
var room;
function chat(room2)
{
room = room2;
}
$.ajaxSetup({
cache: false
});
function getuserlist() {
$.ajax({
type: "GET",
url: "onlinelar.php",
data: {
'room': room,
'current' : numOfUsers
},
dataType: "json",
cache: false,
success: function(data) {
if (numOfUsers != data.numOfUsers) {
numOfUsers = data.numOfUsers;
$('#bu').html($("<strong id='bu'>"+ numOfUsers + "</strong>"));
}
setTimeout(getuserlist(),1);
},
});
}
And finally, the initializer of it in index.html:
----something
<script type="text/javascript">
var chat = new Chat(<?php echo $room;?>);
chat.getuserlist();
</script>
<strong id="bu">
<?php
echo $numOfUsers;
?>
</strong>
------something
In here, i want to check database situation(rows of the certain room), and change the number of chatters in that room simultaneously. 'current' is for number of users and 'room' is for the name of the room.But there is no change even though the num of rows of database is changing. Which part i am missing?
Note: I have added online.js in index.php
$('#bu').html($("<strong id='bu'>"+ numOfUsers + "</strong>"));
This line places a new element under your old one, what you want to do is replace the old one by calling
$('#bu').html(numOfUsers);
Also setTimeout() takes milliseconds so 1 is a really low value, you might want to start with 1000 and work from there.
Edit:
And setTimeout() takes a function as a param so you want to call:
setTimeout(getuserlist, 1000);

Categories