I'm trying to run a php file with AJAX from my "main.php".
The problem is that it doesnt let my stay on the main.php and moves me to "tallennus.php", when I want to stay at "main.php". The tallennus.php should be done on the background.
"tallennus.php" does it's work perfectly (saves data to database). But I want to stay on mainsite while it does it.
Im trying to use AJAX to run "tallennus.php" on the background.
Why does the site change from main.php to tallennus.php?
<button onclick="testi()">testi</button><br>
<script>
function testi()
{
alert("function started");
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
}
xmlhttp.open("get", "tallennus.php",true);
xmlhttp.send();
}
</script>
The default type of <button> is type="submit", so it submits the form. Change it to type="button".
<button type="button" onclick="testi()">testi</button><br>
As per the following reference:
https://www.w3.org/TR/html-markup/button.html
"A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"."
I fixed my problem by doing this:
<script>
function tallenna()
{
var tunnus=document.getElementById('tunnus').value;
var nimi=document.getElementById('nimi').value;
var deadline=document.getElementById('deadline').value;
var vaihe=document.getElementById('vaihe').value;
var dataString=
'tunnus='+ tunnus +
'&nimi='+ nimi+
'&deadline='+ deadline+
'&vaihe='+ vaihe;
$.ajax({
type:"post",
url: "tallennus.php",
data: dataString,
cache:false,
success:function(html){
$('#msg').html(html);
}
});
document.getElementById("frm").reset();// for clearing form
return false;
}
</script>
<br><input type="submit" value="TALLENNA" onclick="return tallenna()">
Related
I am doing a blog with PHP, AJAX, MySQL, etc. As usual, each post has its ID and inside the posts you can see the comments.
What I am trying to do is refresh the comment's div by calling the comments.php document with AJAX and putting it in the div with $('#comments').html(data);.
Doing this every 5 seconds for maintaining the comments like in real time, but the problem is that when the div does the first refreshing, the div loses the ID of the post and say that is undefined.
How can I refresh any div without losing the ID of the post?
If I call the comments.php file with the typical include(file.php) inside of the post file, I have no problem, but using this way I just can't refresh the content.
Here's the code:
post.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'support/comments.php',
success: function(data) {
$('#comments').html(data);
}
});
});
</script>
div where the result is going to be showed:
<div id="comments">
</div>
Script for refreshing the div:
<script language="Javascript" type="text/javascript">
function refreshDivs(divid, secs, url) {
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("your browser doesn't support ajax.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function () {
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
window.onload = function startrefresh () {
//update content on real time
refreshDivs('comments',10,'support/comments.php');
}
</script>
You can pass the post id in the URL, like so:
url: 'support/comments.php?id=<?= $post_id ?>'
Then wrap the call with a setTimeout, like so:
window.setInterval(function(){
$.ajax({
url: 'support/comments.php?id=<?= $post_id ?>',
success: function(data) {
$('#comments').html(data);
}
});
}, 5000);
And discard refreshDiv.
This is assuming that comments.php retrieves the comments, and some other code posts them.
ok guys I solved it... I am gonna leave the code here in case of somebody could has the same problem... what I did was build a hidden input and put this input to use its value like the id of the post, then I sent the value of this input to the script with #('div').val and finally I sent that value to the comments.php file, once there.... I used the value in the query sentence for doing the comparative and finally can get the comments in the right post
Here's the code
<script>
$(document).ready(function() {
window.setInterval(function(){
//Comentarios
var id = $("#idcomment").val();
$.get("support/comments.php", { idpost: id }, function(LoadPage){
$("#comment").html(LoadPage);
});
}, 5000);
});
</script>
I've successfully wrote a working Ajax code, but the problem is that i can add an input field only once. I have a submit input, that calls Ajax script, everything works, the input text field appears, but after this if i want to add another text field by clicking on the submit input, it does not work. You only load once (YOLO). How do i write more awesome code that lets me add as many text fields as needed? Thanks for every reply. Here is my code:
index.php:
<head>
<script>
function ajaxobj(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('asd').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajaxAddInput.php',true);
xmlhttp.send();
}
</script></script>
</head>
<body>
<input type="submit" onclick="ajaxobj();">
<div id="asd"></div>
</body>
the php file:
<?php
echo '<input type=\"text\">';
?>
Simply use a standardized library, just like jQuery. With this in mind, you might use the following code:
$("#asd").on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
Alternatively, you can use the library with classes as well:
$('input[type=text]').on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
I have a problem with AJAX and JQUERY.
I have a form, which contents a tag. After select an option, I use AJAX to generate a formular, fill it with some data from a database and show it.
I would like to use the jQuery UI MultiSelect Widget
The problem is that I need to initialize the select with jQuery but it doesn't work when I call this function in the file that generates the new content: (it works well if I don't use AJAX).
<script type="text/javascript">
$(function(){
$("#ExampleSelect").multiselect({
selectedList: 4
});
});
</script>
The structure is the following:
PHP file with the main form which contains a normal and a which will contain the elements that are generated after the AJAX call. (onChange event in the <select>).
Ajax file
function LoadDiv()
{
var xmlhttp;
var serie_id = document.getElementById('serie_id').value;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divForm").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","divDataManagement.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("serie_id="+serie_id);
}
$.ajax({
success: function(){
$("#ExampleSelect").multiselect("destroy").multiselect({
selectedList: 4
});
}
});
PHP file that contains the jQuery UI MultiSelect which wil be displayed in the main php form (inside the <div> tag).
<select id = "ExampleSelect" multiple>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
Thanks for your help.
Initialize it in AJAX success method.
$.ajax({
...
success: function(){
$("#ExampleSelect").multiselect({
selectedList: 4
});
}
...
If you make changes on a selected instance of multiselect, destroy it and reinitialize after changing.
$.ajax({
...
success: function(){
$("#ExampleSelect").multiselect("destroy").multiselect({
selectedList: 4
});
}
...
In case you use XMLHttpRequest instead of jQuery ajax, you should init multiselect in onreadystatechange method.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divForm").innerHTML=xmlhttp.responseText;
$("#ExampleSelect").multiselect({
selectedList: 4
});
}
}
I have a form in which all the contacts are listed with fields like first name last name etc. Every row has view edit delete anchor tags on which I am calling a popup div. This popup div contains the php include(external file). I want to access the selected rows unique database primary key in that external file.
The link of the code is
https://www.dropbox.com/s/88qpmkwmaepa5s4/New%20Text%20Document%20%283%29.txt
Any help is appreciated.
Thank you
As a simple example to call Ajax by javascript and send the clicked row id to the php file, check this
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//returned response from ajax to the php page will be in xmlhttp.responseText
alert(xmlhttp.responseText); // Do whatever you need with the respones
}
}
var selected_row = document.getElementById('selected_row').innerText; // we assume this is the value of the selected row
xmlhttp.open("GET","path_to_your_phpfile&row_id=" + encodeURIComponent(selected_row), true);
xmlhttp.send();
}
Now the selected row id is passed by GET and in your php file you can get by $row_id = $_GET['row_id'];
If you are using jQuery, you go for a quick kill with AJAX.
Javascript:
<script>
function show_div(id) {
function show_lightbox(){
// your code
}
$.ajax({
type: "POST",
url: "get_detail.php",
data: "id=" + id,
dataType: "html",
success: function(html){
$("#show_detail").html(html);
}
});
}
</script>
Html:
<div id="lightbox">
<div id="show_detail"></div>
</div>
In your anchors:
<a onClick="show_div(uniqe_primarykey)">Click to fetch details</a>
In get_details.php
<?php
$id = $_POST[id];
//your queries
?>
<html>
Data from queries
</html>
The below code is to create a campaign. Before creation, I have to validate the form. I have to validate the campaign name which is already existed in database or not. I don't know whether I can use PHP code inside javascript (like below).Anyway it's not working. How can I change my code? How can I validate values with database values?
$this->campaign is an array which contain all campaign details from database.
<script type="text/JavaScript">
function validate()
{
var name = document.getElementById('name').value;
var shape = document.getElementById('shape').value;
<?
foreach($this->campaign as $c)
{
$old_cname=$c['name'];
?>
if(name==<?=$old_cname;?>)
{
alert("same name exists in database. Try again!");
}
<?
}
?>
if(!name)
{
alert("Please enter a name!");
return false;
}
if(!shape)
{
alert("Please select shape!");
return false;
}
return true;
}
</script>
<form action="create.php" method="post" onsubmit="return(validate());">
Name:
<input type="text" name="name" id="name"/>
Shape:
<select name="shape" id="shape">
<option value="long">Long</option>
<option value="tall">Tall</option>
</select>
<input type="submit" value="Create" name="submit"/>
</form>
Thanks!
You can't mix php and javascript like that.. php is a server-side language, while javascript is client-side; php renders the page before the user sees it, while javascript modifies the page without refreshing. Any php values in your js will get rendered and output before the js even executes.
In order to do what you need, you need to use ajax, which is asynchronous javascript and xml, a method of client-server communication that allows for what you want to happen.
To do this, I would suggest jQuery, a javascript library which makes such requests very simple. As an example of how you would make such a request in jquery....
The jQuery.ajax() method:
$.ajax({
url: "validate.php",
type: "POST",
data: "username=" + username,
sucesss: function(data) {
if (data == 1)
$("#ajax_div").html("Username is taken, choose another!");
}
else {
$("#ajax_div").html("Username is free :)");
}
}
});
That would be how to do it in ajax, while your php file would either return a 1 or a 0 depending on the result of an sql query comparing usernames in the database.
To do this without jquery, it would be something like this:
function checkUsername() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.responseText == 1) {
document.getElementById('ajax_div').innerHTML = "Username is taken, please choose another!";
}
else {
document.getElementById('ajax_div').innerHTML = "Username is free :)";
}
}
}
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username=" + username);
}
}
You should use jquery to validate using a php script. The best way to do this is to disable the submit button until all fields are verified. This requires that you to listen to keystrokes then make a jquery call to validate the input field. A simple example below
script.js
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
//on keyup, start the countdown
$('#myInput').keyup(function(){
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#myInput').keydown(function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
$.ajax({
type: "POST",
url: 'ajax/validate.php',
data: 'cname='+$('#name').val(),
success: function(data) {
if(data == "original"))
//enable the submit button
else
//Update your div that contains the results
}
});
}
ajax/validate.php
<?PHP
//Run your validations here
?>