How can I update mysql fields without refreshing the page, from a list of results from the database.
Using datepicker
In a single .php page?
Example:
order_report.php
$query = $this->db->query("select order_id,
date_format(date_payed,'%d-%m-%Y') as date_payed,
from oc_order");
***code left out to save space***
foreach ($res as $orders) {
print $orders['order_id'];
<input type="text" name="datepicker" id="datepicker" value="<?php echo $orders['date_payed']; ?>"/>
$query = $this->db->query("update oc_order SET date_payed='$datepicker' WHERE order_id='$orders['order_id'];'");
}
Jquery
<script>
$(document).ready(function() {
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd'
});
})
</script>
I'm assuming what you are asking is that you want the datepicker to update your MySQL table when you select on a date without having to refresh that page. The code you provided is a little confusing, but I put something together that may help.
I am guessing that the input field that's in your code is actually supposed to be the html where you are getting the value.
As for keeping it all on one single page... I don't think that will be possible. For best results, you will have to make a new .php page to accept the value of the datepicker, which is passed through the $.ajax call where it says date. If you did it on the same page, there's a possibility you may end up getting a swamp of unwanted html data returned to you via the data parameter in the success function, but it would most likely throw an error and get the error function callback.
In this example, I called the php page process_date.php.
HTML:
<input type="text" id="datepicker" value="<?php echo $orders['date_payed']; ?>"/>
JS:
<script type="text/javascript">
$(document).ready(function () {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function () {
var date = $("#datepicker").val();
$.ajax({
type: "POST", //or GET. Whichever floats your boat.
url: "path/to/process_page.php",
data: { date: date },
success: function(data) {
alert(data);
//Write code here for you successful update (if you want to)
},
error: function() {
alert("Error.");
}
});
}
});
});
</script>
PHP (process_date.php)
<?php
$date = $_POST['date']; //if you used GET in your ajax, then use $_GET here instead
$query = $this->db->query("select * from oc_order");
***code left out to save space***
foreach ($products as $orders) {
print $orders['order_id'];
$query = $this->db->query("update oc_order SET date_payed='$date' WHERE order_id='$orders['order_id'];'");
echo "Success";
}
?>
Note: Not saying you didn't, but don't forget to always sanitize your PHP data before sending it to the server in order to avoid being attacked via SQL Injection. Even if you use parameterized queries, it is still a good idea.
Related
I'm new to Json, Ajax and Jquery, so this is turning out very frustrating.
I'm doing a code to autocomplete on a form using Jquery. My form consists in 4 elements:
1) Client
2) Requestor
3) Address
4) Email
So far, I can autocomplete the Client with this code:
<script type="text/javascript">
$(document).ready(function(){
$("#Client").autocomplete({
source:'getClient.php',
minLength:1
});
});
</script>
However, I need to get the next data (Requestors, Address...) using the Client's values instead of showing all the requestors and all the addresses from the database.
I've been trying for 3 hours and I just don't seem to get any data.
As an example, I've just set my Requestor input with an onclick.
<input type="text" name="Req" size="60" id="Reqt" onclick="getreq()"><br>
This was the last code attempt I've done so far:
<script type="text/javascript">
$(document).ready(function()
{
function getreq(){
//get the username
var Client = $('#Client').val();
//use ajax to run the check
$.ajax({
data: Client,
url: 'getReq.php',
type: 'post',
success: function (response) {
$("#Reqt").autocomplete({
source:'getReq.php',
minLength:1
});
}
});
}
});
</script>
And my PHP looks like this
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("test");
$client = mysql_real_escape_string($_POST['Client']);
$query=mysql_query('SELECT * FROM client WHERE Clients ="'.$client.'"');
$json=array();
while($Reqt=mysql_fetch_array($query)){
$json[]=array(
'value'=> $Reqt["Requestor"],
'label'=>$Reqt["Requestor"]
);
}
echo json_encode($json);
?>
Like I said, I've been trying this for hours and I'm pretty new to Json, Ajax and Jquery, but I need to use those technologies, I would really appreciate any and all insight. Thanks in advance!
I'm noob in PHP, and JQuery, and i'm trying to do a pagination without changing the page.
I could submit a form, but i want to change the value from the limit without doing a submission.
My Query(i want to change the Limit):
$query = "SELECT * FROM events WHERE event_day = '".$list_day."' AND event_month = '".$month."' AND event_year = '".$year."' LIMIT 0,3";
I tried to do that -
First, i created a form with the limit value:
$limit = 0;
<form id="more" method="GET">
<button type="button" id="more_btn" value="<?= $limit ?>" class="c-button-1"><</button>
</form>
And then, i tried to get the value from the button, using Ajax
$(function(){
$(document).on("click","#more_btn",function() {
var value = $(this).attr('value');
$.ajax( {
type: 'get',
url: "modules/groups/calendar.php",
data: $('#more').serialize(),
success: function( response ) {
}
});
});
});
I was thinking about getting the value from the button, and change it in JQuery:
$query = "SELECT * FROM events WHERE event_day = '".$list_day."' AND event_month = '".$month."' AND event_year = '".$year."' LIMIT ".$limit.",3";
you don't even need the <form> there. when you are working with ajax you generally don't need any forms unless you want to do some hybrid coding for browsers with javascript turned off, or for serializing them (what you tried).
but in your case it doesn't really make any sense since your form just contains one button.
and you are already trying to get the value from the button but don't use it later on for some reason. you don't need to use .attr() there, since jQuery got the .val()-function for HTML elements with the value attribute.
so i'd do it like this:
$(function(){
$(document).on("click","#more_btn",function() {
var value = $(this).val();
$.ajax( {
type: 'get',
url: "modules/groups/calendar.php",
data: {
my_button_value : value
}
success: function( response ) {
}
});
});
});
$_GET['my_button_value'] then will receive the value in your PHP script.
in your question you also serialized the form which returns a URL-encoded string ("GET-style") which you can't just use in the data-attribute of the $.ajax function. you need an object there as i did in my code.
I am struggling trying to figure out how to implement a jquery UI date range form that will allow the modification of MySQL queries according to the inputted date range. Ideally, I would like to make my date range form introduce the new query data dynamically, without having to reload the page. I realize that the best and simplest way to do this is to use AJAX to send the form data to a backend PHP file. However, I am confused over how to use AJAX to modify existing queries. In my main front-end file, I have a date range form as follows:
<form id="myForm" action="#" method="post" name="myform">
<input type="text" class = "datepicker" id="txtStartDate" placeholder = "Start Date" style = "width : 85px; margin-left: 10px; margin-top: 1mm;"/>
<br />
<input type="text"class = "datepicker" id="txtEndDate" placeholder = "End Date" style = "width : 85px; margin-left: 10px;"/>
<br />
<input type = "button" name = "submit" value = "Go" style = "margin-left: 10px;"/>
</form>
I am clearly yet to write the AJAX function, but thought it would help to show the MySQL query I would like to modify to include a date range feature. Here is what it looks like before the date range variables have been set:
SELECT project, participant, reel, machine, qc_gsr, qc_hr, qc_acz, qc_bre
FROM rtcdb.session
WHERE site = 'ORL001';
And this is what I would like it to look like after the date range PHP variables have been set:
SELECT project, participant, reel, machine, qc_gsr, qc_hr, qc_acz, qc_bre
FROM rtcdb.session
WHERE site = 'ORL001'
AND download_date >= '$start_date'
AND download_date <= '$end_date';
So all in all, I would like to use AJAX to send form date to a back end PHP script that either modifies or switches MySQL query-usage in the original file to select in terms of the set date-range. Thank you very much for viewing this question and for your insight. It is valuable to me.
$("#myForm").submit(function () { //Ajax event handler on submit
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "pathToYourScript.php",
success: function (response) {
//Warn user everything went okay
},
error: function () {
//Tell there's been an error
}
});
});
In your PHP, just check if the $start_date and $end_date are set. If positive then switch query (make sure to use prepared statements by the way).
If you don't need the callbacks in the Ajax you can even use $.post() method. Everything you need is in the docs.
Use this jquery code
$("#myForm").submit(function(){
$.ajax({
url : "data.php",
type : "POST", //(POST or GET it depends up on your form action)
dataType : "JSON",
data : $(this).serialize(),
success : function (data)
{ alert("form submission is successfull"); } ,
error : function () { alert("something went wrong");}
});
});
In php file try to get the date using POST or GET automatical global variable and then pass it to the sql query as a parameter .Use any good php drivers such as pdo for avoiding sql injection .
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
I'm using jquery autocomplete on an input form 'city' but i would like the query in my 'autocity.php' file to only suggest cities in the pre selected country i.e. WHERE City LIKE '%$term%'" AND CountryID = '%$country%'. The form action submit uses a separate PHP file (create-business.php) for inserting the form data to the database so the usual $_POST['Countries_CountryId'] wouldn't work in the autocity.php. that's why i'm now using AJAX to post 'country' to autocity.php. Also it would be great to have a way to echo/alert/print_r from the the autocity.php file so i can confirm that the $_POST['$country'] from the ajax post reaches the autocity.php file.
I have two input boxes in the form
<pre>`
<form id="input" action="php/create-business.php" method="post">
<select name="Countries_CountryId" id="country">
<input type="text" id="city" name="City">`
</pre>
Here is the script from the form
<script>
$(function () {
var country = $("#country").val();
$.ajax({
type:"POST", url:"autocomplete/autocity.php", data:"country",
beforeSend:function () {
// alert(country);
}, complete:function () { // is there any need for this?
}, success:function (html) { // is there any need for this too?
}
});
$("#city").autocomplete(
{
source:'autocomplete/autocity.php'
})
});
</script>
And here is autocity.php
`
//database connection works fine and autocomplete
//suggestion works without the AND CountryID = '%$country%' part.
$country = "";
if (isset($_POST['country'])) {
$country = trim($_POST['country']);}
echo "window.alert($country);"; //This did nothing no alert
$term = $_REQUEST['term'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>`
So the question is basically:
1 - how can i use a text input from a form using AJAX in a .php file that queries a MySQL db that is not the submit form action .php file
2 - how can i alert the post variable from the PHP file when ajax is used to show that the php file recieves my ajax post. In my brief experience echo and print_r only work on form submit when the web page changes showing the result of my form submit ont the form action.
3- how is my syntax?
Thank you very much in advance for helping this novice out :D
Ok here is my update on things i've tried. I think i'm close. i'm using Jquery UI -
//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js
here is the script method 1:
$(document).ready(function () {
var country = $('#country').value();
alert(country + " complete");
$("#city").autocomplete(
{
source:'autocomplete/autocity.php?country='+country,
minLength:1
});
});
here is the script method 2:
$(document).ready(function () {
$('#city').autocomplete({
// source: function() { return "GetState.php?country=" + $('#Country').val();},
source:function (request, response) {
$.ajax({
url:"autocomplete/autocity.php",
//dataType:"json",
data:{
term:request.term,
country:$('#country').val()
},
success:function (data) {
response(data);
}
});
},
minLength:2
});
});
I like method 2 more since it will allow me to add more than one parameter.
Finally here is my latest autocity.php code
<?php
$term = $_REQUEST['term'];
$country = $_REQUEST['country'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%' ";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>
I'm still totally stuck though. can anybody see the problem with the code? Ive looked everywhere online for the right syntax. Thanks again
For the first problem, your approach is essentially correct. You can bind to the blur event for a particular field and use your function to get that field's value and submit to the php script much in the manner that you are doing so. $.blur() is what you're looking for.
For the second problem the error_log function will write stuff to php's error log. IF you use print_r to dump variables to this log, make sure to set print_r's second argument to true to output the result as the return value.