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});
}
});
});
Related
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.
});
});
Thanks for reading. I have tried the answers in other similar questions but none have worked so far. I'm trying to UPDATE values inside a Table that is inside a form, so in the first part of the file is the isset "saveImport" which is the name of the a tag that I'm using to send the id thru the URL:
if (isset($_POST['saveImport'])) {
$id = $_POST['id'];
}
a tag:
<a name="saveImport" href="./?id=<?= $row['id']; ?>" class="saveImport btn btn-success col-xs">Save</a>
I do get the ID value in the URL but since is been updated in the same file I'm assuming it refreshes the page before the variable gets post thru AJAX:
<script type="text/javascript">
$(document).ready(function() {
$('.saveImport').click(function() {
var imp_id = id.id;
var imp_href = $(id).attr('href');
alert(imp_href);
$.ajax({
url: "./",
data: {id : imp_id},
type: "POST",
success: function(data){
alert(id);//send this ID to the PHP variable without
//refreshing the file
}
});
});
});
I'm getting the class .saveImport because it's inside a Table which is displaying values from a Database so it's inside a while loop and if I use an ID it will cause conflict as the ID will repeat itself.
I already created the PHP function to UPDATE the Values which executes if the ISSET is true, so my real problem will be to execute the ISSET and inside grab the ID that was posted with AJAX so I can use the ID in the UPDATE function. Right now, if I click on the a tag, it sends the ID thru URL, the page refreshes but the value of the ID is not getting in the $id = $_POST['id];
I appreciate your time.
This should work.
Change the ajax url to your php file name (mine was t.php).
Replace 99 with your data from php. (id is used. href is not used)
<?php
if (isset($_POST['saveImport'])) {
print_r( $_POST );
exit;
}
?>
<a name="saveImport" id='99' href="./?id=99" class="saveImport btn btn-success col-xs"'>Save</a>
<script type="text/javascript">
$('.saveImport').click(function(event) {
var imp_id = this.id;
$.ajax({
url: "t.php",
data: {id : imp_id, saveImport: 1},
type: "POST",
success: function(data){
alert( data );//send this ID to the PHP variable without
//refreshing the file
}
});
event.preventDefault();
});
</script>
.preventDefault() will prevent the link from loading the target page... And then, ajax will proceed.
$('.saveImport').click(function(event) {
event.preventDefault();
First, sorry for my English, you can correct me in that area too :)
I know that i can replace text in html with <?=$var?> for example. Also, i can do it through ajax. I use $.ajax to get data in JSON format, than inside jquery i'm changing appearance of my web app.
This is example of getting data, and inside this function i'm calling $.View function where apperance is changing.
$.Model = function(route, data){
$.ajax({
url: "php/books.php?"+route,
type: "POST",
data: {data: data}
}).done(function(response){
var resp = JSON.parse(response);
$.View(route, resp, data);
}).fail(function(msg){
console.log('something is wrong');
});
});
};
Example of $.View function
$.View = function(route, response, data){
if(route==='menuItem'){
var studio='';
$.each(response, function(index, value){
studio += '<button id='+value['STUDIJI_ID']+' class="btn btn-primary studio_button">'+value['STUDIO']+'</button>';
});
$(studio).appendTo(".here");
}
};
So, my question is, what is the best approach for such things? Embed PHP variable to html or do it through jQuery on described way? Or, something third?
Thank you for your time and help.
It depends on your requirements.
If you know everything on page creation, insert the values with php.
If you wnat to update only parts of your page after page is loaded, do it with ajax.
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 had to ask this one again, sorry. So I am running this jQuery to slide toggle a span in my PHP loops output. I have some PHP that generates some calls to the db to get more detailed information back for each item.
I know so far I have got it making the call to the PHP script. I can see the packets returning with the HTML echoed from the PHP file. but I'm having difficulty getting jQuery to insert the returned data into the specified span.
This is a simplified version of what the loop items look like:
<span class="searchitem">
<span style="visibility:hidden;" class="name">some name</span>
<span class="btn">Details</span>
<span class="itemdetails" style="display: none;">
//hidden area to populate with returned ajax html from php script
</span>
</span>
<span class="searchitem">
<span style="visibility:hidden;" class="name">another name</span>
<span class="btn">Details</span>
<span class="itemdetails">
<div>
<p>
this is the area i need the html to populate
</p>
</div>
</span>
</span>.................
This is the jQuery that I'm trying to run. I know everything works up to success. I can't get the data from there.
<script type="text/javascript">
var ajax_load = "<img src='images/loading.gif' style='width:50px;' alt='loading...' />";
var loadUrl = "ajax/item_details.php";
$(document).ready(function ()
{
$('.searchitem').each(function () {
var itemname = $(this).find('.name').text();
var ename = encodeURI(itemname);
var requestUrl = loadUrl + ename;
$(this).find('.itemdetails').hide();
$(this).find('.btn').click(function ()
{
var returned = "";
$.ajax({
type: "GET",
url: loadUrl,
data: "name=" + ename,
dataType: "text",
error: function () { alert("error") },
success: function (data) { $(".ptavail").append(data); alert("successful") }
});
$(this).parent().find('.ptavail').html(ajax_load).slideToggle(1500).html(returned);
});
});
});
</script>
As you can see from the code I'm trying to get the click function the set everything off. I know the PHP file is receiving the call and returning the data but I'm stuck trying to get the jQuery to fill the .itemdetails with the returned data.
What is wrong with this? Would I need to put the AJAX into a separate function for it to behave like I need, or do I need to make it synchronous for it to work? I'm trying to basically replace everything between .itemdetails spans with first a loading symbol and then the data returned with AJAX.... As it is now I get error alert so there's something wrong with the ajax call I know it does the request properly and the PHP returns the results but getting AJAX to read them is proving problematic.
I can see that the content type in the headers is text, so how do I get the AJAX to do the call properly?
Put $(this).parent().find('.itemdetails').html(ajax_load).slideToggle(1500).html(data);
inside the "success" part of the Ajax request.
success: function(data) {
$(this).parent().find('.itemdetails').html(ajax_load).slideToggle(1500).html(data);
}
The success function is there to say "when the Ajax has worked, do this"