Update table with each input character - php

I've just asked a question on how to refresh an element without refreshing your page. I've been learning ajax for some hours now, but I'm having trouble getting any implemented.
So what I want to do is this:
Refresh a table containing mainly sql executions, for which I need the input value.
To update it I use onkeyup="Search();" which then forwards my value to another php page.
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
I know I can get this value on a php page like this:
<script type="text/javascript">
function Search() {
var inputValue = $('#IDsearch').val();
$.post('testAjaxJquery.php', {postname: inputValue},
function (data) {
$('#IDsearch').val(data)
});
}
</script>
and in PHP (testAjaxJquery.php)
<?php
$searchValue = $_POST['postname'];
echo $searchValue;
?>
The problem here is: I don't know how to use the retrieved value and update my existing table with it, without a page refresh. I tried putting all of the code inside a new php file and using $("#refreshOnSearch").load("refresh.php");, no luck.
The essence is: Once a letter is typed, I need an updated version of my table.
I guess you could say I am trying to replicate https://datatables.net/index.

Start with looking inside your $.post function.
Then inspect data using console.log(data) or debugger and looking at what data is. It's possible data is an object and you are trying to set #IDsearch to an object instead of a string or int.
If that is the case you will want to do something like $('#IDsearch').val(data.response);

Related

jquery php mysql html passing value on one page

im curious, if the value of <p class="myclass"></p> assign by jquery using $('.myclass').text('txtvalue'); can be fetch using PHP script? example. like i want to fetch the assign value of jquery without using jquery post, ajax to pass value in PHP because im do this with only one page.
here my code:
<p class='myclass'></p>
<?php
$a = strip_tags("<p>","<p class='myclass'></p>");
echo $a;
// the result is 100; but its dismase like im printing "<p class='myclass'></p>"; i im trying to do is to get exactly the value of "<p class='myclass'></p>". because the value of that, i will use to query in mysql id.
//it is impossible to me to do this?...
?>
<script>
$('.myclass').text('100');
</script>
No, this cannot be done.
PHP runs server-side and generates your HTML, including any Javascripts with jquery in it. When it's done, Javascript gets to work, client-side. The only way to get something back into PHP is to send it to the server by posting it, ajax, or redirection.

onClick add to database

I have the below code, and I'm not sure if it even works. Basically, I want to do a like system, whereby when I click on the link, it adds a +1 to the user's likes.
I've tried so hard to read up but I just don't get anything, and I found a code similar below.
When I clicked on the link, it does process my insert.php page, but I don't know how to get the variable values...
What should I do? I'm not sure if the code structure below is correct...
Thanks!
<script>
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
</script>
<div id="current-salary">
<a id="salary" onClick="insertSalary();">+1</a>
</div>
The variable will be in your php script as $_POST['salary']
The value of salary is passed as part of the post method in jquery.
So you can do:
$.post('script.php', {salary: 100}, function(data){...});
and this will pass the value 100 to your php script as the salary value.
In php the $_POST and $_GET hashes contain the data that you pass with a given request. In jquery $.post, $.get $.ajax create requests and take data hashes to build the data you want to pass with the request.
While this may work, I would recommend separating your logic from your website by putting the javascript in an external file and then link your HTML page to it.
I would also advise against declarative event binding which you have done by specifying onClick="insertSalary()".
jQuery provides a method to pro-grammatically assign functions to events using the on method. So for your code, you could use:
$('#current-salary').on('click', insertSalary());

Outputting variable value into innerHTML with JQuery and then storing it in PHP variable

Essentially, I'm attempting to capture the value of a HTML drop down menu and call a php function (i.e., print_wp_cart_button_for_product) with the user selected row. I have created a JQuery function which is called onchange, but have encountered several problems. By using alerts, I'm sure that the function is called and that the value is stored in currentrow. Additionally, by using the firefox web console, I know that order.php is called with the appropriate parameters. Originally I was using ajax success method, but the function was not being called, so I switched it to the complete method, which at least solved the fist problem. The second issue I'm dealing with involves storing the variable currentrow in the innerHTML of test. When I changed $('#test').html(currentrow) to $('#test').html("Complete") the string was outputted to the screen, as I would expect, but I've been unable to do so dynamically with the value of the currentrow. The last problem I've found involves saving the value of the test div tag into a php variable. I've attempted to use $_GET to capture the value and subsequently call my php function, but have had no luck.
<div id="test">
</div>
<script type = "text/javascript">
function productchange()
{
var currentrow = $('#productcategory1').val();
//alert(currentrow);
$.ajax({
type: "GET",
url: "http://www.example.com/wp-content/themes/themeX/order.php",
data: {'rownum': currentrow},
complete: function(currentrow){
//alert('COMPLETE');
$('#test').html(currentrow);
//$('#test').html("Complete");
}});
return false;
}
</script>
<?php $rownum = $_GET['test']; ?>
<?php echo print_wp_cart_button_for_product($products[$rownum]["Product"], $products[$rownum]["Price"]); ?>
Order.php
<?php
$rownum= $_GET['rownum'];
echo "Row number = $rownum";
?>
It seems like your <div id="test"></div> should really be <input type="hidden" id="test" name="test"/> within a <form>
Using a form element of some kind is the only way you can natively pass a value back to the server on submit.
In any case, the inline PHP code after your HTML will only work after submit of a form.
Here is a snippet of code that will submit a hidden form field to the PHP page allowing you to store the value in a PHP variable. First, do something like this on the main page which has your javascript.
<form method="post" action="storevar.php">
<input type="hidden" name="jsvar" id="jsvar" value="" />
</form>
Then, after you have calculated the value that variable should be in javascript, update the value of this hidden form field with Javascript/JQuery, like this:
function productchange() {
var currentrow = $('#productcategory1').val();
$("#jsvar").val(currentrow);
$.post('storevar.php', {jsvar: currentrow}, function(data) {
// do any additional coding with the result if need be
}
});
return false;
}
Then you could do something like this in storevar.php. Notice I'm storing it in a session so that it can be retrieved in other pages as well if you need to.
session_start();
$currentrow = $_POST['jsvar'];
$_SESSION['currentrow'] = $currentrow;
I hope that helps you. If you need any additional help, or if I've misunderstood something, please let me know and I'd be happy to help.

How to get an array of all checkboxes passed to the next page via _POST using JQuery

How to get an array of all checkboxes selected on the page, and then passing it to the next page (in this case php, so it can be picked up by php _POST function). I have come up with this :
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox:checked").each(function() {
selected.push($(this).val());
});
$('#od').submit(function() {
alert(this.selected); // *See note below
$.post('receiver.php', {'registration': selected});
return false;
});
});
</script>
But is does not seem to work :( It returns null, as if no checkboxes would have been added to the array, or maybe the post function is wrong. Can you point me in the right direction here?
I've found the following of issues:
You read the checked items on page load, thus ignoring all changes made by the user. Move that code to the submit() handler.
Your debugging code (alert(this.selected)) tries to display the value of the selected property for the form node. It isn't a reference to your JavaScript global variable selected. I suggest you use a proper debugging tool such as Firebug; alerts are highly unsuitable.
You sucessfully send the values of checked items. You just ignore the field name and rename everything to registration. That looks intended, otherwise report back:
{'registration': selected}
I suppose you can make jQuery serialize the values for you but fixing these little details in your code should do the trick anyway.
I think $("input:checkbox:checked") should be `$("input[type="checkbox"]:checked")
Or simply: $('input:checked', '#form-container');
$('#od').submit(function() {
var selected = $('input[type="checkbox"]:checked').toArray();
$.post('receiver.php', {'registration': selected});
return false;
});
The Data being posted might need to be split up.....

JavaScript functions give errors when loaded via Ajax

EDIT:
OK, I believe I've found a way around the issue using the info posted by #ManseUK along with #Johan's comment. As a n00b I can't answer my own question but I've added an explanation below the question in case it helps anyone else out.
I am re-writing part of an e-commerce solution which was written by
another development team some years ago. In the new version, we are
experimenting with shortening the user journey using Ajax but doing so
gives JavaScript errors and causes some functions to fail. Dev URL is
here:
http://cognition.thelightbulb.co.uk/type-18/general-purpose-lamps-and-bulbs/craftlight-daylight
The errors appear once the dropdowns have been selected and the
product displays.
The errors are displaying most notably in IE7:
Error: 'frm.qty' is null or not an object
Error: 'qty.value' is null or not an object
I believe this is where the problem is coming from:
var frm = document.frmOrder;
var qty = frm.qty;
In the lines above, frmOrder is the name of the form and qty is
the name of the input for product quantity.
Compare that to http://cognition.thelightbulb.co.uk/product-54 where
the product loads without the Ajax selection process and you'll see
that the functions work correctly.
I suspect that the problem is to do with the fact that var frm =
document.frmOrder; is not working due to the way it relates to the
DOM when loaded with Ajax.
I am using innerHTML=xmlhttp.responseText as the Ajax method. Is
there an alternative way to define var frm so that it will function
properly when loaded with Ajax?
EDIT:
Using the info posted by #ManseUK along with #Johan's comment, I added another argument to CheckMinQty(minorder) so that it now looks like this...
function CheckMinQty(minorder,qty)
...where qty is passed to the function on an onclick event as document.forms['frmOrder'].qty.value
I then moved the whole function out into a separate .js file. It's maybe not the best approach but it still feels tidier for the Ajax call to just return workable HTML which CheckMinQty can use rather than bringing in a whole load of <script> and then trying to run it.
Thanks for all the suggestions and I'd welcome any comments about the approach/solution outlined above.
Change this
var frm = document.frmOrder;
to this
var frm = document.forms['frmOrder'];
That will give you a handle to the form
document.frmOrder refers to the element with id frmOrder on the page, which happens to be the form on this page. Just try to get the correct form-element as the variable there.
Though the Manse's solution might work, use a more sensible way and assign an id to the form and since you're using jQuery anyway, retrieve the form with var frm = $(#formid); Not only is it easier to write, it's much more easier to read by you and everybody else.
When loading script via AJAX, you don't have DOMReady event anymore. In other words, when you want to execute your script on AJAX load, you should use self-invoked functions.
Wrap your ajax-loaded script inside a function like this:
(function(){
// Do what you want to do here.
})();
See if that solves the problem?

Categories