So i'm trying to use a table that generates multiple submit buttons per row. I'm doing this with a php while loop. Each button has a value of the corresponding "id" from the database. The table populates with everything from the database that has a status of "Ordered". On each row I can click a button that will change it to "Received" or "Cancelled". This is why I assigned a value of "id" to each button, so it only affects the status of the row that's being clicked. So far, all this is working fine but I would like to be able to do this using ajax instead of refreshing the page each time.
Currently I have this for my ajax:
$('#cancel').click(function(e) {
e.preventdefault();
//set value of cancel button to a variable
var value = $("#cancel").val();
$.ajax({
method: "POST",
url: "updatetable.php",
data: {cancel: value},
});
});
and this for my PHP:
//updatetable.php
if($_POST['cancel']) {
echo $_POST['cancel'];
}
the reason for the "if" statement is because I also need to click received but if yall help me figure this part out, i can go the rest of the way on my own.
Right now, I can't even get this to connect with a simple echo of the POST variable.
Just for reference, here is my html markup for the buttons:
<button type='submit' class='btn btn-danger' name = 'cancel' id = 'cancel' value='".$row['order_id']."'>Cancel</button>
<button type='submit' class='btn btn-success' name = 'received' id= 'received' value='".$row['order_id']."'>Received</button>
(the buttons are output by a PHP echo statement-hence the concats in the value setting)
I've tried to follow several tutorials but I can't figure out why this doesn't connect the right way. Perhaps I need to change it to an input with type "button" instead of button type submit? But then the actual value of the "value" would appear as the text instead of the word "cancel". Any help is appreciated.
you are going to want to put a unique identifier on your IDs. Here is what I would do (instead):
function cancelClick(btn){
e.preventdefault(); // I dont think this is needed
var value = $(btn).val();
$.ajax({
method: "POST",
url: "updatetable.php",
data: {cancel: value},
});
});
actually I would do this but that isnt what you used:
function cancelClick(btn){
var value = $(btn).val();
$.post("updatetable.php",{cancel: value});
});
then your UI like:
<button type='button'
class='btn btn-danger'
value='<?=$row['order_id'] ?>'
onClick="cancelClick(this)">Cancel
</button>
<button type='button'
class='btn btn-success'
value='<?=$row['order_id'] ?>'
onClick="otherFnName(this)>Received
</button>
edit: to perform a task on return you do something like this:
function cancelClick(btn){
var value = $(btn).val();
$.post("updatetable.php",{
cancel: value
}, function (d){
// here is where you will do stuff on return.
// I suggest first console.log(d); and see what is returning
// return (echo) a value to at least identify the row
// you are wanting to delete, if that is what you are attempting
// be sure the element you are attempting to manipulate has
// a unique identifier (id), and then do whatever.
// you can call a function from here also, to make it neater
// this area will `happen` when your ajax is complete.
});
});
Related
This should be really simple but it's after 2am and I'm struggling!
So I have a PHP file that outputs a database query in JSON format. The plan is then to use Columns (https://github.com/eisenbraun/columns) to format this JSON into a simple table.
The page has a box with a value, when clicking on this value, I want to use AJAX to get the result from my PHP script and display a table.
Currently, I have the table loading at the same time as the page;
<script>
$(document).ready(function(){
var json1 = <?php include($inc.'xx\sp1.php');?>;
$('#sp1').columns({data:json1});
var json2 = <?php include($inc.'xx\sp2.php');?>;
$('#sp2').columns({data:json2});
});
</script>
with the links on the value being;
<a class='btn btn-secondary' data-toggle="modal" href="#sp1">
<a class='btn btn-secondary' data-toggle="modal" href="#sp2">
How can I set the variables (Json1 & Json2) and load the data via an AJAX on click event? I know it's staring me in the face and it's hugely frustrating!
Really simple one to be fair but I'll use alcohol and tiredness as an excuse!
$('#hf1djm883j').on('click',function (e){
$.ajax({
type:'GET',
url :"includes\\files\\private\\798shwo3ixxd\file6llps.php",
dataType: 'json',
success: function(data) {
$('#mmshh5e').columns({data});
}
});
});
At present I have a like/dislike function on my website, which submits SQL to a database on POST, and uses GET to retrieve the product ID and the product category, so after clicking like it currently refreshes and the link appears as:
"/index.php?id=106&category=Entertainment"
I've been looking at AJAX and figured out how to use it to submit SQL to the database without having to refresh, but I can not get it to submit when I need to submit GET variables too. I'm wondering if anyone knows anything about this as I've been trying everything and haven't been successful. Currently the code for this function looks like the following:
Index.html:
<form class="form-horizontal" action="?id=' . $productData->getID() . '&category=' . $productData->getPcategory() . '" method="post">
<button id="like" type="submit" name="like" value="like" class="btn btn-success" onclick="javascript:return like();"><i class="glyphicon glyphicon-thumbs-up"></i></button>
</form>
Index.php:
if (isset($_POST["like"])) {
$productDataSet = new productDataSet();
$productDataSet->addLike();
$likeDislike = "Product has been added to your <b>likes</b>.";
}
AJAX Function (works in other areas of my website where there are no GET variables needed):
function like()
{
$.ajax({
url: "index.php",
context: document.body
}).done(function() {
});
return false;
}
I know I need to add this code in order for the script to be able to read the GET variables on POST but I don't know what to add, any help would be greatly appreciated.
Thanks.
Generally this is quite a simple task, all you need is to configure an event handler, assuming you're using jQuery (Which you appear to be) the following should do for your javascript:
$(document).on('click', 'a[data-ajax-submission]', function(e)
{
var link = $(this);
var action = link.attr('data-ajax-action');
var id = link.attr('data-resource-id');
if(action == undefined || id == undefined)
{
return;
}
e.preventDefault();
$.ajax({
url: yourUrl, // Will need to set, could also use a data attribute again
type: 'POST',
data: {
action: action,
id: id
},
dataType: 'json',
context: document.body
}).always(function(response)
{
// Do stuff here
})
});
This will cause clicking any element with a data-ajax-submission attribute to trigger this event.
We then take an action, and an id from the other data attributes and send them to the sever as POST data in the ajax request, usage example below:
<a data-ajax-submission data-ajax-action="resource-like" data-resource-id="1">Like</a>
I have used the term "resource" as a placeholder, this could be "product" "category" whatever.
Then in PHP you can just handle it like any other form request:
if(isset($_POST['action']) && $_POST['action'] == 'resource-like')
{
// Check for an ID & any other validation
// Persist, do stuff, etc...
die(json_encode(array(
'success' => $success
)));
}
This is a flexible solution, and should allow you to perform several tasks without having to further modify the JavaScript aspect.
It's worth noting, that typically for like, dislike, vote etc... behavior, you will need to limit the voting to one per visitor, usually achieved by setting a cookie.
Let me know if you have any follow up questions etc...
I'm not sure I understand the problem, but if you want to submit GET and POST variables at the same time, you can try this dirty trick :
$.post( "someFile.php?var1=value1&var2=value2", {
var3 : value3 ,
var4 : value4 })
In PHP, read :
$_GET['var1']
$_GET['var2']
$_POST['var3']
$_POST['var4']
I have a PHP script that calls the Twitter 1.1 API, and returns 50 ID numbers. Then I am using a Foreach argument to print the results individualy on to the page. I want to store each different ID number inside a button as a hidden value, and then use JQuery Ajax to post that value to a different PHP page for further processing without leaving or refreshing the page of 50 ID numbers.
If I use this Foreach argument, the 50 ID numbers are ALL the first result in the array, rather than being 50 individual ID numbers which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='RT' onsubmit='return submitForm();'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>
");
}
But, If I remove this section from the Foreach argument, 50 individual ID numbers are printed into into hidden values of the forms:
onsubmit='return submitForm();'
The problem is my JQuery script is listening for submitForm and without that line above the JQuery will not run. Here is my JQuery script:
<script>
function submitForm() {
$.ajax({type: 'POST', url: 'results.php', data: $('#RT').serialize()});
return false;
}
</script>
I know that removing onsubmit='return submitForm();' gives me 50 unique ID numbers from the Foreach, because this code will print 50 buttons which will each contain individual values. But because there is no JQuery script listening for submitForm I have to add method='post' action='results.php in order to POST the value of the button but this means the page results.php loads which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='form' method='post' action='results.php'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>");
}
So, I want the foreach to print 50 unique ID numbers, while also letting me use the JQuery Ajax script. I hope this is clear, I don't know how else to describe what I want to do :D
Okay, now I understand what you're trying to do. I would do it like this.
PHP:
<?php
foreach ($results as $arrResult) {
$tweetId = $arrResult['id_str'];
print('<button type="button" class="mark-tweet" data-tweet-id="' . $tweetId . '"><br/><br/>');
}
JavaScript:
$(function() {
$('.mark-tweet').click(function() {
var id = $(this).attr('data-tweet-id');
$.ajax({
type: 'POST',
url: 'results.php',
data: {tweetId : id}
});
})
.done(function() {
alert('The tweet has been deleted');
})
.fail(function() {
alert('Oops, something went wrong! Please try again.');
});
});
NOTE: I am not capitalizing the 'r' in $Results as you did. Only class names should start in capital letters (class as in OOP, not CSS)
OK, we've got you now. You're on the right track to use an ID, and this is straight-forward.
What you need to render are 50 buttons with onclick that will call your markTweet() JS function & pass it the ID -- and that can do the AJAX post. No form required.
Alternatively, you can render 50 forms with separate IDs ('form'.$tweetId), each with a hidden input & submit button (or just a <button>, since the BUTTON element can have a name & value distinct from its content), and an onclick that calls `postTweetForm('form${tweetId})' -- thus passing the ID of the selected form to your JS function.
Really, since you're doing it in JS, keeping the UI simple & letting JS do the work is easiest. Here's an example to get started. PHP:
foreach ($Results as $arrResult) {
$tweetId = $arrResult['id_str'];
print("<button type='button' onclick='markTweet('".$tweetId."');'><br>\n");
}
Javascript:
function markTweet (tweetId) {
$.post({
url: 'results.php',
data: {'tweetId': tweetId}
);
}
You should also put in a success handler into your AJAX post.. fade in a little green tick or something so the user knows it's worked, because it doesn't always. (I'll let you play with that.)
Try that.. and keep the question up. It's much improved now & may be able to help someone else.
I have a button that when it is pressed calls an ajax function with some parameters and then the ajax posts some values on the database. The user might use this form a lot of times before he leaves the application or refreshes the page. Up to now, this works great!
In my last update, I added a checkbox that will hold one more piece of information that I want to be saved on the database using the aforementioned ajax function. So, when the button is pressed, I check if the checkbox is checked and I send to the ajax function true or false. Up to now, this works great too!
What doesn't work great, though, is the fact that the last features works properly only for the first time! Every other time the user hits the button, no matter what the checkbox checked state is, it will submit the state it was the first time. It is like the checkbox.checked property freezes after the button is pressed for the first time.
It might be irrelevant, but I also tried the same with toggle buttons and I get the same issue!
Do you have an idea on how to overcome this problem?
Thanks a lot!
Here is the code:
The form: It has 1 toggle button and 3 buttons that call the sendTask function.
<button type='button' class='btn btn-info' data-toggle='button' style='margin-top: 5px; width: 216px; height: 40px;' name='yesterday".$category['id']."' id='yesterday".$category['id']."'>This one was yesterday!</button></div>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '1', yesterday".$category['id'].")'>0-15min</button>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '2', yesterday".$category['id'].")'>15-60min</button>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '3', yesterday".$category['id'].")'>60+min</button>
The sendTask function:
function sendTask(category, weight, checkbox){
var ieri = $(checkbox).hasClass('active');
TaskSubmit(category, weight, ieri);
};
The TaskSubmit function:
function TaskSubmit (taskidsubmitted, weight, ieri) {
$.ajax({
url: 'submit_task.php?taskid=' + taskidsubmitted + '&weight=' + weight + '&ieri=' + ieri,
success: function (response) {
if (response !== "fail") {
document.getElementById('score-label').innerHTML = response;
} else {
document.location = "index.php";
}
}
});
}
The problem is that this line:
var ieri = $(checkbox).hasClass('active');
only changes the fist time a button is pressed. All the other times keeps the first state (true or false).
I believe you should be using .prop().
function sendTask(category, weight, checkbox){
var ieri = ($(checkbox).prop('checked') != undefined);
TaskSubmit(category, weight, ieri);
};
The browser -should- remove this property if the checkbox is unchecked. If this is not the case, use console.log() to find out what it is doing.
In your html, you are passing yesterdaySomeCategory to the function, instead of "yesterdaySomeCategory". I am not sure what jQuery does with that, but the normal way of selecting an element is by $("#yesterdaySomeCategory"). Try changing it to
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '1', \"#yesterday".$category['id']."\")'>0-15min</button>
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!