I have two pages, index.php and block1.php
I wanted to load a data from block1.php to a div #details in index.php
here's my code
index.php
<div id="pop_box">
<div class="close"><span id="close">×</span></div>
<div id="block"></div>
<div id="details"></div>
</div>
block1.php
<script>
$(document).ready(function() {
var lnk;
$('[href]').click(function() {
lnk = '';
lnk = $(this).attr('href');
if (lnk.charAt(1) == "b") {
var lot = lnk;
$.ajax({
url: "2dmap_func.php",
method: "POST",
dataType: "text",
data: {
lot: lot
},
success: function(data) {
//alert(data);
$('index.php #pop_box #details').load(data);
}
});
}
});
});
</script>
as you can see I want to load the data from block1.php to index.php's div#details and this code doesn't work.
$('index.php #pop_box #details').load(data);
In you index.php add following line:
<?php include_once 'block1.php' ?>
In your block1.php change following line:
$('index.php #pop_box #details').load(data);
to
$('#details').html(data); // if data is valid html
Related
I'm working on yii2 project and we need to load blocks with ajax on click.
I wrote ajax part that works correctly but im stuck with javascript. My mentor says I should use .append but I cant find way to link it somehow with controller action.
php:
public function actionGetProjects() {
$post = Yii::$app->request->post();
$projects = Project::find()->orderBy('created_at DESC')->limit(15)->offset($post['page']*15)->all();
if (count($projects)>0) {
$this->return['code'] = 200;
$this->return['html'] = $this->renderPartial('_projects', [
'projects' => $projects
]);
} else {
$this->return['code'] = 404;
}
return json_encode($this->return);
}
UPD:
HTML
<div class="projects">
<div class="pageHeader">My Projects</div>
<?php foreach ($projects as $project) {?>
<a href="project/<?=$project->id?>" class="project-block">
<img src="<?=$project->projectImages[0] ? '/img/products/'.$project->projectImages[0]->image:''?>">
<div class="project-title"><?=$project->name?></div>
<div class="project-address"><?=$project->address?></div>
<div class="project-readmore">Read more</div>
</a>
<?php } ?>
<a class="projects-load-btn" href="#">Еще</a>
</div>
New JS:
$(".projects-load-btn").on("click", function(e) {
event.preventDefault();
var id = $(this).data("id") || 0;
$.ajax({
type: 'POST',
url: '/ajax/get-projects',
data: { id: id },
dataType: "json",
success: function (data) {
if(data.code == 200){
$('.projects').addClass('test');
$('.projects').html('');
$('.projects').append(data);
}
},
errors: function (errors) {
console.log(errors);
}
});
});
Do you have urlManager component configured with enablePrettyUrl set to true in your config file?
If so, yii2 uses the following default routing template: <controller>/<action>
In you case this would result in /ajax/get-projects url.
The complete JavaScript code would look something like this:
$(".projects-load-btn").on("click", function(e) {
e.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "/ajax/get-projects",
data: { id: id }
}).done(function (data) {
$(".projects").append(data);
});
});
If I remember correctly you should not send the action as a variable through POST.
It depends on how routing was set in your Yii2 app, thus I'm only guessing:
An ajax call:
$.post("Ajax/getProjects", {id:id}, function(data) { ... });
Appending something in DOM:
$(".projects").append(jsonResponse.html);
Guessing this is school work, thus not giving the whole solution...
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.
I've a link in my php page. Which I want to send a id request to server. But it doesn't response correctly. Actually, I've got two pages.
a. users.php
b. user_update.php
So I'm trying a send a request to the server using jquery/ajax by user id from users.php page to user_update.php for update the details and get back the successful result to user.php page.
The code is look like this:
<div id="edit_user_details">Edit Details</div>
<script>
$('#edit_user_details').click(function() {
id = <?php echo $uid; ?>
$.ajax({
url: edit_user_details.php,
type: post,
data: id;
success: function(response) {
$('#edit_user_result').html(response);
}
});
});
</script>
But it's not working properly. is there anything I'm missing because of I'm new learning of Jquery/Ajax. :)
Update:
I'm requesting this id in php while loop. It's look like this..
while($search_result = mysql_fetch_array($getUser)){
$uid = (int) $search_result['user_id'];
<div id="edit_user_details">Edit Details</div>
}
<script>
$('#edit_user_details').click(function() {
id = <?php echo $uid; ?>;
$.ajax({
url: 'edit_user_details.php',
type: 'post',
data: {'id' : id},
success: function(response) {
$('#edit_user_result').html(response);
}
});
});
</script>
Is it wrong ? What I'm trying is... I want to update user details base on their id. So what need to do for this ?
you need to create a unique id in loop or create a function and calll it onclick like
<?php while($search_result = mysql_fetch_array($getUser)){
$uid = (int) $search_result['user_id']; ?>
<div id="edit_user_details">Edit Details</div>
<?php }?>
<script>
function myfunc(id) {
id = id;
$.ajax({
url: 'db_search.php',
type: 'post',
data: {'id' : id},
success: function(response) {
$('#edit_user_result').html(response);
}
});
}
</script>
you should end your id initialization with a semi-colon;
id = <?php echo $uid; ?>;
Check the correct way of using ajax in this example: Demo ajax using JQuery
Make changes as shown below and try again..
1: Add 'post' in type.
2: Add ''edit_user_details.php' in url
3: Add semicolon at the end here
<?php echo $uid; ?>;
4: take your id as shown in below code
Updated code :-
<script>
$('#edit_user_details').click(function() {
id = <?php echo $uid; ?>;
$.ajax({
url: 'edit_user_details.php',
type: 'post',
data: {'id' : id},
success: function(response) {
$('#edit_user_result').html(response);
}
});
});
</script>
For more information :-
https://api.jquery.com/jQuery.ajax/#entry-examples
i think you are not declaring var id before
try
<div id="edit_user_details">Edit Details</div>
<script>
$('#edit_user_details').click(function() {
var id = <?php echo $uid; ?>;
$.ajax({
url: edit_user_details.php,
type: post,
data: [id:id],
success: function(response) {
$('#edit_user_result').html(response);
}
});
});
</script>
Check your url inside $.ajax. If you are sending your data to user_update.php then your code should be as follows :
<script>
$('#edit_user_details').click(function() {
id = <?php echo $uid; ?>
$.ajax({
url: user_update.php,
type: post,
data: id,
success: function(response) {
$('#edit_user_result').html(response);
}
});
});
</script>
Just change your url to user_update.php and put a comma(,) after data:id in the place of semicolon(;).
This code will works fine for what you need and with less lines, assuming that the PHP var $uid will be processed on loading the page:
<div id="edit_user_details">Edit Details</div>
<script>
$('#edit_user_details').click(function() {
$.get('edit_user_details.php', 'id=<?php echo $uid; ?>', function(response){
$('#edit_user_result').html(response);
});
});
</script>
I have some JQuery handling a div click. If the div is clicked once it hides itself and shows another div (and posts to a php script in the background). If it is then clicked again, it's supposed to hide the new div, show the new one again, and post more data to a different script, and so on.
It changes the first time (.f hides, .uf shows) but when I click '.uf' nothing happens.
JQuery:
if($('.f').is(":visible")) {
$('#follow').click(function() {
var to_follow = $('.name').attr('id');
$.ajax({
type: "POST",
url: "/bin/rel_p.php",
data: "y=" + to_follow,
success: function() {
$('.f').hide();
$('.uf').show();
}
});
});
}
else {
$('#follow').click(function() {
var to_unfollow = $('.name').attr('id');
$.ajax({
type: "POST",
url: "/bin/relu_p.php",
data: "y=" + to_follow,
success: function() {
$('.uf').hide();
$('.f').show();
}
});
});
}
HTML:
<div id="follow" class="f">
<img src="img/icons/Follow.png">
<h1>Follow</h1>
</div>
<div id="follow" class="uf" style="display:none;">
<img src="img/icons/Unfollow.png">
<h1>Unfollow</h1>
</div>
use a class if you intend to use the selector twice, and don't write the same code twice unless you have to:
$('.follow').on('click', function() {
var is_f = $('.f').is(":visible"),
to_follow = $('.name').attr('id'),
give_me_an_u = is_f?'':'u';
$.ajax({
type: "POST",
url: "/bin/rel" + give_me_an_u + "_p.php",
data: {y : to_follow}
}).done(function() {
$('.f, .uf').toggle();
});
});
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>