Load a new value into an input from PHP with jQuery? - php

I have some input like:
'<input type="text" name="display-count" class="display-count" value="23" autocomplete="off" readonly="readonly" />';
And I'm using this jQuery code to remove the value it has and replace it with another one:
var count = $('form.user-count-form').find('.display-count');
$(count).val('');
$(count).load("admin/user-count.php");
But the new value it isn't loaded. I have tried some other ways like:
$(count).val().load("admin/user-count.php");
or
$(count).val(load("admin/user-count.php"));
But didn't work as well. How do I do what I want ?

You need to use the JQuery get method here. You are improperly calling the script from your server and therefore, no call is actually firing and no data is being returned. I'm assuming that the value you are getting is a single string of either text or numbers.
the question is a bit vague so I'm not sure why you have the initial value set at 23 and I'm also not sure when you want to change the value so I am going to show you how to do it upon the dom being ready using the $(document).ready method.
$(document).ready(function(){
$.get('admin/user-count.php', function(data){
$('.display-count').val(data);
});
});

depends of what your script returns
you can do it so, for example:
$.ajax({
url: 'admin/user-count.php',
success: function( data ) {
$(count).val(data);
}
});
In additional you can return you user-count in JSON format, using php-function json_encode()

why dont your just try this
$('input.display-count').load("admin/user-count.php);
or try this onLoad of your HTML doc
$.get('admin/user-count.php', function(response){
$('input.display-count').val(response);
});

.load() will return the Html Contents to matched Element ,it wont set any value. Better you can use $.get or $.post or $.ajax
$.get('admin/user-count.php', function(resultdata){
$('input.display-count').val(resultdata);
});
or
$.ajax({
url: 'admin/user-count.php',
success: function( resultdata ) {
$(count).val(resultdata);
}
});

Related

How can I use a jQuery var in some php code?

I know there are a few topics on this subject, but after I spent 2 or 3 hours trying to get something good out of them, I just decided to ask this question on a specific point.
So here is my problem : I have got a table and I am using a jQuery function to select a row of this table. Now what i actually want to do is getting the text content of the div contained in the first td of the row.
I already used a getter on it and I am checking the getted value with an alert as you can see in th following code :
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
});
So now, what I am trying to do is to send the myValue variable through an ajax request by replacing my alert by this piece of code :
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(rs)
{
alert(myValue);
}
});
Then, back to my php code, I am tring to observe the obtained variable by using an echo, just like this :
<?php echo $_GET['myValue']; ?>
But there is just no way for me to know if my page got it beacause the echo just prints nothing... So i was wondering if someone could do something for me. Thanks.
PS : Oh, by the way ; I don't really know if this can matter, but my page index.php already receives data by a post.
You can't, but read this, php is on the server, while js usually runs on the client, but your ajax trick can work. Just do some processing in the recieving php.
I usually put my ajax recieving end in a different file, and process the rest by the variables posted.
Just try to put the $_GET['myValue']; into an if, or a switch.
Do a var dump of the request var to see if anything is coming through:
<?php
var_dump($_REQUEST);
If not, do a console.log() on 'myValue' to make sure it exists before sending the ajax request - the issue may lie in your js rather than you php.
If you are POSTing data then adjust accordingly - e.g.
$.ajax({
type: 'post',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('successfuly posted:');
console.log(data);
}
});
then:
<?php echo $_POST['myValue']; ?>
If you were using GET your data would be in the url, e.g:
index.php?myValue=something
I'm not sure if you are aware of that, but you should wrap you function in document ready statement as below.
Next, call the AJAX request on some action, in this case we can use a click on the row in table.
$(document).ready(function () {
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('you have posted:' + data.myValue);
}
});
});
});
Okay so it seems that i totally misunderstanded on the way that the $.ajax function works.
I now do use the $.post function (which is actually the same), this way :
$.post('pageElement.php', { myValue : $(".selectedRow .firstTd div").text() },
function(data) { $("#test").html(data); }
);
The url "pageElement.php" refers to a page containing this code :
<div><?php echo $_POST['myValue']; ?></div>
The function called at the end of the process just puts this code into a div of my original page, so i can use it as a php variable now and then send it to another page through a form.

jquery send all html variable by ajax

I want to pass html all tags value to another file using ajax.
is this possible
$.ajax({
url:"myp.php",
type:'POST',
data: //here I want to all possible element values in current html
});
Any Ideas???
$.ajax({
url:"myp.php",
type:'POST',
data: $(':input').serialize()
});
If you want to post every possible element values from a special form:
$('#myForm').serialize();
I think you could do the same with a different selector, which will include every elements to submit:
So, something like this should do the trick:
$('input, select, textarea').serialize();
You can see here for jQuery.serialize() : http://api.jquery.com/serialize/
And there for similar questions : Serialize form data to JSON
you can post all form's elements using this
data : $('#form').serializeArray();

Simple jquery ajax php request

I am doing a basic jquery ajax call on a php file and can't seemsto figure out why it isn't working. Any help is appreciated. Fiebug does not seem to show any ajax or XHR action going on. I want to not to refresh the page and just execute the ajax call. Thanks.
JS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
<script>
function getData(url_param){
$.ajax({
type: 'get',
url: 'data.php',
data: {url_param:url_param},
success: function(data) {
$('#data').html(data);
}
});
};
$('#clickMe').click(function(e){
e.preventDefault();
getData(2);
});
</script>
HTML:
<div><a id='clickMe' href='data.php?url_param=url_param'>CLICK ME TO RUN PHP</a></div>
<div id="data"></div> <!-- divto show result -->
PHP:
<?php
if($_GET['url_param']){
echo "simple ajax call";
}
?>
You have to bind the event inside an onload function. The most common practice is:
$(document).ready(function(){
$('#clickMe').click(function(e){
...
});
});
You should also add return false; in the last line of your event.
First, you have misspelled your function name (getGata != getData).
Secondly:
data: {url_param:url_param}
Are you setting the javascript variable url_param anywhere? The $.ajax data parameter is formatted as follows:
get/post variable name : get/post variable value
As you have it now, it doesn't seem that you are assigning a value to url_param.
you can simply use jQuery post function.
$.post('data.php',{param1:'your param 1', param2 : 'your param 2'}, function(response){
//do your operation here. response is what you get from data.php. 'json' spicifies that the response is json type
$("#data").html(response);
},'json');
The (amended?) JavaScript prevents your code from working, because you haven't closed the angle brackets on jQuery source, it should be:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
One of the comments states you shouldn't have the href in the anchor, but because you've ignored defaults this isn't triggered (assuming JS is enabled in the user's browser).
Finally, I think that
return false;
should really be inside the function after
getData(2);
but since we're ignoring defaults, the anchor shouldn't make an attempt to go anywhere or reload anyway.

Ajax jquery returns blank page

I have this JavaScript code:
$(document).ready(function(){
$('#sel').change(function(){
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+$(this).val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
On status change i need to refresh a div without page reload. But it returns blank page. If i try alert the result on success, i get the response, also i checked with inspect element, its ok. The problem is that it returns blank page.
The file i'm working on, is the same( modules.php?name=TransProject_Management&file=index ) i called in ajax.
the html:
<body>
//...
<div id="ajax_results">
//.....
//somewhere here is the select option <select id="sel">......</select>
//.....
</div>
</body>
Any help, would be very appreciated.
use the following code to return your response html:
echo json_encode(array($your_response));
Then in your javascript, you will need to reference the data as:
success: function(data) {
$("#ajax_results").html(data[0]);
}
since it is now an array.
this in your ajax function refers to the jQuery XHR object, NOT the $('#sel') object. Just assign it to a variable before the ajax function like var sel = $(this) then use it later inside the function. Try this:
$('#sel').change(function(){
var sel = $(this);
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+sel.val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
Hmm, first glance the code looks good. Have you tried using Chrome debug tools? Hit F12 and check the Network tab, this will show you what is being returned. You can also debug without using an alert so you can step through to see what exactly the properties are.
Just thought, you might need to add 'd' to the data returned. Anyway, if you do what I suggested above, put a pause break on the line and run the code you will see what you need.
Based on your comments below the question, it seems that you are using the same script to display your page and to call in the javascript. This script seems to return a complete html page, starting with the <html> tag.
A page can only have one <html> tag and when you try to dump a complete html page inside an element in another page, that will lead to invalid html and unpredictable results.
The solution is to have your ajax script only return the necessary elements / html that needs to be inserted in #ajax_results, nothing more.

jquery.post() and php

I'm using $().post and php to change the contents of a <textarea>.
The script is succeeding - firebug clearly shows that the text in between the textarea tags has changed, and my little alert fires.
The user, however, doesn't see the changes. In Firefox the change doesn't occur at all, and in IE, the textarea updates up to 10 seconds late.
Here's the jquery I'm using:
$(document).ready(function() {
$('#pv_list li:first').addClass('hilite');
$("input[name='db_entries']:first").attr('checked', 'checked');
$("input[name='db_entries']").click(function () {
$.post("changeEntry.php", {post: $(this).val()}, function(data) {
$("textarea").text(data);alert('done');
});
$('#pv_list li').removeClass('hilite');
$(this).parent().addClass('hilite');
});
});
At first I thought it was because the page didn't validate, but it validates xhtml transitional.
The thing that's really bugging me is I had it working earlier and can't figure out what I changed.
Set .val() instead of .text()
Stackoverflow Archive:
Set Value of Textarea in jQuery
Insert text into textarea with jQuery
How to retrieve the value of a textarea with Javascript
Appending input-value to textarea-value
Have you tried using val() to set the value of the textarea instead of text()?
$.post("changeEntry.php",{post: $(this).val()},
function(data) {
$("textarea").val(data);
alert('done');
});
Wouldn't it be easier to use the load() function?
$("input[name='db_entries']").click(function () {
$("#outputarea").load("?", {"paramName":this.value});
});
I'm not sure, but one possibility is that you should do:
function(data){
$("textarea").attr("value",data);
alert('done');
}

Categories