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.
Related
I already checked around for this answer but all are different problems just same title (to prevent random duplicate marks).
Here is an ajax call to the click of the filter button that should send the data inserted in the form formmatcat to the php file formfilt.php and should load the result in a div with id resultins
<script>
$(function () {
$('#filter').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize(),
success: function () {
$("#resultins").load('formfilt.php');
}
});
});
});
</script>
I set the preventdefault to load only in the div without redirecting to the php file and this works but if I put the preventDefault it echoes the string I build by concatenating values sent from the form with those empty values. The strange thing is that if I remove preventDefault of course it redirects and loads the php file but with the correct values:
Moral of the story, data in the form with the ajax call goes correctly to the php file but looks like preventDefault don't let this. Thanks in advance
Here's the structure of the html part with the form
<form id="formmatcat" method="post" action="formfilt.php">
.
.
various textboxes
.
.
</form>
What you're doing is sending an AJAX request toformfilt.php, when this call happens and it returns a response it will be stored as a parameter within the success or $.done function as I'll mention later, that is where your echo'd content will be.
What you're doing here is when the call is successful, you simple send a GET request to the same page. Since that GET request differs from the AJAX POST request and has no POST parameters you'll not get the correct output.
By simply submitting the form and letting it go to the page rather than cancelling the request you're getting the right values as you're directly posting to the page with the correct values, when you call the load function you're doing a seperate AJAX get request.
What load actually is, is a rough equivelant to $.get which is shorthand for $.ajax.
Looking at jQuery AJAX docs
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
Basically, a $.ajax() call returns a promise object that you can chain callbacks on when it is finished. Also note that data here will be the actual content within your PHP file, thus if you rewrite your AJAX call like so:
<script type="text/javascript">
$(function() {
$('#filter').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize()
}).done(function(data) {
$('#resultins').html(data);
});
});
});
</script>
It will then continue to load the output of formfilt.php into the div with ID resultins.
dont use form, use input without form, and use button tag use onclick to run function, if you use form, it will submit and redirect,
i'm not good with ajax on jQuery
but if i were to use javascript/XHR
var CB=document.getElementById("filter").value; //get input/filter value
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('contain').innerHTML=xhttp.responseText;
};
var url="formfilt.php?filter="+CB;
xhttp.open("GET", url, true);
xhttp.send();
if you want to use post :
xhttp.open("POST", "formfilt.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('filter='+CB);
sorry, i'm also learning, and new to this, just learning a week ago,
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.
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.
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);
}
});
$('#target').html(????????) or .ajax() ?
Need this to load a php page in the <div> with id target. How do I call that php page?
This is my problem it wasn't my setup it was trying to include the javascript variable obj.info:
function(obj){jQuery.ajax({'url':'/controller/\'+obj.info+\'','cache':false,'success':function(html){jQuery('#target').html(html)}})}
Whenever I try to work the variable obj.info it the function fails.
$('#target').load('url/to/php/script.php');
http://api.jquery.com/load/
$.ajax({
'url/to/php/script.php',
data: { 'varName': yourJsVariable },
success: function(response) {
// your php script returns HTML content
//
$('#element').html(response);
}
});
Check the page on .ajax() for more info: http://api.jquery.com/jQuery.ajax/