jQuery ajax request awkward issue - php

So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?

Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.

Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});

Related

send data by Jquery ajax to same php

i need help because i'm stuck and don't know what's wrong ,i try to send user clicked button "id" to php to get related data from database in the same page
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
console.log(res, data);
},
error: function(err) {
alert(err);
}
});
});
the ajax print success in console log ,here is php code to get the value if clicked id
<?php
if(isset($_POST['ToEditId'])){
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
}
but nothing happen in php file !!
Which is the expected behaviour.
PHP is not dynamic. It doesn't "update".
PHP only runs once. This means that once your page is rendered, you cannot use PHP to change it again. You actually would have to use javascript to change the page, like so;
PHP side:
<?php
if(isset($_POST['ToEditId'])){
echo $_POST['ToEditId'];
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
die(); // prevent entire page from re-rendering again.
}
JS side:
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
//Add your PHP file's response to the body through javascript.
$('body').append(res);
},
error: function(err) {
alert(err);
}
});
});
As #IncredibleHat mentioned, you should make sure your page doesn't render any of its usual HTML, so it won't return the entire page back to your ajax call. So put the PHP all the way above your html!

Yii ajax call and session handling

I stucked in Yii, with an Ajax call "bug". The problem is, that i have to search by checkboxes, wich are stored in SESSION after hitting the search button.
After this, the keywords inserts into SESSION, and i want to print them in a tag-cloud. (with a cross in the corner -> delete this tag).
The removal of these tags is handled by an ajax call:
$(".tags a").click(function(e) {
e.preventDefault();
var class1 = $(this).attr("class");
var id = $(this).attr("id");
$("#checkbox__"+id).removeAttr("checked");
jQuery.ajax({
url: "recipe/removeFromSession",
type: "POST",
data: "id=" + class1+"&rcp="+id,
dataType: "json",
"success": function(data){
location.reload();
},
"error": function(xhr, status, error) {
var err = xhr.responseText;
alert(xhr.status);
},
"cache" : false,
});
});
It calls the removeFromSession action:
public function actionRemoveFromSession() {
$remove = intval($_POST['id']);
unset($_SESSION['searchItems']['category'][$remove]);
unset($_SESSION['recipeSearch']['category'][$_POST['rcp']]);
echo json_encode($_SESSION);
}
The problem is that it doesn't unsets the value. It's still in the session. Any idea? (sorry for grammar mistakes)
Thanks
You can try this:
Set your session:
Yii::app()->session['searchItems']['category'][$keyword] = "Any string";
To unset session:
unset(Yii::app()->session['searchItems']['category'][$remove]);

how to load data without page refresh using ajax

Here is my code for loading data
$(document).ready(function() {
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
});
});
This code retrieves data from database and working fine. But problem here is that if I add new data on the database, this data doesn't show up without page refresh.
So I don’t want to refresh the page to get the data. It should be displayed once new data added to database.
Any suggestions on this issue?
P.S : I also tried .ajax(), didn’t work.
Here is my $.ajax() request
$(document).ready(function() {
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').append(data);
},// success
})// ajax
});
Does the same as $.get()
If your goal is to refresh the page data without refreshing the page, you can put your code in an interval timer and let it auto refresh every x seconds, like below.
setInterval(getAnswer(), 1000);
note: setInterval fires again and again until you clear it, while setTimeout only fires once.
The Ajax-Function get only called once: In the moment the document is ready (fully loaded). You have to use setTimeout to create a timer, which calls the function every minute or whatever you want. Like this:
function getData() {
setTimeout(function(){
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
getData();
});
}, 3000);
}
Here is my final approach
$(document).ready(function() {
setInterval(function(){
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').html(data);
},// success
})// ajax
}, 1000);
});
Without creating and calling function getData(), this code working fine. Also I have changed .append(data) to .html(data).
But still I'm not happy with my code because it is constantly retrieving data from database that makes data server busy.
Whatever I wanted to tasks has to be done and it is done.
Try this you just need to replace this file retrieve_query.php and this id query-div with yours.
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('#query-div').html(this.responseText);
}
};
xmlhttp.open("GET","retrieve_query.php",true);
xmlhttp.send();
},1000);

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

ajaxStart and ajaxStop for a specific event

How can I bind an ajaxStart function for a specific event, using :
$(document).ajaxStart(function () {
alert("started");
});
$(document).ajaxStop(function () {
alert("Ended");
});
Tried this code but it runs whenever autocomplete starts.
Scenario must be like this : whenever I submit a form, that function will be called.
But when I'm just fetching values using autocomplete via ajax, ajaxStart and ajaxStop shouldn't be called.
But when I'm just fetching values using autocomplete via ajax,
ajaxStart and ajaxStop shouldn't be called.
You can create a boolean variable to keep track of whether user is typing or not something like:
<script>
var isTyping = false;
// inside your autocomplete handler set isTyping to true
$(document).ajaxStart(function(){
if (! isTyping) alert("started");
});
$(document).ajaxStop(function(){
if (! isTyping) alert("Ended");
});
</script>
It is better if you uses the main function and it's sub-functions.
$.ajax({
url: 'url_to_page'
beforeSend: function(req){ //Before the request is taking off},
error: function(req){ //If there were a error},
success: function(req){ //When it all was done}
});
$.ajax({
url :'your url',
data: {
//data to send if any
},
type: 'POST',
success:function(msg){
//eqv to ajaxstop if OK
},
beforeSend:function(){
//before ajax starts
},
error:function(){
//failure in ajax
}
});

Categories