I have a page which is dynamic and takes a URL variable then populates the page from a PHP database call based on the value of the URL variable e.g.
Show item
Upon opening the page I grab the item_id from the URL and collect the data for printing e.g.:
$query = "select * from items where item_id = $_GET[item_id]";
$result = $mysqli->query($query);
$row = $result->fetch_array();
$title = $row['item_title'];
etc etc
My question is, can I grab a data variable from a link instead? e.g.
Show item
The reason for asking is that I want to use a modal which of course cannnot read from a URL as it would be the parent URL.
Ideally I want to stick with PHP as the code is written, but if there's a simple jquery solution to bring the data in to populate the page then that would be ok too (I'd guess an ajax call)
You can use ajax to read the data attributes.
http://api.jquery.com/data/
$('#yourId').data('item_id');
Please read about sql injection in your query
select * from items where item_id = $_GET[item_id]";
How can I prevent SQL injection in PHP?
You may want to use Ajax :
Show item
$('#clickMe').click(function() {
$.ajax({
type: 'GET',
url: 'myPage.php',
data: 'item_id='+$(this).data('item-id'),
success: function(data) {
// Do something with the returned data from the server
}
});
});
Related
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.
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 + '"')
I have a page called post-blog.php, in here I've set-up a blog entry. I have all this data being saved into one variable. Its displaying this data in an array.
var data = title + content + image + datetime + categories;
How can I send this data to another page called publish.php and redirect the user to that page ?
I've tried to set up a ajax to do this but its not working. Any suggestions ?
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: data,
success: function( data ) {
alert ( data );
}
});
return false;
});
As per my understanding of the problem, you need to pass the data to a new page and open that page.
If this is your question then this can be done without AJAX, basically AJAX does not even provide solution here. Instead you can just pass all the data to your new page in query format as below -
var page = 'publish.php?title='+title+ '&content='+content+'&image='+image+ '&datetime='+datetime+'&categories='+categories;
Then just change the window location as below
window.location.href = page;
And to get all those variables in your PHP file, do the following in publish.php on top -
if($_GET['title'])
{
$title = $_GET['title'];
}
// similarly get all the data in publish.php file and continue with your page
I am assuming all your variables are strings. If they are not, for example the datetime may be an object, change them into a string first.
Docs say Object must be Key/Value pairs or a string.
Objects work well for this, try something like:
var data = {title: title, content: content, image: image, datetime: datetime, categories: categories};
If your data is coming from a form check out jQuery's serialize.
I've never tried to pass as a string in a POST, but my gut feeling is it would need to be in a format similar to passing the data through the url.
var data = 'title=' + title + '&content=' + content;
Also keep in mind the data in the success function is not the same as what is being passed to the php page. This is what the php page will return. If you're php page returns nothing your alert will be empty. When I'm testing I like to throw something like echo $_POST['title']; in the php file to see something come back.
Here is a similar question that might help too.
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.
I have many tags. I want click each tag, then post/get the tag's value to another page.
In another page, received the values and make a mysql query. Then return the resalt data to the first page(do not make an iframe).
I think jquery post and load may be can do that (but have no idea how to combine two functiton). Or maybe there have any other way. Can any one give me some simple example? Thanks.
update
products.php
model:hml03
model:hml04
model:hml05<!--post value from products.php-->
...<!--many other tags -->
<div class="show_data"></div><!-- get the data back show in here without refresh the page.
data.php
<div id="data">
<?php
$result = mysql_query("SELECT id,name,details,add_date,model FROM ctw_products WHERE (MATCH (name,details,model) AGAINST ('+$_GET['get']' IN BOOLEAN MODE) Order By add_date DESC LIMIT 20 "); // get value with a mysql query
while ($row = mysql_fetch_array($result))
{
echo '<div class="name">'.$row['name'].'</div>';
echo '<div class="model">'.$row['model'].'</div>';
echo '<div class="details">'.$row['details'].'</div>';// how to return this part of datas back to products.php
}
?>
</div>
If your pages are ALL on the same domain then you can do the following :
Suppose that you have the first page, in which you do not want any iframe, the name of the page is yourPage.php.
And suppose that you have one other page whose name is yourService.php
What I understand from your question is that you just want to perform a simple AJAX request in order to POST/GET some data to a page, and retrieve the response.
With jQuery you can do that.
On yourPage.php you will have :
<html>
[...]
<script type="text/javascript">
function callService() {
$.ajax({
type: "GET", // or "POST",
data: "myLogin=login&myPassword=password",
url: "./yourService.php",
success: function(data){
alert("The service told me : " + data); // data is the response, make something with that like putting your data on your HTML page
}
});
}
</script>
[...]
Call the service
[...]
</html>
And on yourService.php :
<?php
// retrieve the data by looking at $_GET['login'] and $_GET['password'] (or $_POST)
// clean-up the variables if needed
// perform the MySQL query (by using mysql_query() for example)
// retrieve the data from the database
echo 'You are now connected'; // send something to yourPage.php by writing some data with the echo() function for example
?>
I hope my answer will help you.
This solution does not work if yourService.php is not on the same domain name that yourPage.php (the javascript engine of your browser will block that)
With JavaScript You cannot do AJAX calls to other domains. This is a browser "feature" that blocks this calls as prevention to corss-domain scripting...
But still You can do it with PHP. If You also want to get the response regarding to Your post, You can use cURL http://php.net/curl. If You want to use just get, it is much simpler, You only call from Your PHP:
$response = file_get_contents('http://www.domain.com/some_page.php?data=' . $my_get_data);
Depending to the response data format You can output them directly or parse it first.
If You need them to be outputed on another page (that You are now), You can save the data to the $_SESSION and do a redirect...
$_SESSION['response'] = file_get_contents('http://www.domain.com/some_page.php?data=' . $my_get_data);
header('Location: http://www.my_domain.com/my_first_page.php');
and on Your my_first_page.php You can do
var_dump($_SESSION['response']);