div replacing everything after it, AJAX, PHP, JAVASCRIPT - javascript

Using ajax, I'm trying to display what is being selected on a div, and it's working, but everything after the div gets replaced by the div's output. I don't know why it's happening or how to fix it. If you know, please let me know.
test1.php
<?php
include('ajax.php');
echo "<select name = 'select' onchange = 'ajax(\"test2.php\",\"select\",\"select\",\"output\")'>";
echo "<option value = '1'> one </option>";
echo "<option value = '2'> two </option>";
echo "<option value = '3'> three </option>";
echo "</select>";
echo "<div id = 'output'>";
echo "text";
?>
test2.php
<?php
$select = $_POST['select'];
echo $select;
?>
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>

I testing your code in my pc and it worked. But after change this echo "<div id = 'output'>"; into this echo "<div id = 'output'></div>";, the output only show inside div block and everything after the div gets not replaced.
If you want something similar to onload, just use trigger function to trigger the onchange event after page load like so :
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
$(function(){
$('select[name="select"]').trigger('change');
});

You are missing the closing div tag.

Related

jquery ajax return values into html form

I need help with returning values from jQuery/AJAX to html form inside index.php
index.php :
<script type="text/javascript">
$(document).ready(function () {
$('#display').ready(function () {
var pageid = '<?php echo $_GET[\'ID\'] ;?>';
var powiat = '<?php echo $row[\'powiat\'] ;?>'
$.ajax({ //create an ajax request to display.php
type: 'GET',
url: 'display.php?ID=' + pageid + '&powiat=' + powiat,
dataType: 'html', //expect html to be returned
success: function (response) {
$('#responsecontainer').html(response);
//alert(response);
}
});
});
});
(...)
echo "<form action=\"save.php\" method=\"GET\">";
echo "<tr><td>IP</td><td><div id=\"responsecontainer\"></td></tr>";
echo "<input type=\"submit\" value=\"Save\">" ;
echo "</table></form>
display.php file contains:
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
echo "<option value=\"".$disp_row_1['ip']."\">".$disp_row_1['ip']</option>";
}
In return I have filed html as expected but when I try submit form filed by jquery/ajax I have error
Notice: Undefined index: ip.
How can I handle with that?
Thanks.
Syntax error in your code when you are printing the option.
Updated code is as below.
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
?>
<option value="<?php echo $disp_row_1['ip'];?>" ><?php echo $disp_row_1['ip'];?></option>
<?php }

how to send data from a php page to ajax page

i have this code, now i want to send this $_SESSION['roll_id'] variable to another page menu.php where ajax function is written. how i send this variable to another ajax page for set data.
this is login.php page.
if($row["Login_Id"]==$username and $row["Login_Pass"]==$password)
{
echo "<h2 align='center'>" ."Login Sucessfull welcome" ." " .$row["Login_Id"]
."</h2>" ;
$_SESSION['roll_id']=$row['Roll_Id'];
//echo "ID" .$_SESSION['roll_id']; (give roll id)
header("Location: menu.php");
}
else
{
echo "<h2 align='center'>" ."Login Failed" ."</h2>";
}
this is menu.php page where whole functionality is written. i want to send rollid from this page to submenu.php where i can use this roll id in sql query.
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = '<?php json_encode($session); ?>';
$.ajax
({
type:'post',
url:'submenu.php',
data:{"roll_id":rollid},
success:function(response)
{
//console.log(response);
var menuArray= JSON.parse(response);
var html ="";
$.each( menuArray, function( key, value )
{
html += "<li><a href=''>" + value.Menu_Name + "</a>";
if(value.subMenu.length > 0)
{
console.log(JSON.stringify(value.subMenu));
html += "<ul>";
$.each( value.subMenu, function( key, subValue )
{
html += "<li><a href=''>" + subValue.text + "</a></li>";
});
html += "</ul>";
}
html += "</li>";
});
console.log(html);
if(response!="")
{
$("#main_menu").html(html);
}
}
});
});
this is submenu.php page
<?php
session_start();
include('config.php');
$roll_id = $_POST['roll_id'];
$q="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,b.Menu_Level,
b.MainMenu_ID, b.Menu_Order, b.Account_id,b.is_deleted from roll_menu AS a
join menu AS b on a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id;
$menu = mysqli_query($conn, $q);
$mainMenu = array();
foreach($menu as $x=>$value)
{
if($value['MainMenu_ID']==0)
$mainMenu[]=$value;
}
$menuData= array();
foreach($mainMenu as $y=>$value1)
{
$subMenu= array();
$m=$mainMenu[$y]['Menu_Id'];
$q1="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,
b.Menu_Level, b.MainMenu_ID, b.Menu_Order, b.Account_id,
b.is_deleted from roll_menu AS a join menu AS b on
a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id."and b.MainMenu_ID=$m";
$menu1 = mysqli_query($conn, $q1);
while($row=mysqli_fetch_array($menu1))
{
if($row["MainMenu_ID"]==$m)
{
$subMenu[]=array("text"=>$row["Menu_Name"]);
}
}
$value1["subMenu"] = $subMenu;
$menuData[] = $value1;
}
$menuDataJSON = json_encode($menuData);
echo $menuDataJSON;
now i attach the full code of submenu.php page.
Try like this may its helpful for you
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = "<?php echo $session; ?>"; //change here
alert(rollid)
$.ajax
({
type:'post',
url:'submenu.php',
data:{roll_id:rollid}, // change alse here
/*success: function (data) {
alert(data);
}*/
You echoed the <h2 ... on successful login and then used the header function to redirect. This will cause a warning `Warning: Cannot modify header information - headers already sent by” and redirection might not work.
As for AJAX, you need to echo the roll_id like this:
var rollid = '<?php echo json_encode($session); ?>';
I woudl also like to point out that since rollid is a single value, you dont really need to json_encode it.
1st : You missed to echo the variable .
2nd : if it's not a array no need json_encode
3rd : Before header function you will not echo any browser out put like html or echoing something will cause Warning: Cannot modify header information - headers already sent so take care about that .
4th : Try to put exit(); function after header function
header(....);
exit();
Js :
var rollid = '<?php echo $session; ?>';
just start_session() at top of page and try like this
var rollid = "<?php echo $_SESSION['roll_id']; ?>";

Dynamically created select list makes mutilple calls to javascript function

I have created dynamically multiple select list. On click of channel name it should get its type. The problem is once click on select list its repetitively calls java script function causing ajax to load multiple times.
HTML CODE:
<td>
<SELECT name="channel_name[]" onclick ="get_type(this)"; required class='channelname'>
<option value="">Select...</option>
<?php foreach($channel_list as $row) {
$channelid = $row['channelid'];
$channelname = $row['channelname'];
if($U_channelid==$channelid)
{
$s = "selected = selected";
}
else
{
$s = "";
}
echo "<option value='$channelid' $s>".$channelname."</option>";
?>
<!-- <OPTION value='<?php echo $channelid ?>' $s ><?php echo $channelname?></OPTION> -->
<?php } ?>
</SELECT>
</td>
Javascipt code:
function get_type()
{
$(".channelname").live("change", function() {
var channel_id = $(this).find("option:selected").attr("value");
var _this = $(this); //Save current object
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
}
remove onclick ="get_type(this)" from select tag // because you already using $(".channelname").live("change", function() { in javascript
put this
<SELECT name="channel_name[]" required class='channelname'>
and javascript
$(".channelname").change(function() {
var channel_id = $('.channelname').find("option:selected").attr("value");
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});

Ajax delete data from database function not working

I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>&nbsp&nbsp<input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span> &nbsp&nbsp<input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}

Why isn't my AJAX code working?

I believe this should be pretty trivial, but I cannot figure it out at all. I am doing a small test with sending an AJAX request, and echoing a variable extracted from a drop-down menu.
However, it doesn't seem to be executing whatsoever. I was wondering if someone could help me point out what's wrong?
Here are the relevant snippets from index.php:
<html>
<?php
//create a drop down of available accounts
echo 'Available Accounts: ';
echo '<select name=dropAccounts class=dropAccounts>';
//if there is at least one account available
if (count($accsAvailable) > 0) {
echo '<option value=0>---Select an account---</option>'; //default option
foreach ($accsAvailable as $account) {
//populate from API
echo '<option value=' . $account->getId() . '>' . $account->getName() . '</option>';
}
} else {
echo '<option value=0>---No accounts---</option>'; //else if no accounts exist
}
echo '</select>';
//for available webproperties
echo '<br> Available Webproperties: ';
echo '<select name=dropProperties class=dropProperties>';
echo '<option selected=selected>---Select a webproperty---</option>';
echo '</select>';
?>
</html>
The important thing to take away from the snippet is that the first drop-down menu is called 'dropAccounts'.
here is my JS script for handling an onchange event on 'dropAccounts':
<script type="text/javascript">
$(document).ready(function()
{
$(".dropAccounts").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "propertyID.php",
data: dataString,
cache: false,
success: function(html)
{
$(".dropProperties").html(html);
}
});
});
});
</script>
I eventually intend to populate the second drop-down menu 'dropProperties' using the value grabbed from 'dropAccounts' but it's not even echoing in my PHP script.
propertyID.php:
<?php
if($_POST['id'])
{
$accountID = $_POST['id'];
echo $accountID;
}
?>
I was following the tutorial found here: http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
According to what I see the problem is the following:
var dataString = 'id='+ id;
data: dataString
You need to send the data in the following way;
data : {
'id' : id
}
And it should send you the data in the correct format.
EDIT: I'm adding this to clarify how your code would look.
<script type="text/javascript">
$(document).ready(function()
{
$(".dropAccounts").change(function()
{
var id=$(this).val();
$.ajax
({
type: "POST",
url: "propertyID.php",
data: {
'id' : id
},
cache: false,
success: function(html)
{
$(".dropProperties").html(html);
}
});
});
});
</script>
your generated html is not valid. every class and name should be inside quotes.
Change your index.php
like this:
<html>
<?php
//create a drop down of available accounts
echo 'Available Accounts: ';
echo '<select name="dropAccounts" class="dropAccounts">';
//if there is at least one account available
if (count($accsAvailable) > 0) {
echo '<option value="0">---Select an account---</option>'; //default option
foreach ($accsAvailable as $account) {
//populate from API
echo '<option value="' . $account->getId() . '">' . $account->getName() . '</option>';
}
} else {
echo '<option value="0">---No accounts---</option>'; //else if no accounts exist
}
echo '</select>';
//for available webproperties
echo '<br> Available Webproperties: ';
echo '<select name="dropProperties" class="dropProperties">';
echo '<option selected=selected>---Select a webproperty---</option>';
echo '</select>';
?>
</html>
you should append in the ajax success callback:
$(".dropProperties").append(html);
There are a couple of issues here!
For the sake of legibility and syntax highlighting (not to mention that it will draw awareness to your mistakes) you should use direct html output instead of echoing it with php.
Instead of
echo '<select name=dropAccounts class=dropAccounts>';
try
//End php parsing with a closing php tag
?>
<select name=dropAccounts class=dropAccounts>
<?php
//Resume php parsing
This draws attention to the fact that you're not surrounding your attribute values with quotes
Instead of
<select name=dropAccounts class=dropAccounts>
It's important that you quote the attribute:
<select name="dropAccounts" class="dropAccounts">
The next thing is that you're trying to insert the server's output (a raw STRING) into a select element with this code:
success: function(html) {
$(".dropProperties").html(html);
}
I believe this is what you want instead:
success: function(html) {
var newOption = $('<option value="' + html + '">' + html + '</option>');
$(".dropProperties").append(newOption);
}
According to html specification, only option elements should be the children of select elements. In order to add a string into the select element, my code is creating a new option element, making its text the "html" string, and inserting that option element into the select element.
Hope this helps!

Categories

Resources