jQuery write element just after the Ajax call - php

Hello I have a jQuery function that will send to a php file some info. The PHP file will do the stuff it has supposed to do and will generate some HTML code. I am fine until here.
The problem is that I have then to take the HTML results generated by this PHP file and write them in the page where the Ajax call has been created, simply by appending it after a DIV or inside a DIV or whatever.
This is the jQuery function I have so far:
$(document).ready(function() {
var idGenre = $("#txtGenre option:selected").val();
var html = $.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: "id=" + idGenre,
async: false
}).responseText;
});
The DIV that must be updated with the HTML results taken from the PHP file GetSubGenreData.php is:
<div id ="divSubGenre"></div>
Now lets say the PHP file will return a select box, something like this:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
etc...
</select>
This select box must be appended just after the DIV <div id ="divSubGenre"></div> or by simply replacing this DIV with the returned Select Box. Nothing impossible for a good jQuery developer. But I am not.
I just need the function to write the HTML results from the PHP file in the right DIV.
Thanks!!

in your success callback
success:function(html){
$("#divSubGenre").append(html);
}
if you want to replace the container div with the ajax response
success:function(html){
$("#divSubGenre").replaceWith(html);
}
if the div to which you are appending the results is not empty then to insert after the div use after
success:function(html){
$("#divSubGenre").after(html);
}
so your final code may look like this
$(document).ready(function() {
var idGenre = $("#txtGenre option:selected").val();
var html = $.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: {id:idGenre},
async: false,
success:function(html){
$("#divSubGenre").append(html);
}
});
});
jquery ajax
jquery replaceWith
jquery append
jquery after
update
$("#txtGenre").change(function(){
//get the update value here
var idGenre = $("#txtGenre option:selected").val();
$.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: {id:idGenre},
async: false,
success:function(html){
$("#divSubGenre").html(html);
}
});
});
jquery change
yet another update
about the comment to show the result on page load, if i have understood the scenario well you can have two divs on the page like
<div id="divSubGenre"></div>
<div id="divonLoad"></div>
on the page load do the ajax call and append the result to #divonLoad and in the success callback of your ajax call that is inside the change event handler do this
success:function(html){
$("#divonLoad").fadeOut("slow").remove(); removes the div that was holding the result on page load
$("#divSubGenre").html(html);
}

Add an HTML dataType and a success method to your AJAX call:
// No need to return the responseText as a variable
updateSelectHtml = function() {
$.ajax({
type: "POST",
url: "GetSubGenreData.php",
data: "id=" + idGenre,
async: false,
// Make sure the return is formatted as html
dataType: "html",
success: function(data) {
// The return HTML data is appended after the div.
$("#divSubGenre").html(data);
}
});
};
// Bind the function to #txtGenre onchange
$("#txtGenre").change(updateSelectHtml);

Related

Send selectbox value to php variables without page reloading

I'm learning AJAX by reading some online tutorials, so please understand I am very new to AJAX and programming in general. I have managed to do the following with 3 selectboxes:
populates selectbox 2 based on selection from selectbox 1
populates selectbox 3 based on selection from selectbox 2
Everything is working perfectly
Here is my code:
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
Here is an Example
What I want to do
I would like to send the value of the 3 selectboxes to 3 php variables without the form reloading.
My Problem
When the user clicks submit:
The form reloads (which I dont want)
The selectbox values does not get send to my php variables
my code to get the values after submit is clicked is as follows:
if(isset($_POST['submit'])){
$a = $_POST['sport'];
$b = $_POST['tournament'];
:
}
However my code is flawed as I mentioned above.
If any one can help me to explain how to send my form data to the 3 php variables without the form reloading it will be greatly appreciated
If you don't want to submit your form when you click the button, you need to set that input as button and not submit. You can, also, attach the submit event handler to the form and prevent it to submit:
$("form").on("submit", function(e){
e.preventDefault(); //This is one option
return false; //This is another option (and return true if you want to submit it).
});
So, being said this, you could probably do something like:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'yoururl',
data: formData,
type: 'post', //Based on what you have in your backend side
success: function(data) {
//Whatever you want to do once the server returns a success response
}
});
});
In your backend:
if (isset($_POST["sport"])) {
//Do something with sport
}
if (isset($_POST["tournament"])) {
//Do something with torunament
}
echo "Successfull response!"; //You have to "write" something in your response and that is what the frontend is going to receive.
Hope this helps!
Try using the javascript function preventDefault().
See this SO question.
Use a <button>Submit</button> element instead of <input type="submit"/> since the submit automatically submits the form.
Edit: And you would have to use on.('click') instead of looking for submit event in your jQuery.

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');

Refresh div content on form submit (ajax)

On my page I have a form that inserts a new record in to the database. On the same page there is a DIV that contains the current resultset.
What I am trying to do is refresh just that DIV (not the whole page) when the form is submitted. The DIV will then contain the latest records (including the one just added).
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
});
return false;
});
<div id="current-rows">
<?php while($variant=mysql_fetch_array($variants)) { ?>
<div class="row">
// resultset
</div>
<?php } ?>
</div>
I set $variants from within my controller (beforehand):
$variants=Catalog::getProductVariants($product['id']);
Ideally I don't want to be returning a whole load of HTML to be injected in to that DIV.
Set the new content in the success handler of ajax request. Try this
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(newContent){
$('#current-rows').html(newContent);
}
});
return false;
});
I think it is easier to use .load method, which injects the response from the server to the given div, something like:
$('#idOfYourDiv').load('/your/url', {params: params});
alternatively you can still use $.ajax, like:
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(data) {
$('#yourDiv').html(data); // html will insert response, response is stored in "data" variable
}
});
return false;
});
on php site just echo what you want to be displayed, for example
foreach($results as $result){
echo $result."<br />";
}
hope that helps
I have put the contents of the "current-rows" div into it's own seperate view file:
<div id="current-rows">
<?php include("_current-rows.php"); ?>
</div>
And in my controller 'addvariants' action I just do this:
$variants=Catalog::getProductVariants($_POST['product_id']);
include('application/view/admin/catalog/_current-rows.php');
That is the response that is passed back to my jQuery success function.

how to load sql/session content to a div from loaded div

I have been researching for the last two days, and have found nothing.
structure:
index.php:
<head>
<script type="text/javascript" src="JS/jquery-1.6.2.js"></script>
<script type="text/javascript" src="function.js"></script>
</head>
<body>
<div>
<div>Show</div> *-->if I click this link data loads into DIV below by function.js without reloading*
<div id="producten"></div> *-->testpage.php loads here perfect,
the code of testpage.php makes by while loop other links.
Here I want to click on a link to load next data in div id=information
without reloading the index.php so the data in the first DIV stay visible
and I dont know how to do that*
<div id="information"></div> *-->testpage2.php have to load data from sql in this DIV*
</div>
</body>
function.js:
$(document).ready(function() {
$(".testcat").click(function() {
var testid = $(this).attr("id");
var datastring = 'id='+ testid ;
$.ajax({
type: "POST",
url: "testpage.php",
data: datastring,
cache: false,
success: function(res) {
$('#producten').html("<div class='loading'><img src='IMG/loading.gif' /></div>")
.hide()
.fadeIn(2000, function() {
$('#producten').html(res);
})
}
});
return false;
});
});
testpage.php and testpage2.php are PDO code for sql data.
You'll want to attach your click handlers with on so that dynamically added content still has the same ajax handlers available to them:
Add whatever information is needed to differentiate one click from the next, ie
<a href='...' data-resultdiv='production'
Then, cleaning up your handler a bit: I assume you want the ajax request to go to the href of the link, and that you want to show "loading" immediately (instead of waiting for the request to complete).
Finally, to cancel the anchor's default behavior of browsing to the page referenced by the href, you can return false;
$(document).on("click", "a", function() {
var href = $(this).attr("href");
var successDiv = $(this).data("resultdiv");
$('#' + successDiv).html("<div class='loading'><img src='IMG/loading.gif' /></div>");
$.ajax({
type: "POST",
url: href,
data: datastring,
cache: false,
success: function(res) {
$('#' + successDiv).hide().html(res).fadeIn(2000);
}
}
return false;
});
And of course if you only want this to run for certain anchors, you can put a selector on your call to on
$(document).on("click", "a.someClass", function() {

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