I wish to update MYSQL data using text instead of using submit button.
Admin will choose option from combobox and then click at save to update the MYSQL records.
How to do this using AJAX or jquery?
My coding:
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
//get table contents
$start = ($page-1)*$per_page;
$sql = "SELECT bookingID,eventinfo.eventTitle,boothAlias,testbook.bstatus,date, testbook.username, customer.companyName, customer.contactName from eventinfo, testbook, customer where testbook.username=customer.username AND testbook.eventID=eventinfo.eventID order by date desc limit $start,$per_page";
$rsd = mysql_query($sql);
?>
<form method="post" name="form">
<table width="800px">
<?php
//Print the contents
while($row = mysql_fetch_array($rsd))
{
$id=$row['companyName'];
$contactName=$row['contactName'];
$eventTitle=$row['eventTitle'];
//$phone=$row['phone'];
$date=$row['date'];
$status=$row['bstatus'];
$booth=$row['boothAlias']
?>
<tr><td style="color:#B2b2b2; padding-left:4px"><?php echo $id; ?></td><td><?php echo $contactName; ?></td>
<td><?php echo $eventTitle; ?></td><td><?php echo $booth; ?></td><td><?php echo $date; ?></td><td><select name='status' id='status'>
<option value='-1'>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select></td><td><a href=#>save</a></td>
</tr>
<?php
} //while
?>
</table>
</form>
image
This is actually really simple using jQuery. First, you have to create another PHP script that will actually run the UPDATE code. I'm not sure how much you know about AJAX requests, but you can essentially think of them as your browser opening a new tab in the background, sending the request and returning/parsing the response with JavaScript.
So, I'd write a PHP script that you can request (maybe "update_field.php" or "update_field_ajax.php") which does the actual updating. Write this script as you would if a form were being submitted from another page (ie it'll have POST and GET variables, validations, etc). There will be two main differences. First, you'll pass in the POST params with jQuery and second you won't return HTML (you can return HTML if you want - but if you're doing a simple update you really only need some sort of success or fail/error message response). I'd consider JSON for the response type. So, the PHP script is up to you to write, you'll write it just as you normally.
Next, you'll use jQuery to grab the data (GET/POST params) from the page and make a request to the PHP script you created. This isn't all that bad either. I'm not sure what you mean by "using text instead of a submit button" other than you don't want to use a submit button so I'll explain this in a somewhat abstract way. In order to get the AJAX call to run you must have something trigger it. This will be an event on the page, and that event will call a function that fires the AJAX request. Google around for information on jQuery events, but essentially when an event is fired it calls a function that you define. When that function is called we can use jQuery's post() method to create an AJAX post request. This method call will look something like:
jQuery.post('url of your script', {postVarOne: jQuery('some elt').val()}, function () {success function}, 'json');
The details of jQuery.post can be found at http://api.jquery.com/jQuery.post/
So basically write a PHP script as you normally would that returns something other than HTML signifying success/fail or a response message(unless you need to inject HTML right into the page) and then use jQuery.post (or jQuery more generic jQuery.ajax method) to have your browser request that script with the GET/POST vars you define and parse the response.
Finally, check out these tutorials for more information/code examples.
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
Related
I would like to know if it would be possible to run an update query when an item is selected from a drop down list. The user makes a choice, a function is then called to update a particular field in a database. This will be achieved using a select box to store the options. Thanks.
echo '<td>';
echo '<select name="order_status[]" onChange = "update()">';
echo '<option value = "1" class ="pending">Pending</option>';
echo '<option value = "2" class = "approved">Approved</option>';
echo '<option value = "3" class ="disapproved">Disapproved</option>';
echo '</select>';
echo '</td>';
echo '</tr>';
Yes, it's possible. If you want the query to be run seamlessly (that is, without a submit button being pressed and the page refreshing), then you'll need to use Ajax to send the request asynchronously to your PHP script.
EDIT: The easiest thing to do is simply use jQuery's $.get() functionality in your onchange event. That way, each time someone chooses an option, jQuery will send the request to your PHP script with that option's value. The PHP script will run, and return the new data back to your jQuery, which will then use its DOM functionality to insert that data into your page.
You can do the same thing with a button. Just stick $.get() in the button's onclick event rather than in the select element's onchange event.
The jQuery site's documentation will give you relevant code examples.
EDIT 2: Okay, here's a very canned example.
First, let's think about the actual process you want to have happen on the back end. In the simplest terms, you want to take an id from user input and use that to run in a query. Pretty straight forward (using PDO for the database work):
// in a real app, you'd need to sanitize and validate the incoming id
$id = $_GET['id'];
$stmt = $dbh->prepare("SELECT * FROM table_name WHERE id = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row); // makes it jQuery friendly
Okay, so the back end is pretty simple. Now, for the font end, where the magic happens. Here's how I'd approach using both a select element and a button in order to pass the id back to the PHP script, and then handle the results:
<!-- Your HTML up to where the select and button are on your page -->
<select id="id" name="id">
<option value="1">Something</option>
<option value="2">Something Else</option>
<option value="3">Yet Another Thing</option>
</select>
<button id="btn" />
<!-- In your jQuery -->
$("#btn").click(function() {
$.get("path/to/your/back/end/script.php", { "id" : $("#id").value }, function(data) {
/* the data will be the json_encode($row) that was echoed from the PHP script.
* so, you'll need to drill into it, take the data you want, and use
* jQuery's/JavaScript's DOM manipulation tools to insert the data on your
* page
*/
}) // close $.get()
}); // close .click()
None of this is tested, and it's admittedly incomplete, but that should be more than enough to get started. Really, all you'll need to figure out is how to drill into the returned data (it's a JSON object, so it shouldn't be too bad... use a browser's web development tools to see how the data is actually formed) and insert it where you want. That, and any dumb errors I may have made above.
Hope this helps!
My goal is to set a Google Conversion value from a custom field defined in WordPress. The conversion script is located on the landing page, so I need to get my custom field data from my form to the landing page. I can't use GET or POST as the form submission is handled by a third party and no data is returned to the actual landing page.
So I've tried using a PHP session, but this third party is getting in the way of just being able to use PHP, because it's keeping all the data for itself.
This is the approach I'm hoping I can get working:
The validation for the form is done using jQuery Tools.
I then need to submit the variable after validation has been successful via jQuery/AJAX to a separate php file.
Then as the landing page starts to load, I must grab that variable from mentioned PHP file and echo it in the relevant place.
I figured I don't actually need to start a session on the page with the form, as jquery is grabbing the data straight out the input, not any session data. So here's my input with conversion value:
<input type="hidden" id="conv" name="conv" value="90">
Then my form validation:
$("#course-form-modal").validator().submit(function(e) {
// when data is valid
if (!e.isDefaultPrevented()) {
// this grabs the value from my form
var con_val = $("#conv").val();
// and this sends it...
$.post(
"../../usersession.php",
{ data: con_val }
);
}
});
Then I've got the code in usersession.php... where I sent the data:
// As I'm just trying to echo what was sent to this page, via ajax, I shouldn't need to worry about starting/retrieving a SESSION yet... right?
<?php $var_value = $_POST['data']; ?>
<div id="results">
<?php echo $var_value ?>
</div>
// I CAN WORRY ABOUT THIS HALF LATER. RIGHT NOW I JUST WANT TO ECHO MY RESULTS ON USERSESSION.PHP //
Finally, I've got the code on my landing page to retrieve the data from usersession.php:
session_start();
$var_value = $_SESSION['conv'];
echo $var_value;
I'm not entirely sure all this code is right for starters, I'm more of a front end guy...
-EDIT-
Right, I'm pretty sure the code is correct at least now. For some reason it's still not working though. At the moment I'm wondering if WordPress would prevent me writing to usersessions.php from my javascript file (for reference, that file path is set absolutely in my working (not working) example)? I know WordPress will sometimes throw a 404 when you try to access a file directly.
The other potential issue could be with the third party software, vanillasoft. I've a link to their script in the action tag of my form, could that somehow bypass/kill the sending/receiving of data between the form > usersession.php > and then the landing page?
On a side note, if anyone has a great idea on how I can test if usersession.php is receiving the data then please let me know? I did have this code originally, but it returns nothing and if I link straight to the file after a send something (as in just paste the file url in to my browser) it returns a '0'...
if(isset($_POST['conv'])) {
session_start();
$_SESSION['conv'] = $_POST[''conv''];
echo "1";
} else {
echo "0";
}
Set your ID on the input. jQuery is looking for the ID, but you have only set the name.
<input type="hidden" name="conv" value="90">
Should be:
<input type="hidden" name="conv" id="conv" value="90">
EDIT:
Can't believe I didn't catch this earlier. Your problem is in the usersession.php at the following line.
$_SESSION['conv'] = $_POST[''conv''];
You have the POST quoted wrong.
It should be:
$_SESSION['conv'] = $_POST['conv'];
EDIT (re: New js edits)
In you java script your post vars should be formatted thusly:
{ name: "John", time: "2pm" }
So your line should be something like this:
$.post(
'../../usersession.php',
{
conv: $("#conv").val()
},
function(data)
{
alert("Data Loaded: " + $("#conv").val());
}
);
I have created a news area where i have display 3 thumbs of news at a time the source is from mysql database.
i have used the query like this:
$eu = 0;
$limit = 3;
$query2=mysql_query("SELECT * FROM news ORDER BY ID DESC LIMIT $eu,$limit");
now i have also create two buttons with like this
i want to use this buttons for display the next 3 thumbs onclick and prev 3 thumbs. but not able to change the value inside the query i.e $eu.
how can i change the $eu value inside the mysql query with javascript or any other suggestion and also i dont want to do this with reload of page with passing query parameters. i want it without reloading of page
You'll need to do an ajax call, pass in the value for $eu (eg, 3, 6, 9 etc) that you need, and pass back the contents of the news feed, to replace the existing lot.
There are many ways you can do this and which is easiest depends on the frameworks you are using. Google is your friend here, there are plenty of tutorials etc.
You can't change a php variable from Javascript simply because the server side script is already run, and javascript is a client side script.
What I suggest would be, use javascript to send an ajax request to a PHP scriptthat accepts $eu as a parameter.
In that PHP, do the query with the $eu, and print out the search results.
In your javascript, catch this result upon success ajax request and process/replace certain elements in your HTML with the result.
You cannot change the value of any PHP script directly from Javascript because PHP is parsed prior to the page being sent to the browser (i.e. server-side) and Javascript is parsed and execute by the browser (i.e. client-side).
There are 2 main ways this sort of thing is accomplished. If you really want to affect the PHP variable value then you'll have to reload the page (for example using an HTML form). Since you said you don't want to do that, then as others have suggested, you'll want to look at AJAX.
In a nutshell you'll use Javascript to send a request to a PHP page which will run the query you have above (and you can pass along a new value to plug into $eu in the form of POST or GET data) and return the results which you will then use to update the display on your page.
Try this
//PHP
$count=3;
$query= 'select * from news order by id desc ' ;
$limit_str=" limit 0,$count";
if(isset($_POST['page']))
{
$lim=$_POST['page'];
$offset=$lim[0]*$count;
$lim_str=" limit $offset, $count";
$query.=$lim_str;
}
//Form
<form method='post' >
< input type='submit' name='page[]' value='1' />
< input type='submit' name='page[]' value='2' />
< input type='submit' name='page[]' value='3' />
</form>
<?php
// Display logic
?>
I want to display the photos according to the album selected. But, I don't want to post the page, I want to just change the div.
This is my script:
<script type="text/javascript">
function replaceContent(divName, contentS) {
document.getElementById(divName).innerHTML = <?php echo get_pictures_from_album($fb, $albums, contentS); ?>;
}
</script>
And this is the select tag that invokes it:
<select name="album" size= "1" style="width:210;" onchange="replaceContent('photos', this.options[this.selectedIndex].value);">
<?php get_albums_select_list($albums); ?>
</select>
<div id = "photos">
<?php echo get_profile_pictures($fb, $albums); ?>
</div>
I understand from a reading that I have done that the problem might be connected to javascript Vs php variable types.
Please advise.
Looks like you are looking for an AJax call to an PHP script that retrives the data for the appropriate album selected and THEN update the div with the callback function.
Ajax + PHP basics
You are mixing Clientside and Serverside Code here. The function replaceContent is called after the page (and the php code) was loaded. You would need an Ajax Call for that if you need more information about that:
Ajax Tutorials on Google
What you are doing is not possible because PHP code runs before (on the server because PHP is server-side language) javascript code.
You will have to resort ot AJAX for that.
Initially, I used a .js file that contains AJAX functions to call a .php file. The .php file contains code to dynamically populate a DropDown based on certain parameters passed via QueryString.
Everything works fine with the above method. But now I want to populate the DropDowns on page load and so want to use JQuery instead of my old method. I tried following code, but it is not filling the DropDown.
$.get("../Lib/filldropdown.php",
{ param1: "divMemberOf", param2: "inMemberOf", param3: "categorymaster" });
Below is the code of the .php file:
<?php
require("dbconnection.php");
require("dbaccess.php");
$dropdownControlName = $_GET['DropDownControlName'];
$query = ".....";
dbconnection::OpenConnection();
$result = dbaccess::GetRows($query);
?>
<select id="<?php echo $dropdownControlName; ?>" name="<?php echo $dropdownControlName; ?>">
<option>Select from the list</option>
<?php while($row=mysql_fetch_array($result))
{ ?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select>
Please note that the above JQuery code passes three parameters, but I have used only one in the PHP code above. I am going to use two parameters later. The above PHP code is perfectly working with my old AJAX method.
You are making an AJAX request using GET, but you are not adding a callback function to actually handle the returned HTML. It vanishes in thin air.
Check out the JQuery AJAX documentation on GET for a complete example.
Your call would have to look something like this:
$.get("../Lib/filldropdown.php",
{ param1: "divMemberOf", param2: "inMemberOf", param3: "categorymaster" },
function(data) { $('#myDivID').html(data); }
);
You either need to add a callback function, or the .load method might be more appropriate since you just want to inject the results from that PHP call into the page:
$("#someContainer").load("../Lib/filldropdown.php",
{ param1: "divMemberOf",
param2: "inMemberOf",
param3: "categorymaster" });
You just need some DIV or something to be a placeholder to inject the select box into.
You are not specifying the key correctly for your php to work as-is. In your javascript you are creating a request like this:
param1=divMemberOf¶m2=inMemberOf¶m3=categorymaster
I would think you need one of those parameters to be named DropDownControlName since you are using it as the id for your newly created select input. You might also check param2 and param3 since you are likely using those in your query.