display html select (from PHP) via jquery? - php

So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}

if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed

if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.

Related

Send multiple AJAX data to PHP and update Mysql database

i am tying to build an application where user can reorder items (and save the order to database). The items user is reordering are navigation links, which are generated dynamically on the page from php loop:
$nav_links.='<li class="collection-item ui-state-default item" data-ord="'.$navorder.'" data-url="'.$pageurlname.'"><a>' .$pagename. '</a></li>';}
$navorder is order of the page in the navigation
$pageurlname is string which is used to call the page dynamically (index.php?page=$pageurlname) and is unique key in the table.
I am using jqueryUi sortable funcion to make the process drag & drop, it is working fine and each time i reorder the links, the new order is updated to "data-ord".. the sript:
$('#sortable').sortable({
stop: function(event, ui){
$(".sortable li").each(function(i, el){
$(el).attr('data-ord',$(el).index()+1);
});
}
});
Now to the problem, which is my ajax script:
$(document).on('click','.saveorder',function(){
var neworder = $('.collection-item').attr('data-ord');
var pgurl = $('.collection-item').attr('data-url');
$.ajax({
type:'POST',
dataType:'text',
url:'/rs/pages/nav_order.php',
data: { neworder:neworder, pgurl:pgurl },
success: function(data) {console.log(data); $('#response').html(data);},
error: function(data) {console.log('Error!', data); }
});
});
I am new to ajax, so it is mostly build on scripts i found in other quiestions here. (I was able to succesfully implement cript link this to my other functions) however it is not working in this case. The problem seems to be that i am trying to post multiple data for multiple rows (At this time i have 4 links i am trying to reorder, but the link count can be more or less). When i tried to get values of variables "neworder" and "pgurl" (using alert), it always show only the values for the first item.
I have tried lot of solutions found in similar quiestion but none of them worked, simply because user were posting form data and then serialized it, which is not my case because i am not sending data from the form.
Lastly here is the nav_order.php (i guess it is wrong here too, probably need to add foreach but at first i need to have the ajax working correctly):
<?php
include "/rs/include/db.php";
$neworder = $_POST['neworder'];
$pgurl = $_POST['pgurl'];
$query = mysqli_query($Connection, "UPDATE horus_pages SET nav_order='$neworder' WHERE url_name='$pgurl'") or die (mysqli_error($Connection));
echo 'Reordered';
?>
Also when i check the console, there is no data.
So please can you tell me how to correct the ajax script to send the data for each object and then handle it correctly in the php script? Hope i described my problem clearly. Thank you for any help.
Put data-id="your_database_id" in your links html. Selecting them in your database with href, will be slow and bug things if there are multiple records with the same href.
You have save button which sends the order and href of the first link it finds? And what happens when multiple items change their order? If you have many links, you will be throwing hundreds of mysql updates for each save?
You should be better off sending json to your php. Something like that:
[{id:123, order: 332}, {id:124, order:334}, ... ]
dataType:'text' becomes dataType:'json'
If you don't care about scalability, then this will work on the backend.
$data = file_get_contents("php://input");
$links = json_decode($data, true);
foreach($links as $link) {
$order = intval($link['order']);
$id = intval($link['id'])
// UPDATE table SET `order` = '$order' WHERE id = '$id'
}
Btw. Your php code allows SQL injection. Thats bad
Perhaps you can make the order 'float' and make an algorithm which finds empty spot. This will allow you to reduce these 100's of SQL requests to 1.

Can MySQL query include HTML values?

REVISED QUESTION:
How can I reference a row of MySQL data while a form is being filled out. In other words, with my ('Select * FROM... how can I specify the row to pull the fields from without having to process the form to get the PHP fields?
Desired Process 1) User inputs first value, 2) Sidebar MySQL query looks up that value and fills div with data from that row, 3) User continues to fill out form while able to see div filed with MySQL data
ORIGINAL QUESTION:
I am curious if you can include a reference to an HTML input in a MySQL query.
Take the following for an example.
('SELECT * FROM MyTableName WHERE MyColumnID="MyHTMLInputValue"');
I would like to reference all the fields in the row based on the value of an input field and not sure of how to reference such a query.
Thank you!
Ajax is the way to go.
This example uses jQuery.
First we need to setup a php script to get our value and search for it, then return our data.
PHP myPhpScript.php
<?php
$search_value = $_POST["field1"]; //Get our value from the post.
//Make sure to do some authentication on the value so that bad values dont get through
$connection = new mysqli(Stuff here);
$rows = $connection->query(
"SELECT * FROM someTable where searchColumn LIKE %".$search_value."%"
);
//Now all we need to do is send out our data. Lets use json.
$out = $rows[0];//Get the first row. NOTE: Make sure to remove any columns that you dont want the client to see.
echo json_encode($out); //Send the client the data.
?>
Javascript Some script on the page.
var textbox = $("#mySearchBox"); //This is the jQuery object for our text box.
var viewbox = $("#myViewer"); //This is the jQuery object for the div that holds the results
textbox.on("input", function () {
$.ajax({
url: "myPhpScript.php", //This is the php script that we made above.
method: "POST", //This set our method to POST.
data: {field1: textbox.val()}, //set the textbox value to field1
dataType: "json", //So jquery formats the json into an object.
success: function (phpDataObject) { //Now its up to you to decide what to do with the data. Example below
viewbox.html("");//Clear the viewbox.
viewbox.append("Id: "+phpDataObject["id"]); //Show the id of row that was found.
}
});
});
This code may not work. Just fix whatever syntax errors that show up.
Hope this helps.
Comment if you need any more help.
This does not sound like a good idea. Usually you want some separation between your site and database. You could take in "MyHTMLInputValue", process it, then you can complete your query.
var myValue = MyHTMLInputValue;
//validate input
('SELECT * FROM MyTableName WHERE MyColumnID="' + myValue + '"')

Passing a Php Variable Through Ajax to Update a Frame

I have a server-side PHP page that draws data from an SQL database to populate an array of PHP variables. I use the last array value for each variable to initially populate the data into the 3rd frame of a form (i.e., value = ). This form has a "previous" and "next" link that I want to use to populate the 3rd frame of the form with the "previous" or "next" set of variable values (i.e., value = ) dynamically without loading the entire page. While I'm very familiar with javascript, php and sql this will be the first time I've tried to use AJAX. What I'm trying to do is pass the array number or counter, which is a php variable, to an AJAX function which increases or decreases the array counter (i.e., $counter) so that the values for the next set of variables appears in frame 3 of the form. My problem is that I'm sure that I can pass the current $counter value to the AJAX function which will process it as a javascript variable but how can I then pass the result back to update the php variable in frame 3 of the form? Any help will be very much appreciated.
Blacksquare:
My php web page does the first part. It gathers data from the underlying SQL database and places it into a php array. When the web page initially loads, the most recent or last record is used to populate the form fields that are all in a single frame using something like this (value=$dataField[$counter]). This works when the page is initially loaded populating all of the frame fields with data from the last record in the SQL database. What I'm trying to do is create an AJAX function activated by clicking on the "next" or "previous" link (i.e., an onclick event) that takes the $counter value and increases or decreases it by one (1) and then refreshes the frame displaying fields from the "next" or "previous" php array record in the same frame without reloading the page.
You need to create a php file which will handle the ajax request (passing the variable as post parameter) and echo your response in the php file.
Then in ajax file you will get response in success, update the response using jQuery into the form.
Note: Don't forget to put 'exit' after the response in php file.
For example:
$.post( "test.php", { counter: <?php echo $counter; ?>}).done(function( data ) { alert( "Data Loaded: " + data ); });
What about altering appropriate HTML elements using JavaScript after you get results of the ajax call? There is no need to set the php variable and then to use that field to set a value in HTML when you can alter that HTML value directly from JavaScript.
You can't pass a variable back into a static page generated by php. Probably the best approach is to load only the form on page load. Then grab the dynamic data using an ajax call to another php script on the server side (I'm using jQuery for the ajax).
$.ajax({
type: "GET",
url: someURL, //A link to your php script that will load the data
dataType: "json" //Ask for json data from the server
}).done(function(data) {
nextRecords = data;
getNextRecord();
}).fail(function(resp) {
console.log("Something Went Wrong");
});
Move your sql logic to a separate php script accessed at someURL and have php pass back an array of json data like this
$query = ...Your select query returning an array of results
echo json_encode($query);
exit;
Now when a user hits the next/previous button, you can easily grab the latest record without posting to the server.
function getNextRecord() {
if (nextRecords.length > 0) {
var record = nextRecords.pop();
var node = document.getElementById(node_name);
node.innerHTML = record;
if (currentRecord){
prevRecords.push(currentRecord);
}
currentRecord = record;
}
}
function getPreviousRecord() {
if (prevRecords.length > 0) {
var record = prevRecords.pop();
var node = document.getElementById(node_name);
node.innerHTML = record;
if (currentRecord) {
nextRecords.push(currentRecord);
}
currentRecord = record;
}
}

Update MY SQL DB Table from jQuery

Based on the user input's, i calculate some values on my submit action of my form. I have to persist these values in my backend DB. I use PHP for my server side scripting. Please let me know the best practice for doing this. It is a single page application and i use .load("Report.html"); to show the summary page.
Just thinking aloud, can i fetch the row(to be updated) from DB, json_encode, update the json object in jQuery, decode it, then update in DB?
Please help...
My submit button code...
$('form').on('submit', function(event)
{
event.preventDefault();
//CALCULATE SCORE
var noOfCorrectAnswers = 0;
var noOfQuestionsViewed = 0;
$.each(questionsArray, function(i, item)
{
if(item.correctOption == item.selectedAnswer)
{
noOfCorrectAnswers++;
}
if(item.isQuestionViewed == 'YES')
{
noOfQuestionsViewed++;
}
});
alert(noOfQuestionsViewed);
$('#sampleDiv').load("UserReport.html");
});
Run some AJAX passing all of the information you need (which may even be none depending on your use case) from the client-side to your server-side PHP. Your PHP script can fetch things from the database if necessary, make any calculations and/or manipulations and then store the information back in the DB.
If you need to return information to your client-side after updating the database then try returning a JSON object (by just printing the code out in the proper format) from your PHP script before exiting with whatever your JS needs.
Do note that this should be all done asynchronously, so you need to setup your AJAX callback function to handle any information that's returned from your PHP script. If you want to do it synchronously, go for it - but you asked for best practices :P
Looks like you're using jQuery - here's the documentation on AJAX
Raunak Kathuria's answer provides some same code
On form submit make ajax call to set database in the db and access the json
$('form').on('submit', function(event)
{ ...
alert(noOfQuestionsViewed);
$.ajax({
url: "yourphp.php", // php to set the data
type: 'POST',
data: 'yourparams', // all the input selected by users
dataType: json
success: function(json){
//here inside json variable you've the json returned by your PHP
// access json you can loop or just access the property json['sample']
$('#sampleDiv').load("UserReport.html", function () {
// its callback function after html is loaded
$('#someid').html(json['sample'));
});
}
})
You can also use the done callback of ajax
PHP
yourphp.php
Set the values here in db running the desired query and return values using
<?php
// your db ooperations will come here
// fetch the db record
// return the db records in json
$responseVar = array(
'message'=>$message,
'calculatedValue'=>$calculated
);
echo (json_encode($responseVar));
?>

Create mysql table from a query run on another PHP page

I have a PHP page that processes some information when a button is pressed. One of this information is to process a query. I then want the results of the query to be put into a table in another page. I know how to put query results into a table, but I don't know how to pass them row by row to a table on another page. Can anyone help or point me in the right direction?
If I understood this correctly, you'll need AJAX (and, by requirement, JavaScript) for this. What you want to do is call your generation function and have it return a format that you can parse (JSON, XML, you name it).
From there, you'll append it to your table using JavaScript's DOM manipulation functions.
The generation part
Assume that you're getting your data in an array format as follows:
$row = array('column 1','column2');
You'll be getting tons of rows like these, or just one - we'll write the script to handle both cases without requiring a rewrite. Every time you get a row, add it to a non-associative array , call it $RowArray. So, on every row, you'll be calling $RowArray[] = $row;.
You now have the PHP side almost done - all you need to do now is to echo it back to the client. Make sure you echo nothing else but this: echo json_encode($RowArray);. This will format and serialize your array to be a perfect JSON object.
The JavaScript side
We'll assume jQuery for simplicity. Your aim will be to read the JSON object and add rows to a table. We'll assume that the table has ID #MyTable.
The AJAX call is done as follows:
$.ajax({
url: "your_url.php",
dataType: "json",
type: "post",
success: function(d) {
// Your code here
}
});
The success handler will be triggered when the object has been successfully parsed, and the variable d will be the object. This object will be a JavaScript array where each element is an object. All you need to do now is to loop through d and create a row per entry!
success: function(d) {
for(var i=0; i < d.length; i++) {
var newRow = $("<tr></tr");
for (var k in d[i]) {
newRow.append($("<td></td>").text(d[i][k]));
}
newRow.appendTo($("#MyTable"));
}
}
Voila, dynamic AJAXified table in six lines!

Categories