Ajax Onchange replace div not working - javascript

I have a select box with onchange,
<select class="form-control" onchange="getval(this.value,'<?php echo $prd->pr_id;?>','ajax<?php echo $key?>','<?php echo $key ?>')">
and my ajax div is in foreach loop,
foreach($name as $names)
{
<div id = "ajax<?php echo $key?>" Some Content </div>
}
My ajax function:
function getval(id,prid,divid,key)
{
alert(divid)
$.ajax({
type: "POST",
data: "aid="+id+"&prid="+prid,
url: '<?php echo site_url('grocery/onchange')?>',
success: function(html){
$('#'+divid).html(html);
};
});
}
i am tryimg to change the div content..but its not working?

You need a lot of changes in your ajax-
first use console.log() instead of alert and then because your div's id(s) are being created dynamically then you need to handle it in this way-
$.ajax({
type: "POST",
data: {aid:id,prid:prid},
url: '<?php echo site_url('grocery/onchange')?>',
success: function(html){
$(document).find('div[id='+divid+']').html(html);
};
});
Here is the live example- http://jsfiddle.net/x4Lvfk9k/

Related

Ajax - Update database on button click

I need some help with a project. I'm still learning javascript and jquery so bear with me. The website that I'm working on needs to update a database entry when a button is clicked, the button content is also queried from the database.
First database query to get the buttons:
<?php
$freq_sql = "SELECT freq FROM disc_freq WHERE in_use='0'";
$result_freq = $connection->query($freq_sql);
echo "<h5>Available frequencies</h5>";
while($row = mysqli_fetch_array($result_freq)){
$set_freq=$row[0];
?>
<a id='button' class='w3-bar-item w3-button'><?php echo $set_freq ?></a>
Then the ajax script I tried but there is something wrong with it
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":<?php echo $set_freq ?>},
success: function(data){
data = JSON.toString(data);
}
});
});
});
Finally the php file
<?php
session_start();
include("konf.php");
if(isSet($_POST['set_freq'])){
$update_sql="UPDATE disc_freq SET in_use = '1', working_usr='".$_SESSION['username']."' WHERE freq='".$_POST['ins_freq']."'";
$update_run=mysqli_query($connection,$update_sql);
}
?>
For some the first button when clicked on initiates same number ajax calls of how many buttons have been displayed. Others won't do anything.
The php code does work but the only problem is the ajax call and I haven't found a solution yet so any help is appreciated.
please update code as in your code there is error in ajax script in js
change
you can change code from
data: {"set_freq":<?php echo $set_freq ?>},
to
data: {"set_freq":'<?php echo $set_freq ?>'},
First of all you should prevent your page to refresh because you are clicking on a tag so.
You should send your data with #pritamkumar's answer or also send like my answer.
$(document).ready(function(){
$("#button").click(function(event){
var data=$(this).text();
event.preventDefault()
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data},
success: function(data){
data = JSON.toString(data);
}
});
});
});
As per your comment that there are many links than you should change your selector. Like as below
<a class='button' class='w3-bar-item w3-button'><?php echo $set_freq ?></a>
And also change JS code
$(".button").click(function(event)
there is always passed the same value to ajax
data: {"set_freq":<?php echo $set_freq ?>},
in html change
<a id='button' class='button w3-bar-item w3-button' data-freq='<?php echo
$set_freq ?>'><?php echo $set_freq ?></a>
in js
$(document).ready(function(){
$(".button").click(function(){
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":this.data('freq')},
success: function(data){
data = JSON.toString(data);
}
});
});
});
i didn't test it - writing from "memory"

ajax post to php a null variable

I have a script that copies an entire div into a variable. It works when I alert the data, but It wont work when I try to echo it in php.
<script>
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php?id='+vin,
data: {ordering:orderIm},
dataType: 'html'
})};
</script>
And my php:
<?php
echo $_GET['id'];
echo '<br />';
echo gettype($_POST['ordering']);
echo $_POST['ordering'];
?>
Output:
JS2YB417785105302
NULL
You can using full post request
<script>
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php,
data: {ordering:orderIm,id:vin}, // added id:vin on POST parameter
dataType: 'html'
})};
</script>
And my php :
<?php
echo $_POST['id']; // converted into $_POST
echo '<br />';
echo gettype($_POST['ordering']);
echo $_POST['ordering'];
?>
when i use the succes function :
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php',
data: {ordering:orderIm,id:vin},
dataType: 'html',
success: function(data) {
alert(data)}
})};
it shows the correct data. i guess it means that its solved. i just dont see it in the php file while i access it via the console log--> double clicking on XHR finished loading.
even tho the variables types shows NULL in the php script, i can still manipulate the content of them and everything is working fine !

submitting form with ajax and php

Hi I have a page that lets a user view results for a certain tournament and round
User will select sport then tournament is populated based on sport selection then user will select round which is populated based on tournament selection
When all is done user press Submit button which will look up the results for the result based on tournament and round selected
My code is working great:
mainPage.php
<script type="text/javascript">
$(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>
get_sport.php
<label>Sport :</label>
<form method="post">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
get_round.php
if($_POST['id'])
{
$id=$_POST['id'];
$sql="SELECT DISTINCT round FROM events WHERE tournament='$id'";
$result=mysql_query($sql);
?>
<option selected="selected">Select Round</option><?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['round'] ?>"><?php echo $row['round'] ?></option>
<?php
}
}
?>
EXAMPLE
Sport=>Football; Tournament=>EPL; Round=>5;
Assuming the above is selected when the user clicks submit the code will query select results from someTable Where sport='Football' AND...
My Problem
I get the data from the selectboxes by using a simple php isset() function
if(isset($_POST['submit'])){
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
:
:
Now my problem is when submit is clicked everything works BUT the form gets reloaded, which is what I don't want
Im looking for an AJAX equivalent of isset() or a way for the data to be submitted without the form reloading
Any ideas/help will greatly be appreciated
There is a different ways to avoid the reload of a submit form.
A solution would be to handle the submit action of the form and return 'false' ( Example here and here) or preventing the default action ( Example here )
You can also replace the input type submit for an input type button (or button), and handle the click button action instead of handling the form submit action. This would be an easy workaround to most of your 'form submit' problems, but is a worst solution in the semantic and valid code point of view.
You can do the form submission from JQuery as an AJAX request and do the resulting in the success.
jQuery(document).ready(function(){
jQuery('#form').submit(function(ev) {
$.ajax({
url : 'url',
type : 'POST',
dataType: 'json',
data : $('#form').serialiseArray(),
success : function( data ) {
// Populate the result
}
});
ev.preventDefault();
});
});
Initially load all the values in Sport: Dropdown
Then dynamically populate the Tournament and Round
// To Trigger Sport Change
$(".sport").change(function () {
var selected_sport = $(".sport").val();
var dataString = 'sport=' + selected_sport;
var urlAddress = "get_sport.php";
$.ajax({
url: urlAddress,
cache: false,
method: 'post',
data: dataString,
dataType: 'html',
success: function (result_data) {
$(".tournament").html(result_data);
// This will append the tournament drop-down dynamically
}
});
});
// To Trigger Tournament Change
$(".tournament").change(function () {
var selected_sport = $(".sport").val();
var selected_tournament = $(".tournament").val();
var dataString = 'sport=' + selected_sport + '&tournament=' + selected_tournament;
var urlAddress = "get_round.php";
$.ajax({
url: urlAddress,
cache: false,
method: 'post',
data: dataString,
dataType: 'html',
success: function (result_data) {
$(".round").html(result_data);
}
});
});
In your Corresponding PHP get_round.php
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
foreach ($row as $r) {
$round = $r['round'];
echo '<option value = "' . $round . '">' . $round . '</option>';
}
}

php/ajax like button not working

hi guys i try to create like button with php and ajax so write this codes but just work in first loop
<?php header('Cache-Control: no-cache'); ?>
<script>
$(document).ready(
function(){
$("#like").click(function(){
$.ajax({
type: "POST",
url: "<?php echo ADDRESS ;?>thank.php",
data: "like="+$("#like").val(),
success: function(result){
$("#result").html(result);
}
});
});
}
);
</script>
<?php
foreach ($this->value['posts'] as $post){
echo $post[1] . $post[0] .$post[2] . $post[3] . '</br>';
echo '<div id="result"></div>';
}
?>
I think the problem is in my #like that repeat and jquery dont know which one is our div
ok some one answered my question but id dont know why deleted :O
any way he or she writed
$(this)
thanks!
your code not worked but help me to fix that ok problem was in my button value ! all the buttons returned value for the first loop so i changed the js code to this
<script>
$(document).ready(
function(){
$(".like").click(function(){
var spdiv = ".result" + $(this).val();
$.ajax({
type: "POST",
url: "<?php echo ADDRESS ;?>thank.php",
data: "like="+$(this).val(),
success: function(result){
$(spdiv).html(result);
}
});
});
}
);
</script>
and i use class instead of id .
IDs are Identifiers - meaning they must be unique! Also your script is messy and I guess you didn't mention there are many like buttons on the page, right?
Try this PHP code:
foreach ($this->value['posts'] as $index=>$post) {
echo '<div class="comments">';
echo $post[1] . $post[0] .$post[2] . $post[3] . '</br>';
echo '<button class="like" data-id="<?php echo $index; ?>">LIKE</button>';
echo '<div class="result"></div>';
echo '</div>';
}
And this javascript:
$(document).ready(function(e) {
$("div.comments").on("click", "button.like", function(e) {
$.ajax({
type: "post",
url: "<?php echo ADDRESS ;?>thank.php",
data: {
like: $(this).attr("data-id")
},
success: function(data, textStatus, jqXHR) {
$(this).siblings(".result").html(data);
}
});
});
The script above will add an event listener to all buttons that have the class like. The $(this) will refer to the like button and the $(this).siblings(".result") will get the result div that is a direct sibling of the like button(!), meaning they both sit in the same <div class="comments">.
I have changed the way you approach DOM elements. I also added a new identifier to your LIKE button so don't forget to change this data-id to suit your needs!

Facing on Make Like Unlike Button in php , mysql using ajax calling

I m creating like and unlike button for my website , at my local server i used seprate file it it working fine but when i install at my website then it is not working properly.
I m Fetching some information using this code from url bar
<?php
error_reporting (0);
include "includes/session.php";
include 'database/db.php';
extract($_REQUEST);
if(isset($_GET["i"]))
{
$pid=($_GET['p']);
$lid=($_GET['i']);
}
?>
<?php
$likquery = mysql_query("select * from likes where userid=$id and postid=$lid");
if(mysql_num_rows($likquery)==1){
?>
<a class="unlike" id="<?php echo $lid ?>">UnLike</a> <span class="like_update" id="<?php echo $lid ?>"></span>
<?php }else{?>
<a class="like" id="<?php echo $lid ?>">Like</a>
<?php
}?>
AFTER this I use script
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('body').on('click','.like',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$('body').on('click','.unlike',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
And I m not getting any response but when i use
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(".like").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$(".unlike").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
only once it is changing the value
Ok, the second version works only once, because at the beginning, the event is on the button, then you re-render the button by changing it's class and text, so the events get unbinded.
Same is for the 1st version. Jquery says: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().... If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
So re-bind the events after changing the button.
I suggest something like this:
function bindEvents() {
$('.like').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
//rebind events here
bindEvents();
}
});
$('.unlike').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
//rebind events here
bindEvents();
}
});
}
$(document).ready(function(){
bindEvents();
});
Also notice that in var postData = 'postid='+postId+'&uid=<?php echo $id ?>'; code, the php part won't be treated as php. It will be just a string. So replace that part with the following, assuming that the code is located inside a php file:
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;

Categories