One function to load varrious php pages with jQuery and AJAX - php

I have the following code that i need some help with, i am trying achieve the same thing with jQuery. I have found some solutions that come close but as yet i am still searching for the perfect solution.
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
Right now i am triggering the function with:
<input type = "button" value = "TEST" onclick = "getData('subject_selectAJAX.php?course_id=1', 'ajax')">
I would like to achieve the same thing with jQuery. I think the following function although wrong gets close, my problem is that the url changes depending on where the user is within the course. course_select.php is initially loaded into the #ajax div, which then would be replaced with subject_select.php?course_id="whatever" followed by topic_select.php?subject_id="whatever"
function getData() {
//generate the parameter for the php script
$.ajax({
url: "something.php", //i want this to be passed to the function
type: "GET",
data: data,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #ajax div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('slow');
}
});
}
I would love some help with this, i'm currently getting confused pretty sure it is something that would help other Ajax jQuery newbies.

This seems to work although i'm sure it could be much cleaner and i would still like to add some sort of loading graphic for slower connections.
<script type="text/javascript">
function getData( url, id ){
$.ajax({
type: "GET",
url: url,
data: "id=" + id,
cache: false,
success: function(html){
$('#ajax').hide();
//add the content retrieved from ajax and put it in the #content div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('fast');
})
};
</script>

Related

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.

Get next set of data for jquery ajax autoscroll

I'm trying to set up a custom infinite scroll with jQuery and some Ajax. This is what I have so far:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "POST",
url: "posts/view/",
data: "",
success: function(results){
$(".container").after(results);
}
})
}
});
It all works fine and dandy, but what I'm struggling to visualize is how to get the next "set" or, "page" of data. I'm using PHP and in my function I'll have something like getMore($page = 1). But how can I have jQuery keep track of what page it's currently on, and know which page is next? Should I set up some sort of increment function inside of jQuery so that it pulls the URL (e.g. posts/page/1/) and then simply add 1 to the url it passes via Ajax?
I feel like I'm really overthinking this, is there an easier way?
Just use a page counter inside the scroll closure:
(function(){
//inner functions will be aware of this
var currentPage = 0;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "GET",
url: "posts/view/" + currentPage,
data: "",
success: function(results){
$(".container").after(results);
}
})
currentPage++;
}
});
})();​
And change your server script according to the page param you are passing.
If there is nothing more to retrieve, just answer with an empty body.
By the way, POST is not suitable for retreiving data, use GET instead.
You can go for simpler way.
Put one hidden field like this
<input type hidden value="1" id="page" />
now before every ajax send take the pagevalue from that hidden field. And after every ajax success function increment the hidden fierld value like this.
$('#page').val(parseInt($('#page').val())+1)
Your ajax call will look like this
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "POST",
url: "posts/view/"+$('#page').val(),
data: "",
success: function(results){
$('#page').val(parseInt($('#page').val())+1);
$(".container").after(results);
}
})
}
});

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

Workaround possible for cURL and Javascript?

Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>

How can I add the content of a page in a div with Ajax?

I have a list in my site, and when I click each of the list items, I want the div next to them to reload with ajax, so as not to reload the whole page.
Here is my javascript
parameters = "category_id="+categoryId;
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
The ajaxFunction() function is the regular $.ajax() jQuery function, with "POST". In the "changeCategory.php" I call with include another php file.
The problem is that the whole page is reloaded instead of only the div. I want to use this ajax function I have, cause I want to send data to my php file.
Does anyone know what should I do to reload only the div?
Thanks in advance
Try this
$(document).ready(function(){
var parameters = {category_id:categoryId};
$.ajax({
url:'changeCategory.php',
type:'post',
data:parameters,
dataType:'html',
success:function(result){
$("#mydiv").html(result);
},
error:function(){
alert('Error in loading [itemid]...');
}
});
});
Also verify that when in your click event this line is written or not return false; This is required.
Try using load to load the div with the url contents -
$("#mydiv").load("changeCategory.php", {category_id: "category_id_value"} );
You can pass data to the url.
The POST method is used if data is provided as an object; otherwise, GET is assumed.
you could send a query to that PHP so it "understands" that it needs to output only the div, like this:
in your javascript:
//add the query here
parameters = "category_id="+categoryId + "&type=divonly";
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
in your "changeCategory.php":
//add a query check:
$type = "";
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
//then, depending on the type, output only the div:
if($type === "divonly"){
//output the div only;
} else {
//your normal page
}
$(document).ready(function() {
$.ajax({
url: "right.php",
type: "POST",
data: {},
cache: false,
success: function (response) {
$('#right_description').html(response);
}
});
});
The whole page is reloaded that means there may be an error in your javascript code
check it again
or try this one
function name_of_your_function(id)
{
var html = $.ajax({
type: "GET",
url: "ajax_main_sectors.php",
data: "sec="+id,
async: false
}).responseText;
document.getElementById("your div id").innerHTML=html;
}
you can use get method or post method....

Categories