I am building a system where the user builds their own navigation system, the process is when the user visits the site there is a llist of available topics they can select slect a top creates and accordion that holds all that topics content, clicking the topic again should remove the top, currently I have this code, but it does not work, can any one guide me,
The javascript
$("a.navlink").click(function(ev) {
var url = $(this).attr("href")
var id = $(this).attr("id")
ev.preventDefault();
if(!$(this).hasClass('saved')) {
//$("a.navlink").addClass('active')
$.ajax ({
url: url,
type: "POST",
data: "method=add&id="+id,
success: function (html) {
$('#accordion').accordion('destroy');
$("#accordion").append(html);
$('#accordion').accordion({
//active: 0,
header:'h2.'+id,
collapsible:true
});
$("a.navlink").addClass('saved');
}
});
} else if($("a.navlink").hasClass('saved')) {
$.ajax ({
url: url,
type: "POST",
data: "method=delete",
success: function (html) {
$("a.navlink").removeClass('saved');
//$("."+id).remove();
}
});
}
});
The HTML/PHP That builds the accordion
<?php
var_dump($_POST);
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class=".$this->input->post('id')."><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
if(isset($favourites_category)) {
//die(var_dump($favourites));
echo "<h2 class=".$this->input->post('id')."><a href='#'>$favourites_category</a></h2>";
$count = 0;
$replace = array(".", "png", "gif", "jpg");
foreach ($favourites as $row) {
$count ++;
$image_name = str_replace($replace, "", $row['image_name']);
echo "<div class='$favourites_category'>";
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$row[content_id]'>";
echo "<img src='/media/uploads/".strtolower($row['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "<a/>";
echo "</div>";
}
}
?>
Basically I need away to identify each accordion that is created and if its link is pressed while it has an accordion on scrren the accordion is deleted from the HTML on screen.
The callback function has a different context than the ajax call. Your variables id and url are not accessible in your callbacks. You can have them passed through the ajax call to use it in the callback, but the response should be JSON instead HTML.
Also, you have $("a.navlink") (which will evaluate to the first a.navlink) instead of $(this) in a few places ( like the else if).
Here's some updated code, but I'm not real clear on what you are trying to do
$("a.navlink").click(function(ev) {
var url = $(this).attr("href")
var id = $(this).attr("id")
ev.preventDefault();
if(!$(this).hasClass('saved')) {
//$("a.navlink").addClass('active')
$.ajax ({
url: url,
type: "POST",
data: {method: 'add', id: id},
dataType: "json",
success: function (response) {
//vars url and id are not accessible here
//so it needs to be returned from the ajax call
$('#accordion').accordion('destroy');
$("#accordion").append(response.html);
$('#accordion').accordion({
//active: 0,
header:'h2',
collapsible:true
});
$("#" + response.id).addClass('saved');
}
});
} else if($(this).hasClass('saved')) {
$.ajax ({
url: url,
type: "POST",
data: {method: 'delete', id: id},
dataType: "json",
success: function (response) {
$("#" + response.id).removeClass('saved');
$("h2." + response.id).remove();
}
});
}
});
Related
I want to split the echo which comes from php in 2 different divs in my ajax success.
$.ajax({
url: 'counter.php',
type: 'POST',
data: {
some_data:some_data
},
success: function(data){
$('.div1').html(data); // in here 1st echo
$('.div2').html(data); // in here 2nd echo
},
});
Piece of code from counter.php looks like this:
if (file_exists($blogfile)) {
echo 'content updated'; // this echo should come in div1
}
else {
echo 'file does not exist anymore'; // this echo should come in div2
}
How can i achieve this?
One way to do it is to return a JSON object from your PHP, which contains two properties: firstly - the message itself, secondly - some sort of status indicator which the JS can use to decide what to do with the message.
e.g.
PHP:
$result = array();
if (file_exists($blogfile)) {
$result["message"] = 'content updated'; // this echo should come in div1
$result["status"] = 1;
}
else {
$result["message"] = 'file does not exist anymore'; // this echo should come in div2
$result["status"] = 2;
}
echo json_encode($result);
JavaScript:
$.ajax({
url: 'counter.php',
type: 'POST',
data: {
some_data:some_data
},
dataType: "json",
success: function(data){
var div;
if (data.status == 1) div = $('.div1');
else div = $('.div2');
div.html(data.message);
},
});
I've written an Ajax code, which calls a function in a php file.
queryURL = "http://<?php echo $_SERVER['SERVER_NAME'] ?>/MyPhpFile.php";
params = fromDate+" , "+to_Date;
$.ajax(
{
url: queryURL,
type: "post",
dataType: 'json',
async: false,
data:
{
funcName: "MyFunc",
values: params
},
complete: function (result) {
debugger;
doSth();
}
});
And in my php file:
if ($_POST) {
if (isset($_POST['funcName'])) {
if (function_exists($_POST['funcName'])) {
G::LoadClass('case');
$fName = $_POST['funcName'];
if (isset($_POST['values'])) {
$values = $_POST['values'];
$arrP = explode(",", $values);
echo call_user_func_array($fName, $arrP);
} else {
echo $fName();
}
}
}
}
fucnction MyFunc($fromDate, $toDate){
echo "1";
}
In the Network tab of my browser's debugger section, I can see that the php file just called once. Yet the response is duplicated.
If my function returns 1, the response will be 11.
Why is this happening?
how can I prevent it?
Remove echo from echo call_user_func_array($fName, $arrP);. Just use call_user_func_array($fName, $arrP);
My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}
I have got this html
<div class="Likes" data-i=<?php echo $row[8];?>>
<img src="../img/like.png">
<p class="L_c"><?php echo $row[4];?></p>
</div>
And this jquery/ajax
$(".Likes").click(function() {
var i = $(this).attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
$(this).children(".L_c").html(data);
}
});
});
Connect.php
if (isset($_GET["I"]) && !isset($_GET["C"])) {
$RandS=$_GET["I"];
$query3=$con->query("SELECT id,likes FROM uploads WHERE Rand='$RandS'");
$row=$query3->fetch_row();
$IdU=$row[0];
$Likes=$row[1];
$Sel2=$con->query("SELECT id FROM likes WHERE User_id='$NameId' AND Post_id='$IdU'");
$num_rows=$Sel2->num_rows;
if ($num_rows>0) {
echo $Likes;
}else{
$query=$con->query("INSERT INTO likes (Post_id,User_id,`DATE`) VALUES('$IdU','$NameId',NOW())");
$query=$con->query("UPDATE uploads SET Likes=$Likes+1 WHERE Rand='$RandS'");
echo $Likes+1;
}
}
But it does not return anything untill i refresh the page
The this keyword inside the $.ajax methods callback is not the element, but the ajax call itself.
You have to either set context, or just store the outer this -value
$(".Likes").on('click', function() {
var me = $(this);
var i = me.attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
me.find(".L_c").html(data);
}
});
});
I have one issue with ajax when I get echo success on my php. I don't get execute the first if
if(text[0]==="success")
Code inside php
if(count($error)==0)
{
$user = ORM::for_table('usuario')->create();
$user->username = $username;
$user->contrasenia = password_hash($password, PASSWORD_DEFAULT);
$user->email = $email;
$user->admin = $is_admin;
$user->save();
echo "success";
}
else
{
$error = json_encode($error);
echo $error;
}
My code in ajax
[![$("#create-button").on('click', function(event){
//cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm()
{
var dataString = $("#userForm").serialize();;
$.ajax({
dataType: "json",
type: "POST",
url: "/altausers",
data: dataString,
success: function(text)
{
console.log("hola");
console.log(text);
if(text\[0\]==="success")
{
alert("hola");
//$("#error").addClass('hidden');
}
else if(text.length > 0)
{
$("#error").removeClass('hidden');
texterror = "<ol type='disc'>";
$.each(text,function(index,value)
{
texterror+="<li>"+value+"</li>";
});
texterror+="</ol>";
document.getElementById("error").innerHTML = texterror;
}
}
});
}
Image console
What is the problem?
Could say me which it is problem?
I have that convert the message success to json too
Replace the success echo with
echo json_encode(["success"]);
or leave echo the same and replace if in ajax
if(text == "success")
The problem could be that it is an array, so you can try this:
$.ajax({
url: "items.php",
async: false,
type: "POST",
dataType: "JSON",
data: { "command" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});
And if you want to see the results:
Object.keys( response ).forEach(function( key ) {
console.log('key name: ', key);
console.log('value: ', response[key]);
});