can jQuery or plain JavaScript check how the value of input field was changed? Maybe something similar to that:
$('input').change(function(e){
e.preventDefault();
console.log(e.changedFunction.name);
});
I know given code doesn't work and doesn't do what I want. But is this even possible somehow?
Why do I need that? I have a dialog box where I have multiple forms (each form changes one thing). When I submit form, the value resets back to value which was there previously. e.g. In the form there's a word 'Hello', when I change it to 'Hello, World!', it successfully sends the data to $.post, but then resets the value to 'Hello'. I can't seem to find any function, neither php, nor javascript that changes the input. That's why I need to check what or who changes my input value back.
EDIT:
Including sample code.
editblock.php
} else if ($_POST['what'] == 'email') {
$sql = mysql_query("SELECT id, email, loggedin FROM users WHERE id = " . mres($_POST['id']) . " LIMIT 1");
$edit = mysql_fetch_array($sql);
$output .= '<div id="block-' . $_POST['what'] . '"><form method="post" id="form-' . $_POST['what'] . '">';
$output .= '<input type="hidden" name="id" value="' . mres($_POST['id']) .'" />';
$output .= '<input type="text" name="value" value="' . $edit['email'] .'" /> ';
$output .= '<input type="hidden" name="what" value="' . mres($_POST['what']) .'" />';
$output .= '<input type="submit" name="submit" value="OK" />';
$output .= '</form></div>';
$output .= '<script>
$("#form-' . $_POST['what'] . '").submit(function(event) {
event.preventDefault();
var $form = $( this ),
doval = $form.find( "input[name=\"value\"]" ).val(),
doid = $form.find( "input[name=\"id\"]" ).val(),
dowhat = $form.find( "input[name=\"what\"]" ).val();
$.post("/pages/profilis/doedit.php", { do: doval, id: doid, what: dowhat },
function( data ) {
$("#block-' . $_POST['what'] . '").empty().append( data );
$form.find("input[name=\"value\"]").val(doval);
}
);
});
</script>
';
}
doedit.php
else if ($_POST['what'] == 'email') {
if (empty($_POST['do'])) {
$error[] = 'err';
} else {
if ( ! preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $_POST['do'])) {
$error[] = "err";
}
$sql = mysql_query("SELECT `id` FROM `users` WHERE `email` = '" . mres($_POST['do']) . "' LIMIT 1");
if (mysql_num_rows($sql) == 1) {
$error[] = "err";
}
if ($edit['loggedin'] > 0) {
$error[] = "err";
}
if (sizeof($error) >= 1) {
echo join($error, '<br/>');
} else {
$sql = mysql_query("UPDATE users SET
email = '" . mres($_POST['do']) . "'
WHERE id = " .(int)$edit['id'] . "
LIMIT 1");
if ($sql) {
echo 'OK';
$logmsg = 'Changed email';
} else {
echo 'Error';
}
}
}
}
PHP function mres() escapes all the characters (for database injection protection - not really important here).
According to the situation which you explained. I would prefer you to use jqueryajax
in this Once the Post function is done you can change the value with the changed value
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg ); // portion where you can change the field value to the updated one.
});
Thanks and Regards,
Philemon Philip Kunjumon
Related
I checked out this post but no luck :
PHP - concatenate or directly insert variables in string
The suspect in question: showUser(3, change, " . $name . ");'> $name breaks the code; the second $name does work. The variable does not get passed to the function.
I have been testing for hours to get this to work! It seems like it should work.
I tried checking other places in the application to see what the problem could be and this seems to be the culprit.
<?php
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = "<p onClick='DoIt(); showUser(3, change, " . $name . ");'>" . $name . "</p>";
} else {
$hint .= "\n" . "$name";
}
}
}
?>
JavaScript probably is requiring $name to be quoted.
$hint = "<p onClick='DoIt(); showUser(3, change, \"" . $name . "\");'>" . $name . "</p>";
Escaping the quotes like this will cause them to appear in the JS function call.
Quotes are often a thorny problem when mixing PHP, JavaScript and HTML on one line.
You can quote your variable like this
if ($q !== "") {
$q = strtolower($q);
$len = strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$name = "'" . $name . "'";
$hint = '<p onClick="DoIt(); showUser(3, change, ' . $name . ');">' . $name . '</p>';
} else {
$hint .= "\n" . "$name";
}
}
}
}
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 just wrote my first Ajax request but it doesn't work. It needs to update when a new value in the drop-down list is selected.
This is my javascript code:
$(document).ready(function() {
function ajaxLoaded(response) {
$('#performanceResults').html(response);
}
function doRequest() {
$.ajax({
url: "results.php",
type: 'POST',
success: ajaxLoaded
});
}
$('#performance').change(doRequest);
});
and this is how I retrieve the q part (which doesn't work):
public function getResults() {
$intCase = intval ( $_POST ['q'] );
var_dump ( $intCase );
if ($intCase == 1 or $intCase == 2 ) {
if ($intCase == 1) {
$strSql = 'select bidder_id, won, lost, fillrate, costs, cost_auction from result_bidder where tagload = ( select max(tagload) from result_bidder) order by cost_auction asc limit 1';
}
if ($intCase == 2) {
$strSql = 'select bidder_id, won, lost, fillrate, costs, cost_auction from result_bidder where tagload = ( select max( tagload ) from result_bidder ) order by fillrate asc limit 1';
}
$arrBestPerformer = $objDatabase->queryresult ( $strSql );
echo "<table border='1'>
<tr>
<th>bidder_id</th>
<th>won</th>
<th>lost</th>
<th>fillrate</th>
<th>costs</th>
<th>cost_auction</th>
</tr>";
while ( $row = mysqli_fetch_array ( $arrBestPerformer ) ) {
echo "<tr>";
echo "<td>" . $row ['bidder_id'] . "</td>";
echo "<td>" . $row ['won'] . "</td>";
echo "<td>" . $row ['lost'] . "</td>";
echo "<td>" . $row ['fillrate'] . "</td>";
echo "<td>" . $row ['costs'] . "</td>";
echo "<td>" . $row ['cost_auction'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
}
My Form:
public function SelectPerformanceIndicator() {
$this->getResults ();
$str = '<form >';
$str .= 'Select your performance indicator<br>';
$str .= '<select id = "performance">';
$str .= '<option value = "">Select Performance Indicator</option>';
$str .= '<option value = "1">Cost per auction </option>';
$str .= '<option value = "2">Fillrate </option>';
$str .= '</select>';
$str .= '</form>';
$str .= '<br>';
$str .= '<div id="performanceResults">';
return $str;
}
Your problem is that your POST data string is invalid.
xmlhttp.send("q ="+ str);
Should be
xmlhttp.send("q="+ str);
Without the space between q and =.
And you missed to send the header to tell PHP that it should map the Data sent with the request to the $_POST var.
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
So your correct function would be:
function showUser(str) {
if (str=="") {
document.getElementById("performance").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("performance").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","results.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+ str);
}
But again: use jQuery to make your AJAX requests. If you use jQuery you don't have to struggle with errors like this anymore.
You have added space in query string, "q =" this is not behaving as q key in $_POST variable,
remove space between key and =
xmlhttp.send("q ="+ str);
to
xmlhttp.send("q="+ str);
Update Answer: AJax POST will be worked when request have Content-type: application/x-www-form-urlencoded header.
please add Header before send method
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
OR
you can send request by GET method without header
I'm not familiar with javascript and I'm sure the problem I have has a simple solution, I just need some direction.
The script below wasn't written by me, it's an URL shortening script. When the user inputs the long URL and presses submit the script creates a random short URL and displays the short URL in the input field. What I want to know is which part of the javascript controls the display of the short URL in the input? I want to change what is displayed after the URL is shortened.
page.php
<script src="script.js" type="text/javascript"></script>
<form action="#" id="form-add-url" class="profile" method="post" onsubmit="return add_url()">
<input type="text" id="urls-url" name="url" class="widefat-main" placeholder="Paste a link" tabindex="1" title="URL">
<input type="hidden" name="action" value="add_url">
<button type="submit" class="button-main" tabindex="3">Submit</button>
</form>
script.js
function add_url() {
jQuery("#front-url .loading-dark").fadeIn(200);
jQuery.post(url_base+"ajax.php", jQuery("#form-add-url").serialize(),
function(return_data) {
jQuery("#front-url .loading-dark").fadeOut(200);
data = jQuery.parseJSON(return_data);
var status = data.status;
if (status == "OK") {
jQuery("#urls-url").val(data.url);
} else if (status == "OK2") {
jQuery("#search_query").val("");
jQuery("#page_number").val("");
reload_urls("", 1);
jQuery("#urls-url").val(data.url);
} else if (status == "ERROR") {
show_notification("error", data.message, 3000);
} else {
show_notification("error", "Internal error. Please contact administrator.", 3000);
}
}
);
return false;
}
My PHP:
case 'add_url':
if ($options['only_registered'] == 'yes' && !$active_user)
{
$return_object = new stdClass();
$return_object->message = 'URL shortening is available for registerd users only.';
$return_object->status = 'ERROR';
echo json_encode($return_object);
exit;
}
$url = trim(stripslashes($_POST['url']));
if (substr(strtolower($url) , 0, 7) != "http://" && substr(strtolower($url) , 0, 8) != "https://") $url = 'http://' . $url;
$error = '';
if ($url == '')
{
$error = 'Hey, seems you forgot to paste a link.';
}
else
if (!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url))
{
$error = 'Are you sure you submitted the correct URL?';
}
else
if (sizeof($url) > 255)
{
$error = 'Hey, seems URL is too long.';
}
if (!empty($error))
{
$return_object = new stdClass();
$return_object->message = $error;
$return_object->status = 'ERROR';
echo json_encode($return_object);
exit;
}
if (substr(strtolower($url) , 0, strlen($url_base)) == strtolower($url_base))
{
$return_object = new stdClass();
$return_object->message = 'Hey. Seems this URL is short enough. ;-)';
$return_object->status = 'ERROR';
echo json_encode($return_object);
exit;
}
if ($active_user) $user_id = $active_user['id'];
else $user_id = 0;
$url_details = $icdb->get_row("SELECT * FROM " . $icdb->prefix . "urls WHERE url = '" . mysql_real_escape_string($url) . "' AND deleted = '0' AND user_id = '" . $user_id . "'");
if ($url_details)
{
$icdb->query("UPDATE " . $icdb->prefix . "urls SET created = '" . time() . "' WHERE id = '" . $url_details['id'] . "'");
$url_code = $url_details['url_code'];
}
else
{
$icdb->query("INSERT INTO " . $icdb->prefix . "urls (user_id, url, url_code, redirects, created, blocked, deleted, short) VALUES ('" . $user_id . "', '" . mysql_real_escape_string($url) . "', '', '0', '" . time() . "', '0', '0', '" . $_POST[short] . "')");
$url_code = url_code($icdb->insert_id);
$icdb->query("UPDATE " . $icdb->prefix . "urls SET url_code = '" . $url_code . "' WHERE id = '" . $icdb->insert_id . "'");
}
$htaccess = url_rewrite();
$return_object = new stdClass();
if ($active_user)
{
$return_object->status = 'OK2';
}
else $return_object->status = 'OK';
$return_object->url = $url_base . ($htaccess ? '' : '?u=') . $url_code;
echo json_encode($return_object);
exit;
break;
check this out
function add_url() {
// fading effect
jQuery("#front-url .loading-dark").fadeIn(200);
// posting with ajax post method
jQuery.post(url_base+"ajax.php", jQuery("#form-add-url").serialize(),
// success function after request complete
function(return_data) {
// applying fade out effect
jQuery("#front-url .loading-dark").fadeOut(200);
//parsing response string from server into javascript object
data = jQuery.parseJSON(return_data);
// getting status value
var status = data.status;
if (status == "OK") {
//putting [data.url] value in html element with id [urls-url]
//data.url => url value from server
jQuery("#urls-url").val(data.url);
} else if (status == "OK2") {
jQuery("#search_query").val("");
jQuery("#page_number").val("");
reload_urls("", 1);
jQuery("#urls-url").val(data.url);
} else if (status == "ERROR") {
show_notification("error", data.message, 3000);
} else {
show_notification("error", "Internal error. Please contact administrator.", 3000);
}
}
);
return false;
}
jQuery("#urls-url").val(data.url);
In the response of the post to url_base+"ajax.php" a JSON string is returned. The URL part of this response (data.url) is used as a value for you input (#urls-url).
I believe this is what you are after:
jQuery("#urls-url").val(data.url);
The .val() method is used to get and set the values of form elements such as input, select and textarea.
Thanks for your input guys! Very much appreciated.
The 4th last line in ajax.php (111.118.164.146/~jodeleep/ajax.php.html) was what I need to look for.
So I have a working ajax/jquery dropdown/list that populates results from the database depending on the users input.
Basically is populates a <li> for every resu1lt in the database, and makes it into a link that can then go to that persons profile page.
I have tested the code and it works perfectly on the test page, but as soon as it has other content behind it, the links don't work anymore. How can I fix this?
here is the code:
custom.js:
/* JS File */
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
search.php (the file that searches, not the page that is displayed to the user):
/************************************************
Search Functionality
************************************************/
// Define Output HTML Formating
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = 'SELECT * FROM users WHERE username LIKE "%'.$search_string.'%" OR name LIKE "%'.$search_string.'%"';
// Do Search
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['function']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['name'] . " " . $result['surname'] . " (" . $result['username'] . ")");
$display_url = 'timeline.php?user='.$result['username'];
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
And the search form itself:
<!-- Main Input -->
<input type="text" id="search" autocomplete="off">
<!-- Show Results -->
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
All this code can be found here: live search with ajax, php and mysql
credits to him.
thanks for the help in advance!
I got it working thanks to Enijar.
Set the positioning to absolute and the z-index to 99.