jQuery $.ajax success runs for one time only - php

I'm trying to implement a single-star rating (i.e. a like button).
I want to change (toggle) the star image. The only problem it seems to have is that while using $.ajax, on "success:" part, the src attr (or anything else really, like .css) applies for one (the first) time ONLY! In fact, the client has to refresh the page to see the latest star image/status (which loads from the db).
Here's the code:
<script language="javascript">
// Ajax: Star
$("#p<?php echo $pID;?>").find('.star').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "./ajax.php",
data: "pID=<?php echo $pID;?>",
cache: false,
success: function(html)
{
$("#s<?php echo $pID;?>").attr("src",html);
}
});
});
// END OF: Ajax: Star
</script>
the php file echos back a filename which is meant to be replaced with the src attribute (e.g. star-on.png OR star-off.png)
So I think the question is: Why the "success: function" triggers only once?

I finally realized what the problem is. It is due to the server side file (php) as it always evaluates the static data given from the client side file. All I need to do is refreshing the toggle's trigger on my php file.

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.

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 Ajax - reload Image onClick works with chrome but not with firefox nor with IE

Ok this is very spooky....
I'm trying to reload a CAPTCHA Image which is generated on the server side and I don't want to reload the whole page for that, hence I have to use AJAX.
So what I do is to first trigger a php file on server side (with AJAX), which updates all needed stuff so I can have a new CAPTCHA Image.
Then when this is done I simply update the image src="", to load the new image from that php file.
Here the code:
File 1
HTML:
<tr id="rowWithCaptcha">
<td><p><img id="captchaImg" src="./?<?php echo session_name() ?>=<?php echo session_id() ?>"/></p></td>
</tr>
JQuery-Skript:
$("#reloadImg").click(function(){
$.ajax({
url: 'getNewKCAPTCHA.php',
cache: false,
type: 'POST',
async: false,
success: function(){
$("#captchaImg").attr("src","http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?");
}
});
});
File two:
PHP:
kcaptcha.php is where all the captcha magic happends :)
so if you just open this php file in your browser, you'll get the captcha image itself.
And if you reload the page the image changes every time.....
<?php include('kcaptcha.php'); session_start(); $captcha = new KCAPTCHA(); $_SESSION['captcha_keystring'] = $captcha-getKeyString(); echo TRUE; ?>
So the weird thing now is that this whole thing (AJAX call and update of picture) is working just fine with the new chrome browser, but when I try it with FFOX or IE it works only one time and any further click doesnt change anything.....I think it has something to do with the JQuery part, but I just cant get it to work :///
Every help is appreciated!!!
Thanx in advance!
Assuming that
url: 'getNewKCAPTCHA.php',
and
http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?
are actually the same script, there is no need to call them twice.
Consider this simple method (it's working method I use in real projects):
$("#reloadImg").click(function(){
var d = new Date ();
var captcha = "http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?r=" + d.getTime ();
$("#captchaImg").attr ("src", captcha);
});
http://jsfiddle.net/hGfgn/
Regards
this might be corellating to the HTML5 support. i had the same problem not long ago and it seems that neither FF nor IE support
$('whatever').click(function(){});
but it could work if you call it with onclick="function()" in the html-tag, but i do not know if it works
I'm not a big fan of editing src attributes.
I would usually remove the image (or replace with a loading image) and then append the new image (and remove the loading image). The code below should remove the image and append a new image - I missed out all of the buffering image replacement stuff
$("#reloadImg").click(function(){
$.ajax({
url: 'getNewKCAPTCHA.php',
cache: false,
type: 'POST',
async: false,
success: function(){
$("#captchaImg").remove();
$("#rowWithCaptcha td p").append('<img id="captchaImg" src="http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?" />');
}
});
});
hope it helps

Ajax-returned elements do not trigger in jQuery

In the HTML, a dropdown with the ID="project_pick" will fire a change event, sending the selected value to the getallreports.php file. This works. The PHP file does a MySQL lookup and returns values inside some HTML. This also works, and looks great on the page. Here below is the jQuery/ajax code that sends the selected item to the PHP file:
$('#project_pick').change(function(e) {
$.ajax({
type: "POST",
url: "getallreports.php",
data: "project_id=" + $(this).val(),
success:function(data){
$('#reportstable').html(data);
}
});
});
The returned data appears inside the specified div, and includes anchor tags with specific IDs that should allow other JQuery events to happen. Snippet of returned HTML:
<table><tr>
<td>Report 1</td><td>click to change</td>
<td>Report 2</td><td>click to change</td>
</tr></table>
The jQuery code to trigger on the above click event is:
$('#change_1').click(function() {
alert('Change Report One was clicked');
});
However, clicking the above anchor tag does nothing. Also, the returned HTML does not even appear in the source -- although it shows on the screen and in firebug.
What am I missing? How can I get that click event to fire?
EDIT:
I've been reminded about the .on('click', etc) event (thanks Michael and Zirkms), but when I attempted to add it to my code the dropdown's .change event stopped firing. Perhaps the below code needs a facelift?
$('#project_pick').on(change(function(e) {
$.ajax({
type: "POST",
url: "getallreports.php",
data: "project_id=" + $(this).val(),
success:function(data){
$('#reportstable').html(data);
}
});
});
On the moment of $('#test').click() code execution #test didn't exist in the DOM, so you didn't bind that handler to somewhere.
Use
$(document).on('click', '#test', function() { ... });
instead
Or (better) if you have a particular node where you insert the retrieved html - use some particular selector rather than $(document) like
$('#reportstable').on(...)
does not even appear in the source
In the "view source" browsers usually show the response from the server as it was retrieved on request, without reflecting JS DOM modifications.

Load dynamic content from php on submitting a form

I have created a page "index.php" with a lot of divs and I need to refresh only one of the divs when the form is submitted.
This div loads the content from chat_window.php which is as follows:
<div id="chatbox">
<?php echo $res; ?>
</div>
<!-- Chat user input form-->
<?php echo $formchat; ?>
chat_window.php uses dynamic content - $res and $formchat from chat.php.
Everytime I post the form the content of $res and $formchat is modified and I need to reflect the same in my page which loads chat_window.php.
I used AJAX and jQuery to do the same as follows:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("input#chat").val();
var dataString = "chat="+ name;
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
}
});
$("#chatwrapper").load(chat_window.php);
return false;
});
});
The index.php has a div to show the chat_window as follows:
<!-- Chat window-->
<div id="chatwrapper">
<?php include ("chat_window.php"); ?>
</div>
As per my analysis, when I post the form, $res and $formchat are getting updated in the php. But when I load the chat_window.php, it doesnot loads the modified values. It rather loads the initial static values.
(Please dont suggest setInterval() as I dont want to refresh the page automatically).
Javascript is non-blocking, so it means that the interpreter does not wait for jobs to complete before processing the next one.
In your code, $("#chatwrapper").load('chat_window.php'); is being called pretty much before the ajax request above it completes. You will need to use the ajax success event to call the reload.
Try:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load('chat_window.php');
}
});
Try moving the .load() statement into the ajax success handler:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load("chat_window.php");
}
});
The $.ajax() call is asynchronous, which means that execution does not pause waiting for the response, rather, it moves on directly to the .load() call. (Which is also asynchronous, so really you've no guarantee about the order the response from each call will come in unless you don't make the second call until the first one finishes.)
I got my work done. Though I used another way of doing it.
What I have understood after few days of R&D is that, when we submit the form to a php, the request is sent with input params. When your php file processes this request, it might be updating some global variables. It completes processing the request and returns the control back to the calling index.php page.
The important thing to notice is:
The variable updates made while processing the form submit request do not persist after the control is returned. The global php variables will only get updated when the page gets refreshed.
So, if there is a strict requirement to avoid page refresh, collect the processed data from the php in some output string and pass it back to index.php like this:
$responseString = $res . "|" . $formchat;
echo $responseString;
The success parameter of .ajax will receive this output and accordingly you can update your chat window or any other form.

Categories