Ajax Response show and disappear - javascript

It was working fine.
What changes I made, I am unable to trace it out, which has broken it.
But now my Ajax response shows momentarily on the screen and disappear.
Using firebug I can see that I am getting the response properly.
I am just been unable to locate, what has gone wrong.
This is the code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.loader').hide();
$("#domain-check").submit(function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
$('.loader').show();
/* Send the data using post and put the results in a div */
$.ajax({
url: "?r=site/check",
type: "post",
data: values,
success: function (response) {
$('.loader').hide();
$("#result").html(response);
}
});
});
});
</script>
and HTML DiV below the form is like this
<div class="loader">
<span></span>
<span></span>
<span></span>
</div>
<div id="result"></div>
Can it be related to some cache issue?

Related

Onload Page load extern page

i use this AJAX script to load an extern page (mpt_planningen_overzicht.php) into a div op the mainpage (mainpage.php) when people select or unselect a checkbox.
But i also want to load the data from the extern page in the div when mainpage.php is opened.
How can i do this?
Script:
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('click', function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
});
});
</script>
I thought something like this:
function onLoadSubmit() {
document.nameofForm.submit();
}
But the Ajax script that checks if a selectbox is checked/unchecked is already on mainpage.php, so when i add the script above, it will continue reloading.
If I understood the question correctly, you can try something like this:
<script type="text/javascript">
//separationg the function that loads the page in order to use it multiple times
var loadSepratePage = function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
}
$(document).ready(function(){
$('input[type="checkbox"]').on('click', loadSepratePage); // without paranthesis () to pass the function as a parameter
loadSepratePage() // with paranthesis () to actually call the function
});
</script>
If this is not what you mean feel free to leave comment

Unable to get data from Wikipedia API

I am working on a 'Wikipedia Viewer' project, where you enter a search term and see a list of Wikipedia search results, but it is far from complete.
Until now I have just written the code to display the first search term. But it doesn't work.
My HTML:
<div class="container-fluid">
<div class="searchAndButtons">
<input type="text" id="search">
<button class="btn" id="searchBut">Search</button>
<form action="https://en.wikipedia.org/wiki/Special:Random"><button class="btn">Random Wiki Article</button>
</form>
</div>
<div class="searchResults">
</div>
</div>
My CSS:
.container-fluid{
padding:5%;
}
.searchAndButtons{
text-align:center;
}
My Javascript:
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("#search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Where am I going wrong? When I run the code in Codepen and check the console, it shows an error "TypeError: document.getElementById(...) is null".
My project on codepen - link
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Update your JS code with this. id gets value by 'search' not '#search'
UPDATE: To add headers you can do the following
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1', //your request URL
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo'); //your header key and value
}
});
});

HTML Links do not work after AJAX POST

Background: I am working on a small web application. AJAX will successfully POST the data to the action(create.php) and create.php will execute the necessary mysql query. Once AJAX is done, I append a message to the div id="container"></div> informing the user of a successful execution then clear the content "container" for future use; however, here in lies the problem.
Problem: After AJAX executes, I can not click on any HTML links already loaded onto the page(page.php). I have to refresh the page in order to click on any links and follow them to their destination. What is causing this to happen and how can I fix it?
AJAX does not need to return a result. It only needs to execute the specified jQuery code once the request is done. On a hunch, I altered create.php to echo the $_POST array and have AJAX return that as a result. Once AJAX loads the result into the "container" I still can not click on any links loaded on page.php
Answer: The DOM was not being reloaded after AJAX calls causing bootstrap dropdown menus to not function properly. The bootstrap dropdown class had to be manually reinitialized after each call. This has already been answered in detail here
create.php
<?php
if($_POST){
//run mysql query
}else{
//do nothing
}
?>
form.php
<form id="new-items">
<input type="text" name="item" />
<input type="button" onclick="create_item()" name="Submit" value="Submit" />
</form>
page.php
<html>
<head>
<script>
$(document).ready(function(){
$("#add_items").click(function(){
event.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow");
}, 5000);
setTimeout(function(){
$("#content").empty();
}, 8000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>
Link1
Link2
Add New Items
</nav>
<div id="content"></div>
</body>
</html>
After you fadeOut the #content element, it remains hidden. The next time you call your AJAX function, it's loading create.php into an invisible element.
Try:
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
Other issues: <div class="content"> should be <div id="content">; you didn't include jquery.js at the top of your script; you didn't pass the event object e to your click handler.
page.php should now look like:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#add_items").click(function(e){
e.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>Add New Items</nav>
<div id="content"></div>
</body>
</html>
The anchor links in the <nav> will natually 'refresh' the page with the new content.
If you want to load the content via an ajax request then you should try the following:
Add a common class to the links
<nav>
Link1
Link2
Add New Items
</nav>
Then attach a click event to each link which intercepts the default page refresh with e.preventDefault(). The you can perform the ajax request using the href attribute of that link.
$(function(){
$(".anchor").on('click', function(e){
e.preventDefault();
var $this=$(this);
$("#content").load($this.attr('href'));
});
});
The DOM was not being reloaded after AJAX call. Boostrap dropdown module has to be manually reinitialized after each call. Detailed answered here: answer

PHP and Ajax posting

I'm using jQuery form plugin to send ajax requests. Which you can find on below url
http://malsup.com/jquery/form/
This is my jQuery code
$(document).ready(function()
{
$('#SubmitForm').on('submit', function(e)
{
e.preventDefault();
$('#submitButton').attr('disabled', '');
$(this).ajaxSubmit({
target: '#output',
success: afterSuccess //call function after success
});
});
});
function afterSuccess()
{
$('#submitButton').removeAttr('disabled'); //enable submit button
}
This code is displaying out put on the div id output and each time i submitted code will remove the old out put and display the new one. What i want to do is, keep the old out and display the new out put on top of the old output. Can someone tell me how to do this.
What you could do, is alter your afterSuccess method a little bit. What I did was:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
The whole fiddle is available here
The whole code of javascript:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
$(document).ready(function()
{
$('#submitButton').click(function(e)
{
$('#submitButton').prop('disabled', true);
$('#SubmitForm').ajaxSubmit({
data: {
html: "<p>Text echoed back to request</p>",
delay: 1
},
success: afterSuccess,
url: '/echo/html/'
});
});
});
and of course assuming following html structure
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<body>
<form id="SubmitForm" method="POST">
<input type="button" id="submitButton" value="submit"/>
</form>
<div id="output">
test
</div>
</body>

when loading a page content through ajax post and codeigniter load functions, some jquery functions are in the head section cannot be called

I know My question Title is not perfectly describe my question extremely sorry about that. I don't know how to tell this as a summery. anyway this is my question.
I am making a admin panel to change some of the content in my web page. this scenario is for change slideshow images.
ok then after someone logged into my page I am loading three pages. like this.
$this->load->view('admin/header');
$this->load->view('admin/menu');
$this->load->view('admin/table_and_editor_holder');
all the page contents I have mentioned below. so basic path is like this. once someone logged he can click the button [slide manage] to load the images and details of already inserted slides. these are getting from a database. so once he clicked the menu button. this jquery function is executing.
$('.menu-item > a').on('click', function() {...})
this function simply getting a html page. filled with previous slide details. this is the controller function handle the menu request.
function slider_edit_delete() {
$sdata['slide_imgs'] = $this->admin_basic_curd->get_all_items('sider_images');
$slide_manager = $this->load->view('admin/slider_manager', $sdata, TRUE);
echo $slide_manager;
}
so previous jquery function is then appending this page content to a div like this.
$('#table_container').html(data);
so inside this page content I have a buttons call edit for each slide already inserted. so by clicking on of this button I can edit that slide image or some test content of it. that button is like this.
<a class="onclick_post_by_a" href="<?php echo base_url() . 'adm_edit_this_slide/' . $sl->id; ?>">
<button class="btn btn-info"> Edit </button>
</a>
so by clicking this button must execute this function in the header section and this function must add a html form (in a separate page) to the #editor-form-container div as previously
$('.onclick_post_by_a').on('click', function() {...})
but the problem is once I click the edit button it couldn't find this function. so it is opening the content as a separate page
How can I make this to work? Thank you
the header page contains all the css and js file links. and some jquery functions. like this.
<script>
$(document).ready(function() {
$('.menu-item > a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#table_container').html(data);
});
return false;
});
$('#editor-form-container').css({
display: "none"
});
function posting_url(url, pdata) {
return $.ajax({
url: url,
data: pdata
});
}
$('.onclick_post_by_a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#editor-form-container').css({
display: "block"
});
$('#editor-form-container').html(data);
});
return false;
});
$('.post_with_image').on('submit', (function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
}));
});
</script>
</head>
then I have load menu page. it is like this.
<div class="admin-navi">
<div class="menu-item">
Home
</div>
<div class="menu-item">
Side Manage
</div>
</div>
<div class="clearfix"></div>
table_and_editor_holder.php page. it is like this.
<div class="col-lg-12">
<div class="col-lg-2"></div>
<div id="table_container" class="col-lg-8">
</div>
</div>
<div id="editor-form-container" class="col-lg-6">
</div>
Dynamically created element does not respond to direct call to events like below -
$('.onclick_post_by_a').on('click', function() {...})
So you have to write like this
$(document).on('click', '.onclick_post_by_a', function() {...})
Just try it out.

Categories