On my website I have an update form that when submitted alters my database.
What I want to do however is have all the elements that contain the old values,
AJAX
// UPDATE
$(".bill-upd-submit").click(function() {
var elem = $(this);
$.post("update_bill.php", elem.parent(".bill-upd").serialize(), function(data) {
//INSERT INTO OLD VALUES
});
});
PHP
In my PHP I've tried the following with no luck, has anybody done this before or can give me advice on where I may be going wrong?
echo "elem.closest('li').find('.cost').html('');";
You do not need to have the server provide the jQuery code. You can just type it into the callback function, where you have your //INSERT INTO OLD VALUES-comment.
$.post("update_bill.php", elem.parent(".bill-upd").serialize(), function(data) {
//We will use the "data"-variable that was passed to this function by jQuery.
elem.closest('li').find('.cost').html(data);
});
In the above code, the "data"-variable contains that which was given back by the server. So for that solution, make sure that "update_bill.php" will return the HTML that you want to insert into 'li .cost'.
Related
I am trying to post the element information that jQuery pulls, when a user clicks on table cell, to a new page that will use that information (an id in this case) in a sql query. i.e., the user clicks a cell and the job he/she clicks has an id of 25, that is to be passed to my php page that queries the database for the job with that id and then populates the page with said information. The user can then alter the information from the query and submit it to update the database table. I have the id from the click function and a success alert tells me that the info was posted. The problem is that when the page is opened it states that the posted name index is undefined.
Here is my script to get the information:
<script>
$(document).ready(function()
{
$("table.jobs tbody td#job").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
if (col == '')
alert("Please pick another column");
else
$.ajax(
{
type:"POST",
url:"../php/jobUpdate.php",
data:"name=" + LeftCellText,
success: function()
{
window.location = "../php/jobUpdate.php";
}
});
});
});
</script>
and here is the simple php page it is sending to:
$name = $_POST['name'];
echo $name;
I am new to jQuery, and I cannot figure out why this is not working?
When you use ajax, the second page ../php/jobUpdate.php processes the data sent by the first page, and returns a value (or even a huge string of html, if you want).
The first page receives the new data in the ajax routine's success function and can then update the current page. The updating part happens in the success: function, so you're on the right track.
But in your success function, you are redirecting the user to the 2nd page -- after already being there and processing the data. Redirecting them is probably not what you want to do.
Try replacing this:
success: function()
{
window.location = "../php/jobUpdate.php";
}
with this:
success: function(data)
{
alert(data);
}
If you want to see how to update the first page with the data received via ajax, try adding an empty DIV to your html, like this:
<div id="somestuff"></div>
Then, in the success: function of the ajax routine, do this:
$('#somestuff').html(data);
(Note that the term "data" can be any name at all, it only needs to match the name used in the function param. For example:
success: function(whatzup) {
alert(whatzup);
}
From your comment to my previous post, it seems that you don't need ajax at all. You just need a form in your HTML:
<form id="MyForm" action="../php/jobUpdate.php" method="POST">
<input type="hidden" id="jobID" name="yourJobID">
</form>
Note that forms are invisible until you put something visible inside them.
You can have select controls (dropdowns) in there, or all form elements can be invisible by using hidden input fields (like the HTML just above), which you can populate using jQuery. Code to do that would look something like this:
<script>
$(document).ready(function() {
$("table.jobs tbody td#job").click(function() {
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
//Set value of hidden field in form. This is how
//data will be passed to jobUpdate.php, via its `name` param
$('#jobID').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#myForm').submit();
});
});
</script>
If you add more values to your form to send over to jobUpdate.php, just ensure that each element has a name, such as <input type="text" name="selectedJobType"> (this element, type="text", would be visible on screen).
In the jobUpdate.php file, you would get these values thus:
$SJT = $_POST['selectedJobType'];
$id = $_POST["yourJobID"];
//Use these vars in MySQL search, then display some HTML based on results
Note that the key referenced in the $_POST[] array (selectedJobType / yourJobID) is always identical to the name specified in the HTML tag. These names are case sensitive (and spelling counts, too).
Hope this isn't TMI, just wish to cover all the bases.
On your success function causing the window to reload will delete any of the variables passed in via .ajax.
What you can try is returning the data and use it in the existing page.
success: function(msg) {
$('#someDiv').append(msg);
}
The reason the index is not defined is because you are using a string in the data-argument, however, that is actually an array-like object. :)
data: { name: col }
that should be the line you need to change. Otherwise I have not seen any problems. Also if I can give you a little idea, I wouldn't use POST actually. In fact, I'd use GET. I can not confirm if that is saver or not, but using $_SERVER["HTTP_REFFERER"] you can check from where that request is coming to determine if you want to let it pass or not.
The way I would suggest is, that you sent the ID in a GET-request and have the PHP code return the data using json_decode(). Now in jQuery, you can use $.getJSON(url, function(data){}) - which is, for one, shorter and a bit faster.
Since you probably will crop the URL yourself here, make sure that you use a function like intVal() in JS to make sure you are sending an intenger instead of a malicious string :)
I'm still new to jQuery and stuck trying to figure this one out, hope someone can help. I have this jQuery code that needs to pass different values depending on the clicked element. Each element created has a unique number in it's ID (which is needed). If I manually change the jQuery code to a specific ID and call, for example:
http://mysite/examplepost?effect=113
This will work. But I need to have $('#div- ...different numbers here...') to be able to handle multiple elements on the same page. I already have the PHP side producing different values using:
if($_GET['effect'] == $id){
I just need this to work with ajax so that it doesn't reload the page.
Example:
$('#div-113').on('click', function() {
var dataString = 'effect=113';
jQuery.ajax(
{
type:'GET',
url:'?',
data: dataString,
success: function(data){
alert('Works');
}
}
);
});
Any help would be appreciated.
I would give all your divs a common classname (i.e. myClickableDiv) and also a specific data-id.
This way you can target all your divs by that common classname, rather than having to figure it out depending on how the id is formed. The data-id allows you to only provide very specific information to the click handler (like an integer), without having to parse the id.
HTML:
<div class=".myClickableDiv" id="div-XXX" data-id="XXX">My Div</div>
JS:
$('.myClickableDiv').on('click', function() {
var dataString = $(this).attr('data-id');
jQuery.ajax({...});
});
I have a jquery mobile app that on page load, reads data from the database and populates select boxes on the page with user specific data like their favorite addresses.
Ive implemented an ajax script that deletes the selected option which works well. But I need to find a way refresh the select boxes without reloading the page.
I gather AJAX is the way I need to go, but I wouldn't know where to start.
I assume I'll need to re-run the php file that reads the database and then the javascript that takes the returned data and populates the select boxes.
index.php (First Part)
<?php
$show_faves_pass=true;
$show_faves_cctr=true;
include('../includes/favourites.inc');
?>
favorites.inc
$js_str='';
if ($show_faves_addr){
// Postgres sql statement here
$addr_json=json_encode($addr_rows);
$js_str.="var fave_addresses=$addr_json;\n";
}
if ($show_faves_cctr){
// Postgres sql statement here
$cctr_json=json_encode($cctr_rows);
$js_str.="var fave_costcentres=$cctr_json;\n";
}
if (strlen($js_str)>0){
echo "<script type='text/javascript'>\n$js_str\n</script>\n";
}
index.php (Second Part)
//populate favourites pickers
function findFave(arr,key,val){
var found=null;
$.each(arr,function(i,v){
if (v[key]==val){
found=v;
}
});
return found;
}
var pass_fave_sel=$('select#pass_fave_picker');
$.each(fave_passengers,function(i,fave){
pass_fave_sel.append("<option value='"+fave.passenger_details_id+"'>"+fave.passenger_nickname.replace("'","\'")+"</option>");
});
var cctr_fave_sel=$('select#cctr_fave_picker');
$.each(fave_costcentres,function(i,fave){
cctr_fave_sel.append("<option value='"+fave.cost_centre_id+"'>"+(fave.cost_centre_code+" ("+fave.cost_centre_nickname+")").replace("'","\'")+"</option>");
});
Hopefully this all makes sense, any help at all will be appreciated,
Thanks heaps in advance!
Every jQM element has its own refresh method used for restyling.
For example:
Listview has a:
$('#listviewID').listview('refresh');
Here's an example: http://jsfiddle.net/Gajotres/AzXdT/. This is a listview dynamically generated from XML data.
Button elements have a:
$('#buttonID').button('refresh');
Here's an example: http://jsfiddle.net/Gajotres/K8nMX/
Slider has a:
$('#sliderID').slider('refresh')
And you are going to use this one:
Selectmenu has a:
$('select').selectmenu('refresh', true);
By now you can see a pattern here. To refresh always use a component name as s function with 'refresh' parameter.
In case you are doing a whole page restyle you should use this method.
EDIT :
$.ajax({url: server_url,
data: save_data,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
// Here delete elements from select box
},
error: function (request,error) {
// Throw an error
}
});
i am trying to get a button on my page which will eventually be a delete button to work. However because it is a <li> element and not your average submit button with a form etc... i have to use ajax to send all the variables to be processed, at the moment i just want them to be in a state where they can be processed, but at the moment my script doesn't seem to return any value like i want it to and output them.
Hopefully from the code below you will see what i mean, all i need it to do at the moment is just select all the values from the checkboxes which are cehcked and send it to the mail_trash.php, and then just send it back and output the array, just so i can see it is selecting the proper values etc... The actual delete php code is already written and working, this is just to check the Ajax.
Here is the javascript and ajax
<script>
$("document").ready(function (){
$("li.trash").click(function(e){
var db = $(':checkbox:checked').map(function(i,n) {
return $(n).val();
}).get(); //get converts it to an array
if(db.length == 0) {
db = "none";
}
$.ajax({
type: "GET",
url: "mail_trash.php",
data: {'db[]':db },
dataType: "json",
statusCode: {
200: function (response) {
$("#mail_header_name").html(response.mess_id);
}
}
});
});
});
</script>
And here is the script for the mail_trash.php
<?php
include 'connect_to_mysql.php';
$mess_id = $_GET["db"];
echo json_encode($mess_id);
?>
And just to check things the button
<li><a class="trash" href=""> </a></li>
Thank you so much for your help, this has been bugging me for the last couple of hours.
It's not li.trash. It's a.trash because trash is a class of the a element. As such the first three lines of the js should be:
<script>
$("document").ready(function (){
$("a.trash").click(function(e){
and then so on with the rest of you code. I haven't checked the rest of your code necessarily, although I am pretty iffy about $(':checkbox:checked') as I don't think that's correct jquery.... To start off, I'd suggest fixing the first selector I mentioned, checking the second with jquery docs and then jshinting/jslinting your code. (Javascript only)
I don't know if its a typo in the question itself or the issue with your script but name of th e parameter while passing is "db" but on the server side you are expecting "mess_id"
Is it possible to get an element id into a PHP variable?
Let's say I have a number of element with IDs:
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
});
});
</script>
I need to pass $(this).attr('id') into $newID in order to run
SELECT * from t1 WHERE id = $newID
jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.
Thanks.
This is like your question: ajax post with jQuery
If you want this all in one file (posting to active file) here is what you would need in general:
<?php
// Place this at the top of your file
if (isset($_POST['id'])) {
$newID = $_POST['id']; // You need to sanitize this before using in a query
// Perform some db queries, etc here
// Format a desired response (text, html, etc)
$response = 'Format a response here';
// This will return your formatted response to the $.post() call in jQuery
return print_r($response);
}
?>
<script type='text/javascript'>
$(document).ready(function() {
$('.myElement').click(function() {
$.post(location.href, { id: $(this).attr('id') }, function(response) {
// Inserts your chosen response into the page in 'response-content' DIV
$('#response-content').html(response); // Can also use .text(), .append(), etc
});
});
});
</script>
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
<div id='response-content'></div>
From here you can customize the queries and response and what you would like to do with the response.
You have two "good" choices in my mind.
The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.
In this even callback, you'd initiate the $.post as you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).
The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Plugin to handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.
In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):
var order = [];
$('span.myElement').each(function(){
// N.B., "this" here is a DOM element, not a jQuery container
order.push(this.id);
});
return order.join(',');
You're quite right, something along those lines would work. Here's an example:
(btw, using $.post or $.get doesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post(document.location, { id: $(this).attr("id") },
function (data) {
// say data will be some new HTML the server sends our way
// update some component on the page with contents representing the element with that new id
$('div#someContentSpace').html(data);
});
});
});
</script>
Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location (I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.
If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.
$.post(window.location, {id: this.id}, function (data) {
//one
location.reload();
//two
$("#responsedata").html(data);
//three
$("#responsedata").load("affected_page.php #output");
});
I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in data above for jQuery to handle however you wish.
By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.