echo '<script>
function ' . $row['idname'] . 'Click(){
$( "#flip-' . $row['idname'] . '" ).flipswitch( "disable" );
var isOff = document.getElementById("flip-' . $row['idname'] . '").value;
if(isOff == "off"){
console.log("action.php?do=turn-off-' . $row["id"] . '");
jQuery.ajax({
url: "action.php?do=turn-off-' . $row["id"] . '",
type: "GET",
success:function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
}else{
console.log("action.php?do=turn-on-' . $row["id"] . '");
jQuery.ajax({
url: "action.php?do=turn-on-' . $row["id"] . ',
type: "GET",
success : function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
}
}
</script><br>';
So my problem is that ajax doesn't even load the page that is requested.
It creates this code from the result of a MySQL query, so it's basically a JavaScript file in a PHP File. The target is an empty page that only has some functions.
The function is invoked onChange from this <select>:
echo '<div class="ui-field-contain" style="width: 100%;">
<label for="flip-' . $row['idname'] . '">' . $row['name'] . '</label>
<select onchange="' . $row['idname'] . 'Click()" name="flip-' . $row['idname'] . '" id="flip-' . $row['idname'] . '" data-role="flipswitch">
<option value="off" selected="">Aus</option> <option value="on">An</option>
</select>
</div>';
This may solve the problem because it is not a nice way to just replace it with always. You might consider adding some error handling where no wrong elements are tested to be selected with the error message as a part of the id.
Deprecated jqXHR.success()
The issue may occur because this method is deprecated since jQuery 1.8. It has been replaced by jqXHR.done().
jQuery.ajax({
url: "action.php?do=turn-on-' . $row["id"] . '",
type: "GET",
done: function (data) {
$( "#flip-' . $row['idname'] . '" ).flipswitch( "enable" );
console.log("SUCCESS!!");
}
});
Suggesting another way
$.get("api.php", {
do: "turn-on-' . $row["id"] . '"
}, function (data) {
console.log(data);}
});
Related
I am working with jQuery and PHP. I am using AJAX in the controller and I am getting "Feeds" (Posts) in a PHP loop.
The issue is that whenever I click on any button in that loop it shows me the alert multiple times instead of one time. How can I solve this?
Right now I just alert a simple message for the test but the alert box shows more than 1 time after a single click. I just want that it should alert only one time so I can write/execute my function further.
Thank you in advance.
<?php
function fetch()
{
$FeedId;
(dynamic) $FeedData = $this
->M_main
->GetFeedData(); // getting feed data from database
foreach ($FeedData as $feeds)
{
if ($feeds['flag'] == "feed")
{
$GetFeedComments = $this
->M_main
->GetFeedsComment($FeedId);
$TotalFeedsComments = $GetFeedComments['TotalRows'];
if ($TotalFeedsComments > 1)
{
$Loads = '<div class="show_more_main" id="show_more_main' . $postID . '">
<input type="hidden" name="fixs" value="' . $postID . '" id="fixs">
<input type="hidden" name="MinValue" value="' . $postID . '" id="MinValue">
<input type="hidden" name="MaxValue" value="' . $postID . '" id="MaxValue">
<span id=' . $postID . ' data-val=' . $postID . ' data-status=' . $postID . ' class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>';
}
else
{
$Loads = "";
}
}
}
$paths = base_url() . "Main/AddComments";
echo "<script>
$('.show_more').click(function (e) {
e.preventDefault();
alert("Helloworld");
});
</script>";
}
?>
In php, I want to pass a php variable using the jquery.post method.
The first figure shows the code that post the variable
first
The second figure shows to read the posted variable.second
php variable contains some statements, but output will print the variable names like "$rxss", "$sxss".
The post method seems to be writing the data part incorrectly, so please let me know how to write it.
add
i already tested
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
}, 500); ......
-
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:"" + $rxss + "",sxss:"" + $sxss + "",sqli:""+ $sqli + "",basqli:"" + $basqli + "",autoc:"" + $autoc + "",idor:"" + $idor + "",dirlist:"" + $dirlist + "",bannerdis:"" + $bannerdis + "",sslcert:"" + $sslcert + "",unredir:"" + $unredir + "",clamav:"" + $clamav + ""}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:"" + $rxss + "",sxss:"" + $sxss + "",sqli:""+ $sqli + "",basqli:"" + $basqli + "",autoc:"" + $autoc + "",idor:"" + $idor + "",dirlist:"" + $dirlist + "",bannerdis:"" + $bannerdis + "",sslcert:"" + $sslcert + "",unredir:"" + $unredir + "",clamav:"" + $clamav + ""}, function(data){$("#status").html(data)});
}, 500); ......
but when these test not showing getStatus.php and apache log haven't error
You can you this $("$yourvariable")
Also take a look at this How to call PHP function from string stored in a Variable
My question, before I go further with how I did it, is: How can I make this work, and make it easier and better than what I have done?
I have a database with a lot of data, and I am viewing all these in a table. Each <td> has a <div title=""> included, so that all who mouseover each <td> can see more information about that data item. The trouble is, that it's only viewable as a table on mobile devices. To create a hyperlink for a new page is difficult, because that takes the user away from a <table> with comparrision to just that one data information. So I was thinking to use jQuery UI. And was reading a little over the "Basic Dialog" option. I tried to put that into my script, but I see I have way too much data. So I created a file called jq_scripts.php. In there I have a script to create dialog options. But first I include it like this in the header:
<script src=\"//code.jquery.com/jquery-1.10.2.js\"></script>
<script src=\"//code.jquery.com/ui/1.11.4/jquery-ui.js\"></script>
<script src=\"jq_scripts.php\" type=\"text/javascript\"></script>
Then in the script I have put this as a standard:
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
});
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
});
But since I have so many different dialogs, I need one #id to each button with unique information, so this is what I have as a script:
echo "\$(function() {\n";
$result = mysqli_query($con, "SELECT * FROM $database WHERE type = 1");
$num = mysqli_num_rows($result);
if(!$result) {
die('Invalid query: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
foreach($abo as $abo_vis) {
$abo_vis = strtolower(str_replace(' ', '', $abo_vis));
echo " \$( \"#dialog_" . $abo_vis . "_" . $id . "\" ).dialog({\n";
echo " autoOpen: false,\n";
echo " });\n\n";
echo " \$( \"#opener_" . $abo_vis . "_" . $id . "\" ).click(function() {\n";
echo " \$( \"#dialog_" . $abo_vis . "_" . $id . "\" ).dialog( \"open\" );\n";
echo " });\n\n";
}
}
echo "});\n";
This creates a viewing file with 12583 lines!!!
In a <td> I have put this _DATA_ and in the bottom of the viewing file, I have created this:
echo "<div id=\"dialog_" . $abo_vis . "_" . $id . "\" title=\"" . $abo_vis . "\">\n";
echo "<p>" . $dialog_info[$id] . "</p></div>\n\n";
This creates this file to be a lot longer than needed. And on top of that, none of my <a href="#"> works. Actually, the <div id="dialog..."> actually shows, while on the demo it was hidden.
Maybe your problem is the way you are calling it, instead of using IDs use classes:
echo "<div class=\"dialog_" . $abo_vis . "_" . $id . "\" title=\"" . $abo_vis . "\">\n";
I have a html form in which user can select an option upon which ajax call should be fired to php controller.
<form action="<?php echo URL . 'task/show_list/' . $this->tasks[0]->list_id;?>" method="GET" id="#sortTaks">
<select name="sort_task" id="selectSortTask">
<option value="" selected="selected">Sort by:</option>
<option value="byName">Name</option>
<option value="byDeadline">Deadline</option>
<option value="byPriority">Priority</option>
<option value="byStatus">Status</option>
</select>
<input type="submit" value="Submit">
</form>
Now, i would like that sort functionality provided asynchronously with ajax. This is the corresponding php code:
//controller
public function show_list($list_id)
{
if (isset($list_id)) {
$task_model = $this->loadModel('TaskModel');
$check = $task_model->checkUserPermission($list_id);
if ($check) {
$tasks = $task_model->showTasks($list_id);
$this->view->tasks = $tasks;
$this->view->render('task/task');
} else {
header('location:' . URL . 'dashboard/index');
}
} else {
header('location:' . URL . 'dashboard/index');
}
}
//model
public function showTasks($list_id)
{
if (isset($_GET['sort_task']) and !empty($_GET['sort_task'])) {
$sort_parameter = strip_tags($_GET['sort_task']);
$sort_order = $this->sortData($sort_parameter);
$sort_order = 't.task' . $sort_order;
} else {
$sort_order = 't.task_name';
}
$sql = "SELECT t.task_name, t.task_id, t.task_priority, t.task_deadline, t.task_completed, l.list_id
FROM task AS t
LEFT JOIN list AS l ON l.list_id = :list_id AND l.list_id = t.list_id
WHERE l.user_id = :user_id
ORDER BY $sort_order";
$query = $this->db->prepare($sql);
$query->execute(array(':list_id' => $list_id, ':user_id' => $_SESSION['user_id']));
return $query->fetchAll();
}
//view snippet
echo '<td>' . $value->task_name . '</td><td>' . $priority . '</td><td>';
echo $task_deadline->format('l jS \of F Y h:i:s A');
echo '</td><td>';
echo $overdue_until->format('%R %a day/s, %h hours, %i minutes');
echo '</td><td>' . $status . '</td>';
echo '<td><a href="' . URL . 'task/edit_task/' . $value->list_id . '/' . $value->task_id . '">Edit</td>';
echo '<td><a href="' . URL . 'task/delete_task/' . $value->list_id . '/' . $value->task_id . '">Delete</td>';
echo '<td><a href="' . URL . 'task/completed/' . $value->list_id . '/' . $value->task_id . '">Completed</td>';
echo '</tr>';
What is the best approach in solving this problem? I'm a little bit confused with how should ajax call look like regarding mvc structure and presenting sorted data back to user.
Any help is much appreciated.
For now i have this:
$(document).ready(function(){
$('#selectSortTask').change(function(e){
e.preventDefault();
var sortParam = $('#selectSortTask').val();
$.ajax({
url: $(this).attr('action'),
type: "GET",
data: {sort_task: sortParam},
dataType: 'json',
success: function(data){
alert(data);
},
error: function(error){
alert(error);
}
});
return false;
});
});
Which alerts object Object as error. How to modify this ajax call and model/view/controller to get desired result? Alerts are for debugging purposes.
I'm currently requesting some text via jQuery on a php page. The problem is that the new line symbols \n are displayed in the alert window, and do not get interpreted as new line. I do not escape the string at any time.
In the error: function(..) block of my jQuery request, I get the string returned by php via jqXHR.responseText, here is it's exact value :
Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n
When I do this, new lines DON'T WORK :
alert(jqXHR.responseText);
So to debug, I decided to paste the php response string (which is the previous string) directly in the alert() function, and in this case the new lines WORK :
alert("Some fields are empty!\n$name= \n$schedule= 480;1140;480;1140;480;1140;480;1140;480;1140;480;1140;480;1140\n$free_connection= false\n$free_coffee= false\n$rating= -1\n$lat= 44.715513732021336\n$lng= 1.9775390625\n)");
The string is exactly the same, but yet new lines don't work when I use jqXHR to get it.
Anybody has any clue ?
EDIT: php code that generates the string :
$errorMessage = 'Some fields are empty!' . '\n'
. '$name= ' . $name . '\n'
. '$schedule= ' . $schedule . '\n'
. '$free_connection= ' . $free_connection . '\n'
. '$free_coffee= ' . $free_coffee . '\n'
. '$rating= ' . $rating . '\n'
. '$lat= ' . $lat . '\n'
. '$lng= ' . $lng . '\n';
echo $errorMessage;
You're using the wrong type of quotes. In PHP, escape sequences aren't processed in single quotes, only in double quotes. So it should be:
$errorMessage = 'Some fields are empty!' . "\n"
. '$name= ' . $name . "\n"
. '$schedule= ' . $schedule . "\n"
. '$free_connection= ' . $free_connection . "\n"
. '$free_coffee= ' . $free_coffee . "\n"
. '$rating= ' . $rating . "\n"
. '$lat= ' . $lat . "\n"
. '$lng= ' . $lng . "\n";
echo $errorMessage;
I do not know if I understood well but You can try
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
or
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});