document.getElementById causes jquery document ready to be executed twice - javascript

This code is supposed to run over to load.php and get some data in xml format, parse it, and load it in a div and display it. It works great, except the data from load.php is displayed twice. Is there another way to do this that won't cause the data to be shown twice? I've seen a number of posts related to the document ready function causing this problem, but can't seem to figure out how to apply any solutions to this case. I am putting this in the head tags on my page. I really want to keep this format, because eventually I'll POST some data to the load.php page.
SCRIPT
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'load.php',
success: loadReturn
});
function loadReturn(data) {
var xml = $.parseXML(data);
$xml = $(xml);
$errorcode = $xml.find('errorcode');
$data = $xml.find('data');
document.getElementById("defaultcode").innerHTML = $data.text();
$("#defaultcode").fadeIn(300);
}
});
</script>
HTML
<div id="defaultcode" style><h3>a title</h3><p>blah blah</p><h3>a title</h3><p>blah blah</p></div>
Thank you in advance for your time.

First of all I try to fixed your code to the right ways. but I dont think code is wrong. it should be you have send two data tag from load.php. please check your returned data.
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'load.php',
success: loadReturn
});
function loadReturn(data) {
// check your data
console.log(data);
// jQuery will parse for you automatically
var $xml = $(data);
var $errorcode = $xml.find('errorcode');
var $data = $xml.find('data');
// set html before fadeIn
$("#defaultcode").html($data.text()).fadeIn(300);
}
});

Related

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

How can I refresh a PHP file with itself using Ajax?

Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..

Reload an AJAX loaded page after update

I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.

Javascript get current page html (after editing)

I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.
I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.
I can get the copy of the file using this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
Which works fine and gets me the html I expected and see when viewing the page in notepad.
The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:
origPage.getElementById('editor').innerHTML = e.html;
But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:
alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);
But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?
EDIT:
Complete page html below:
<!DOCTYPE html>
<html>
<body>
<div id="editor">
<h1>This is editable.</h1>
<p>Click me to start editing.</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="snapeditor.js"></script>
<script type="text/javascript">
var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
var isSuccess = true;
//var origPage = e.html;
var origPage;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
// Actually perform the save and update isSuccess.
// Javascript:
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
//origPage shows expected html as this point
//alert($(origPage).getElementById('editor').innerHTML);
//alert($(origPage).html().getElementById('editor').innerHTML);
$(origPage).getElementById('editor').innerHTML = e.html;//fails here
alert(origPage);
//alert(newHtml.getElementById('editor').innerHTML);
$.ajax({
data: {html: origPage, docName: 'example1.html'},
url: 'savePage.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
isSuccess = true;
}
});
return isSuccess || "Error";
},
onUnsavedChanges: function (e) {
if(confirm("Save changes?")) {
if(e.api.execAction("save")){
//location.reload();
}
} else {
e.api.execAction("discard");
}
}});
</script>
</body>
</html>
It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited
Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?
If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.
Code to send the data:
javascript/jQuery:
alert(e.html); //you should see the user-edited HTML
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'userStuff=' + e.html, //var_name = var_contents
success: function(d){
window.location.href = ''; //redisplay this page
}
});
another_php_file.php:
<?php
$user_edits = $_POST['userStuff']; //note exact same name as data statement above
mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());
echo 'All donarino';
The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.
The data is received as $user_edits, and then inserted into your MySQL db
Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?
This is where you haven't provided enough information, and why I wanted to see all your code.
ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?
You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:
https://phpacademy.org/videos/php-and-mysql-with-mysqli
https://phpacademy.org/videos/oop-loginregister-system
If all you need to do is insert the contents of e.html to replace the #editor div, then try this:
$('#editor').html(e.html);
HOWEVER, you need an event to trigger that code. Are you able to do this?
alert(e.html);
If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.

Put json result from php script into divs jQuery

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

Categories

Resources