connecting ajax and php not work - php

what is the problem of this code?
it is menu and page change by ajax with out refreshing the page, but its not working
it is my ajax code
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
});
});
</script>
this is my html tags
<ul>
<li><a class="news" onclick=\"give('news')\" href="#">news</a></li>
</ul>
and php code
mysql_connect("localhost", "root", "")
or die(mysql_error());
mysql_select_db("basi")
or die(mysql_error());
if($_POST['where']=='news'){
$result = mysql_query("SELECT * FROM contents WHERE type = 0");
while ($row = mysql_fetch_array($result)){
$title = $row['title'];
$text = $row['text'];
echo"
<div class='title'><span>$title</span></div>
<div class='content'>
$text
</div>
";
}
}
the information read from DB but dont return to html file.

The problem is with your JavaScript. You're waiting for document ready and (incorrectly) binding a click event listener that isn't being used! Try:
<a class="news" onclick="give('news')" href="#">news</a>
with the JavaScript:
<script>
function give(id) {
$('#main-unit').text('Please Wait...');
var place = id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
}
</script>
A better solution would be to separate HTML from JavaScript - remove the onclick attribute from your menu link, and use pure jQuery to select it and bind an event that calls give() when it is clicked:
$(document).ready(function() {
$('.news').click(function(e) {
give('news');
});
});

FTFY
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
//I believe your mistake was here
success: function(data){
$('#main-unit').html(data);
}
});
});
});
</script>

Related

AJAX load content using link instead of button?

I am trying to load content of a URL which is in a href of a Link using AJAX/JQUERY.
For some reason, the AJAX doesn't get executed and when i click on the Link, the URL will open in a new window!
but I need to load the content of URL on the same page that has the AJAX without opening a new window!
this is my current code:
<div id="content"></div>
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
and the AJAX:
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href);
return false;
});
</script>
just to clarify, I do have the jquery lib included in my page header and I am using it for other stuff on the same page. so the issue is not that.
could some please advise on this issue?
Thanks
You need to prevent the default action of the link:
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$("#content").load(this.href);
return false;
});
</script>
You need to do something with your AJAX return :
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href, function(result){
alert("AJAX done");
});
return false;
});
</script>
You can change the href from the actual page, to a javascript: call. This way, you wouldn't have to concern about the default link redirect.
<a id='listc' class='lisitem' href=javascript:LoadFunction('file.php?id=".$id."'); >".$id."</a>
JS:
function LoadFunction(url) {
$("#content").load(url, function(result){
//something
});
}
Give the following a try:
document.getElementById('listc').addEventListener('click', function() {
$("#content").load(this.href);
return false;
});
UPDATE
Change:
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
to:
<a id="listc" class="listitem" data-id="<?= $id; ?>" href="#"> <?= $id; ?></a>
And AJAX to:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$('#content').load('file.php?id=' + id);
return false;
}
or:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$.post('file.php', {id : id}, function(answer) {
$('#content').html(answer);
});
}
Try something like that :
When you click on the link, do an AJAX call then print the result in your container.
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$.ajax({
url: $(e.currentTarge).attr('href'),
complete: function () {
// remove loading status if neeed
},
success: function (response) {
$("#content").html(response)
},
error: function() {
//manage error here
}
});
});
</script>

How can i load php file after sending ajax data

So I have 2 files file1.php with all the php and ajax, and file2.php with only php.
$_POST["there_id"] will be sent from file1.php page to file2.php through ajax.
file1.php code:
<div class="list_items">
<li><p>content here ...</p>
</div>
<div class="content_area">
//load ajax content here
</div>
$(".box").on("click", function(e) {
e.preventDefault();
var there_id = $(this).attr("id");
$.ajax({
url: "indexnew.php",
type: "POST",
data: { there_id : there_id}
});
});
file2.php code:
<div id="file2content>
<?php
$there_id = $_POST['there_id'];
$user_id = 5;
$fetch_data = regular_query("SELECT * FROM contents WHERE
(user_by = :me or user_by + :them) AND (user_to = :me or user_to = :them)",
["me" => $user_id, "them" = $there_id], $conn);
foreach ($fetch_data as $data) : ?>
<li><p>database data here</p>
<?php
endforeach;
?>
</div>
now what i want to do is when file2.php is done with php and list items are available i want to load file2contents to content_area on file1.php.
$(".box").on("click", function(e) {
e.preventDefault();
var there_id = $(this).attr("id");
$.ajax({
url: "indexnew.php",
type: "POST",
data: { there_id : there_id},
success: function(data) {
$('.content_area').html(data);
}
});
});
However, content_area should really be an id rather than a class so that it's unique.
Since you're just returning html, you can simplify it using the .load() function.
$('.box').on('click', function(e) {
e.preventDefault();
var there_id = $(this).attr('id');
$('.content_area').load('indexnew.php', {there_id: there_id});
});
success: function(data) { $(".content_area").html(data); }
adding the above to your AJAX call should do what you want if I understand you correctly.

delete row with ajax function and php

i have a table with mysql Data,i add a trash button and i want remove each row when trash button is clicked with ajax function,
this is my html:
<table border="1">
<?php
$sql ="SELECT * FROM music";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($result)){
echo '<tr><td>'.$row->file_name.'</td><td>'.$row->composer.'</td><td>'.$row->lyric.'</td><td>'.$row->music_thumb.'</td><td>'.'
<a href="#" id="'.$row->msuic_id.'" class="trash" >
جذف کردن
</a>
'.'</td></tr>';
}
?>
</table>
and my ajax function here:
$(function(){
$('.trash').click(function(){
var del_id= $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type:'POST',
url:'delete.php',
data:del_id,
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})
});
and also my "delete.php" page here:
<?php
include('../db_inc.php');
$music_number = "POST['del_id']";
echo '$music_number';
$qry = "DELETE FROM music WHERE msuic_id ='$music_number'";
$result=mysql_query($qry);
?>
i think my problem is ajax function;
thanks
try this
$.ajax({
type:'POST',
url:'delete.php',
data:{del_id:del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})
and also change
$music_number = "POST['del_id']";
to
$music_number = $_POST['del_id'];
In addition to the above answers, you should delegate your on click handler to prevent unnecessary duplication
$(document).on('click', '.trash', function() { ... });
Your ajax code should be this:
$(function(){
$(document).on('click','.trash',function(){
var del_id= $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type:'POST',
url:'delete.php',
data:{'del_id':del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
});
});
});
And PHP code should be:
<?php
include('../db_inc.php');
$music_number = $_POST['del_id'];
//echo $music_number;
$stmt = $db->prepare("DELETE FROM music WHERE msuic_id=?");
$stmt->execute([$music_number]);
echo "YES";
Try this:
$music_number = POST['del_id']; in delete.php
write ajax function like:
$.ajax({
type:'POST',
url:'delete.php',
data:del_id,
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
});
Thanks
Here are the things that you need to correct
In "delete.php" file
$music_number = "POST['del_id']";
// to
$music_number = $_POST['del_id'];
Also, in the success callback of ajax, you are checking for "YES" in response which is not sent anywhere in this file.
Change to your ajax request
data: {'del_id':del_id},
Hope this helps.
send you data as object and not just value
...
type:'POST',
url:'delete.php',
data:{'del_id':del_id}, //<----here
....
and take it as POST in delete.php
$music_number = $_POST['del_id'];
updated
add this to your delete.php
<?php
include('../db_inc.php');
$music_number = $_POST['del_id'];
$qry = "DELETE FROM music WHERE msuic_id ='$music_number'";
$result=mysql_query($qry);
if($result) {
echo "Yes";
} else {
echo "No";
}
?>
$.ajax({
type:'POST',
url:'delete.php',
data:{del_id:del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})

Ajax load more from PHP

Updated:
I want to make a load more ajax button, I want it to load data from a php file which will extract data from database.
I've managed to make it to load just once, however when I click the new more button it doesn't work.
Here's the Javascript:
$(document).ready(function(){
$(".more").click(function(){
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "more.php",
data: "lastimg="+ ID,
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove(); // removing old more button
}
});
} else {
$(".morebox").html('The End');// no results
}
return false;
});
});
And here's more.php
$lastimg = mysql_real_escape_string($_POST['lastimg']);
$result = $mmhclass->db->query("SELECT * FROM `file_storage` WHERE `is_private` = '0' AND `file_id` < '$lastimg' ORDER BY `file_id` DESC LIMIT 10;", array(MYSQL_FILE_STORAGE_TABLE));
while($row=mysql_fetch_array($result))
{
$file_id = $row['file_id'];
$filename = $row['filename'];
?>
<li>
<?php echo $filename; ?>
</li>
<?php
}
?>
<div id="more<?php echo $file_id; ?>" class="morebox">
more
</div>
It just work once, because after your ajax completed, the .more element will be new on the page,
so the click event handler you attach to it, isn't working anymore.
You must use event delegation:
$('body').on('click', '.more', function () {
// your code
});
Note: jQuery 1.7+ required.
References:
.on() - jQuery API Documentation
I think you may use jQuery live function
$(".more").live("click", function(){
// Code here
});

Change DIV content using ajax, php and jQuery

I have a div which contains some text for the database:
<div id="summary">Here is summary of movie</div>
And list of links:
Name of movie
Name of movie
..
The process should be something like this:
Click on the link
Ajax using the url of the link to pass data via GET to php file / same page
PHP returns string
The div is changed to this string
<script>
function getSummary(id)
{
$.ajax({
type: "GET",
url: 'Your URL',
data: "id=" + id, // appears as $_GET['id'] # your backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
And add onclick event in your lists
<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>
You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load() method to send an AJAX request and replace the contents of the summary div:
$(function() {
$('.movie').click(function() {
$('#summary').load(this.href);
// it's important to return false from the click
// handler in order to cancel the default action
// of the link which is to redirect to the url and
// execute the AJAX request
return false;
});
});
try this
function getmoviename(id)
{
var p_url= yoururl from where you get movie name,
jQuery.ajax({
type: "GET",
url: p_url,
data: "id=" + id,
success: function(data) {
$('#summary').html(data);
}
});
}
and you html part is
<a href="javascript:void(0);" class="movie" onclick="getmoviename(youridvariable)">
Name of movie</a>
<div id="summary">Here is summary of movie</div>
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
jQuery.load()
$('#summary').load('ajax.php', function() {
alert('Loaded.');
});
<script>
$(function(){
$('.movie').click(function(){
var this_href=$(this).attr('href');
$.ajax({
url:this_href,
type:'post',
cache:false,
success:function(data)
{
$('#summary').html(data);
}
});
return false;
});
});
</script>
<script>
function getSummary(id)
{
$.ajax({
type: "GET",//post
url: 'Your URL',
data: "id="+id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>

Categories