Right now, what i'm trying to do is to replace a label on the front page with a block of html. Right now, the page basically has:
<label id="replace"></label>
the js currently has:
$(document).ready(function(){
$("#replace").load('/test');
});
the Zend class function has:
public function indexAction(){
$this->_helper->layout()->disableLayout();
$this->_view->message = "This is from TestController index";
}
and finally the index.phtml template simply has:
<?php echo $this->message;?>
Right now, I want to change the code around so that instead of just replacing that label with the same message, it would do a POST where the function will pull out a parameter, do something (like for instance, go to the database and pull something out with the POST parameter) and then return the message.
I've tried editing the js so that it would look like:
$.post('/test', {param : "test_param"},
function(data) {$("#replace").html(data);});
or
$.ajax({
type: 'POST',
url: '/test',
data: "{param:test_param}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {$("#replace").html(data);}
});
and neither worked. I took a step back and tried to replicate the .load functionality and do:
$.ajax({
url: '/test',
success: function(data) {
$('#replace').html(data);
alert('Load was performed.');
}
});
and it doesn't work either.
Anyone have any tips on how to go about doing this?
Are you sure that you can call /test directly with out using ajax? Also see what is the absolute url you are calling to. Try adding error callback and see it works, it will give you the error response which will help you fix the problem.
The original .post code you have looks right
$.post('/test', { param: "test_param" }, function(data) {
$('#replace').html(data);
});
You can also try looking at your browsers JavaScript console to see if any errors are being reported.
Is your controller set to auto JSON encode the view parameters?
Either way I think your supposed to access it like
{ success: function(data) {$("#replace").html(data.message); }
Related
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 a web application which features a bunch of different items, which are generated from a MySQL table. As users scroll through it, I want them to be able to click a link next to the item which will insert the request into a MySQL database. Normally, I’d do this by creating a PHP page (which I will do anyways) that grabs the item name & user id from the URI using the $_GET method & inserts it into the table. However, in this case, I don’t want the users to be redirected away from wherever they are. I just want the link to send off the request, and maybe display a small message after it is successful.
I figured jQuery/AJAX would be best for this, but as I’m not too familiar with it, I’m not sure what to do. Any tips are appreciated!
You have to do something like
$('.classofyourlink').click(function(e){
e.preventDefault();//in this way you have no redirect
$.post(...);//Make the ajax call
});
in this way the user makes an ajax call by clicking a link without redirecting. Here are the docs for $.post
EDIT - to pass the value to jQuery in your case you should do something like
$('.order_this').click(function(e){
e.preventDefault();//in this way you have no redirect
var valueToPass = $(this).text();
var url = "url/to/post/";
$.post(url, { data: valueToPass }, function(data){...} );//Make the ajax call
});
HTML
<a id="aDelete" href="mypage.php">Delete</a>
Script
$(function(){
$("#aDelete").click(function(){
$.post("ajaxserverpage.php?data1=your_data_to_pass&data2=second_value",function(data){
//do something with the response which is available in the "data" variable
});
});
return false;
});
See http://api.jquery.com/jQuery.ajax/
$('#my-link').click(function(){
$.ajax({
url: "mypage.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
return false;
});
$('.classOfYourLinkToBecliked').click(function(){
$.ajax({
type:'GET',
'url':'yoururl',
data: {yourdata},
processData: false,
contentType: false,
cache: false,
dataType: 'json',
success: function(response){
alert(response);
}
});
});
I'm not sure this question has the best of titles but I'm not sure what else to call it so sorry for that.
I'm using ajax to pull in content for a div on my website (after an option is selected). The content is a form generated by a PHP script. When the form is submitted a JavaScript function should be called but I'm just getting an error that says the function can't be found.
The JavaScript is pulled in via ajax with the form and I can't really change that as it needs to change demanding on the option selected.
My question is should this work? if not I'll just have to re think the way I'm doing it, just wanted to check if it wasn't working because it never will or if I'm doing something wrong.
I would show the code but it's very long.
Thanks in advance!
Edit: thanks for all the comments ect, apologies for not including the code before here it is.
function select(id){
$.ajax({
url: 'select/'+id,
type: 'GET',
dataType: 'html',
success: function(msg) {
$('.product_details').html(msg);
return false;
}
});
}
Are you using a javascript library?
With jQuery specify a data type of html and make sure the script tags are before the HTML in the response
$.ajax({
url: "something.php",
dataType: "html",
success: function(data, text, request) {
...
}
});
in mootools...
var myRequest = new Request({
url: "something.php",
evalScripts: true,
onSuccess: function(responseText, responseXML){
....
}
});
myRequest.send();
Now your passed tags will be evaluated and available to the DOM
I make this code that, after 9 seconds, it call an ajax function, and print the result elaborated from the server to the client.
This is the JS code :
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
$('.menusponsor').hide().fadeIn(1000).html(msg);
}
});
}
$(document).ready(function() {
x=window.setInterval("changeSponsor()", 9000);
});
the result is printed on a div at the top of the page. when the result is printed to the client (after, as said, 9 seconds), and I am at the bottom of the page, the page go automatically at the top. I don't want this.
You can see an exemple at this link : open this page, go to the bottom (is not so long this page) and after few seconds (9). You will se the page scroll at the top.
How can resolve this problem? Cheers
It doesn't look like anything that you mention would move the page up, it must be something else?
I found that the page moves up normally when you do something to the url, like adding a hash (#)? are you adding a hash or altering the url in any way?
solution:
oh the problem is with your html, you need to hide the child of menusponsor and not the container itself.
try this
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
$('.menusponsor').find('div').hide().fadeIn(1000).html(msg);
}
});
}
Can you tell us a little more about what happens when the page jumps to the top? Are you calling this function somewhere other than this setInterval?
What does your html look like? If you're replacing a huge portion of the page, it's possible that, for a split second, the page is very short, putting you at the top of the page.