I'm using a script I found for changing a line of text on the go (you click on it and an input shows). It works fine without doing anything to the database but when I add my code for an update, it will update the DB but won't refresh the text after it submits. I'm totally lost now since I've been at it for hours, maybe I'm missing something very basic.
My JS:
$.ajaxSetup({
url: '/ajax/nombreruta.php',
type: 'POST',
async: false,
timeout: 500
});
$('.editable').inlineEdit({
value: $.ajax({ data: { 'action': 'get' } }).responseText,
buttons: '',
cancelOnBlur: true,
save: function(event, data) {
var html = $.ajax({
data: { 'action': 'save', 'value': data.value }
}).responseText;
//alert("id: " + this.id );
return html === 'OK' ? true : false;
}
});
nombreruta.php:
<?php session_start();
$action = isset($_POST) && $_POST['action'] ? $_POST['action'] : 'get';
$value = isset($_POST) && $_POST['value'] ? $_POST['value'] : '';
include $_SERVER['DOCUMENT_ROOT'] ."/util-funciones.php";//for my db functions
$cnx=conectar();
$sel="select * from ruta where id_ruta='".$_SESSION['ruta']."'";
$field=mysql_query($sel, $cnx);
if($row=mysql_fetch_object($field)){
$data = $row->nombre;
}
switch ($action) {
// retrieve data
case 'get':
echo $data;
break;
// save data
case 'save':
if ($value != '') {
$sel="update ruta set nombre='".$value."' where id_ruta=".$_SESSION['ruta'];
mysql_query($sel,$cnx) or die(mysql_error());
$_SESSION['data'] = $value;
echo "OK";
} else {
echo "ERROR: no se han recibido valores.";
}
break;
// no action
default:
echo "ERROR: no se ha especificado accion.";
break;
}
Firebug shows me that after I update my text it returns OK and after I refresh the site it will show the updated text but not before. I started thinking this approach is too much hassle but after so much hours I feel like I'm one step from my solution...
EDIT:
I'm using this plugin: http://yelotofu.com/2009/08/jquery-inline-edit-tutorial/
And my html is just
<span class="editable">Text</span>
Your code works fine for me....
Here's the demo app I put together (asp.net, but basically the same minus the database).
Just to be clear: Press Enter to save. Click off to cancel (since you removed the buttons).
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<script type="text/javascript" src="https://raw.github.com/caphun/jquery.inlineedit/master/jquery.inlineedit.js"></script>
<script type="text/javascript">
$(function(){
$.ajaxSetup({
url: 'Test.ashx?' + window.location.search.substring(1),
type: 'POST',
async: false,
timeout: 500
});
$('.editable').inlineEdit({
value: $.ajax({ data: { 'action': 'get'} }).responseText,
buttons: '',
cancelOnBlur: true,
save: function (event, data) {
var html = $.ajax({
data: { 'action': 'save', 'value': data.value }
}).responseText;
return html === 'OK' ? true : false;
}
});
});
</script>
</head>
<body>
<span class="editable">Test 1</span>
</body>
</html>
C#
public void ProcessRequest(HttpContext context)
{
//Custom Object to Get and Format my Connection String from the URL
QueryStringObjects QSO = new QueryStringObjects(context.Request, "InlineAjaxTest");
//Look for any GET or POST params named 'action'
switch (context.Request.Params["action"])
{
//If 'action' = 'save' then....
case "save":
//Open a connection to my database (This is a custom Database object)
using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
{
//Create a SQL parameter for the value of the text box
DbParameter[] Params = {
new SqlParameter("#val", context.Request.Params["value"])
};
//Execute an Insert or Update
SQL.ExecSQL(#"UPDATE
Test_InlineAJAX
SET
Value = #val
IF ##ROWCOUNT=0
INSERT INTO
Test_InlineAJAX
VALUES
(#val)", Params);
}
//Return OK to the browser
context.Response.Write("OK");
break;
default:
//Open a connection to my database
using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
{
//Get Value from my table (there's only one row so no need to filter)
object obj = SQL.GetScalar("Select Value From Test_InlineAJAX");
//If my value is null return "" if not return the value of the object
context.Response.Write(obj != null ? obj.ToString() : "");
}
break;
}
}
SQL
CREATE TABLE [dbo].[Test_InlineAJAX](
[Value] [varchar](255) NULL
) ON [PRIMARY]
Not sure what else to tell you, but maybe something here will give you an idea...
Related
I know that it may be so tricky!
In detail:
on the blog detailing page(blog-single.php/title) I have a subscription form this subscription form is working fine on another page with the same PHP action file and ajax
and blog-single.php/title is also working fine until I did not submit the form
On this page in the starting, I have bellow query
<?php
$query_head="SELECT * FROM blog_post WHERE friendly_url = '{$_GET['url']}' ";
$result_head= $fetchPostData->runBaseQuery($query_head);
foreach ($result_head as $k0 => $v0)
{
//----- some echo
}
?>
and my subscription form code:
<form action="" method="post" class="subscribe_frm" id="subscribe_frm2">
<input type="email" placeholder="Enter email here" name="email" id="subscribe_eml2">
<button type="button" id="subscribe2">Subscribe</button>
</form>
and ajax code is bellow:
$(document).ready(function() {
$("#subscribe2").click( function() {
subscribe_frm_val2 = false;
/*email validation*/
var emailReg2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($("#subscribe_eml2").val().length <= 0) {
$("#subscribe_eml_Err2").html("Required field");
//console.log("Required");
subscribe_frm_val2 = false;
}
else if(!emailReg2.test($("#subscribe_eml2").val()))
{
$("#subscribe_eml_Err2").html("Enter a valid email");
}
else{
$("#subscribe_eml2").html("");
subscribe_frm_val2 = true;
//console.log("final else");
if(subscribe_frm_val2 == true)
{
console.log("frm true");
var form = $('#subscribe_frm2')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "updation/subscribe_action.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
beforeSend: function(){
// Show image container
$("#submition_loader").show();
//alert ("yyy");
},
success: function (data) {
// console.log();
$(document).ajaxStop(function(){
$("#subscribe_eml_Err2").html(data);
});
},
complete:function(data){
// Hide image container
$("#submition_loader").hide();
}
});
}
else{
alert('Please fill all required field !');
}
}
});
});
When I submit my form above the first query is giving a warning like below:
Warning: Invalid argument supplied for foreach() in D:\xamp\htdocs\my\bootstrapfriendly\category.PHP on line 13
and after warning page doing misbehave
I think the error because of URL passing but I am not sure how to solve it
Please help me with solving it.
Thank's
I got the solution
its very simple just converted my relative URL into an absolute URL
I just created a PHP function for base URL
function base_url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
and then using this base URL function inside script like this
$.ajax({
----
url: "<?php echo base_url()?>/updation/subscribe_action.php",
-----
});
In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_tags').on("change", function(e) {
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag " + e.added.id + "?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.
I'm using Select2 3.3.1, and on an event I get access to the changed elements in my multiple text input that serves as a place to create and delete tags for use on my website. I'm having trouble iterating over the objects returned in the event handler. Specifically, I want to do this because I want access to the individual tags, and the event handler return parameter contains these objects organized by whether the tags were added or removed. So, this is excellent. But everything I've tried fails.
.on("change", function(e) {
alert(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
var added = JSON.stringify({added:e.added});
$.each(added, function(){
$.ajax({
url: '/db-interaction/tags.php',
data: {
'action': 'addtag',
'q': this
},
type: 'get',
success: function(output) {
}
});
});
The command on the second line above
alert(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
displays this string
{"val":["newtag"],"added":{"id":"newtag","count":"0"}} in an alert.
In this case, I had just added the word 'newtag' as a tag. I'd like to be able to iterate over these items in this inner list.
I've also tried a double nested loop, like shown below, but I get the same error. I'm not certain what structure the JSON string requires.
$.each(added, function(){
$.each(this, function(){
The ajax request doesn't seem to execute but I can't locate the bug. The success function doesn't execute and there is an error in the firebug console. It says TypeError: invalid 'in' operand e, pointing to the jquery script. It's my bug, I'm sure. Probably to do with the way I'm handling the event handler parameter 'e', but I don't know what I'm doing wrong.
Here's the tag script. FWIW, the addNewTag() method works in other use cases.
<?php
session_start();
include_once "../inc/constants.inc.php";
include_once "../inc/class.tags.inc.php";
$tags = new Tags();
if (isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn']==1)
{
if(!empty($_POST['action']) )
{
switch($_POST['action'])
{
case 'addtag':
echo $tags->addNewTag();
break;
case 'removetag':
echo $tags->removeTag();
break;
case 'getalltags':
echo $tags->getAllTags();
default:
break;
}
}
else if(!empty($_GET['action']))
{
switch($_GET['action'])
{
case 'addtag':
echo $tags->addNewTag();
break;
case 'removetag':
echo $tags->removeTag();
break;
case 'getalltags':
echo $tags->getAllTags();
default:
break;
}
}
}
else
{
header("Location: /");
exit;
}
?>
And the addNewTag() method, which works well in other cases:
/**
* Adds a new tag, increment uses_count if it already exists
*
*
*/
public function addNewTag($name=NULL)
{
if ($name === NULL){
if (isset($_POST['q']) )
$u = $_POST['q'];
else if (isset($_GET['q']))
$u = $_GET['q'];
}
else{
$u = $name;
}
$sql = "INSERT INTO tags(name,uses_count) VALUES (:term,1)
ON DUPLICATE KEY UPDATE uses_count=uses_count+1;";
if($stmt = $this->_db->prepare($sql))
{
$stmt->bindParam(":term", $u, PDO::PARAM_STR);
$stmt->execute();
$stmt->closeCursor();
}
Can anyone help me out? If it would be of use, I could describe the other things I've tried and why they haven't worked.
Try something like
$.each(e.added, function(key, value){
alert(key + ' - ' + value )
$.ajax({
url: '/db-interaction/tags.php',
data: {
'action': 'addtag',
'q': this
},
type: 'get',
success: function(output) {
}
});
});
Demo: Fiddle
this is my javascript code ...i have written a function in my controller in which if false is return then i am echoing the 'userNo' other wise echo the json .. here is my javascript in which only else part is working not if part ... i have checked in firebug also .. i am getting a response "userNo" but dont know why it is not running the first part
<script type="text/javascript">
$(document).ready(function(){
$('#hide').hide();
$('#bill_no').blur(function(){
if( $('#bill_no').val().length >= 3 )
{
var bill_no = $('#bill_no').val();
getResult(bill_no);
}
return false;
})
function getResult(billno){
var baseurl = $('.hiddenUrl').val();
$('.check').addClass('preloader');
$.ajax({
url : baseurl + 'returnFromCustomer_Controller/checkBillNo/' + billno,
cache : false,
dataType: 'json',
success : function(response){
$('.check').removeClass('preloader');
if (response == "userNo") //this part is not working
alert("true");
else
$('.check').removeClass('userNo').addClass('userOk');
// $(".text").html(response.result);
$('#hide').show();
$(".text1").html(response.result1);
$(".text2").html(response.result2);
$(".text3").html(response.result3);
}
})
}
})
</script>
my Controller
function checkBillNo($billno)
{
$this->load->model('returnModel');
$query = $this->returnModel->checkBillNo($billno);
//$billno = $this->uri->segment(3);
$billno_results = $this->returnModel->sale($billno);
if (!$billno_results){
echo "userNo";
}else{
echo json_encode($billno_results);
}
}
Instead of echo "userNO", try to use it:
echo json_encode(array('return' => 'userNo'));
... and in your JS, use this:
if (response.return == "userNo") { // ...
This is getting really confusing now... Updating a mysql database without leaving the page.... I have 3 bits of code. The javascript in the head tags, the action button in the body and the code to be performed on another page. Here are the three sections:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
function addItemToUsersList(itemId)
{
$.ajax({
'url': 'member-bucketadd-exec.php',
'type': 'GET',
'dataType': 'json',
'data': {itemid: itemId},
'success': function(data)
{
if(data.status)
{
if(data.added)
{
$("span#success"+itemId).attr("innerHTML","Item added to your personal list");
alert("Item added to your list!");
}
else
{
$("span#success"+itemId).attr("innerHTML","This item is already on your list");
alert("This item is already on your list!");
}
}
},
beforeSend: function()
{
$("span#success"+itemId).attr("innerHTML","Adding item to your bucketlist...");
}
,'error': function(data)
{
// what happens if the request fails.
$("span#success"+itemId).attr("innerHTML","An error occureed");
alert("On your list!");
}
});
}
</script>
The action button ...
<a onclick="addItemToUsersList(<?php echo $itemid ; ?>)">Add<img src='images/plus-green.png' /> </a>
And the code that is run on the other url...
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$bucketlist=MYSQL_QUERY( "SELECT * FROM membersbuckets where userid = $userid AND bucketid = $bucketid")
or die(mysql_error());
$bucketlist=mysql_fetch_array($bucketlist) ;
if($bucketlist < 1)
{
mysql_query("INSERT INTO membersbuckets (memberbucketid, userid, bucketid, complete)
VALUES ('', '$userid', '$bucketid', '0')");
return json_encode(array("status" => true, "added" => true));
}
else
{
return json_encode(array("status" => true, "added" => false));
}
?>
It doesn't matter if the item is already on the list (like it is supposed to check bucket<1), or not on the list I always get the alert("On your list!"); , and also the link / the activation button bit, when I hove over it I don't get the hand/finger i just get a text cursor!!
I have never used jquery, or ajax before this little project so have no idea what to look for to see what is out of place. I have downloaded firebug and tested it with that but I can't see any problem/s. Can anyone help?
Thank you anyone and everyone in advance! hope you can help.
check php manual for mysql_fetch_array your code in
$bucketlist = mysql_fetch_array($bucketlist)
will be FALSE with no rows.
To avoid the href="#" causing the page to jump to the top, your onclick function needs to return false. This tells the browser not to continue with the standard href action. You can do this in several ways, including adding return false; to the end of addItemToUsersList(), or even directly in the onclick code, like so:
onclick="addItemToUsersList(<?php echo $itemid ; ?>); return false;"
a) Check your .ajax request:
<script type="text/javascript" src="./jquery-1.4.2.min.js"></script>
<script type="text/javascript">
function addItemToUsersList(itemId) {
$.ajax({
'url': 'http://localhost/test/add_member.php', /*test6ed in my PC*/
'type': 'GET', 'dataType': 'json',
'data': {itemid: itemid, userid: 1}, /*Added itemid, userid */
/*Params in 'success function*/
'success': function(data, textStatus, XMLHttpRequest){
if(data.status) {
if(data.added) $("#success").attr("innerHTML","Item added");
else $("#success").attr("innerHTML","Already on your list");
}
},
beforeSend: function(XMLHttpRequest){
$("#success").attr("innerHTML","Adding item ...");
},
'error': function(XMLHttpRequest, textStatus, errorThrown) {
$("#success").attr("innerHTML","An error occureed");
alert("On your list!");
}
});
}
</script>
Add
<span id="success"></span>
2) Your PHP server-side code must receive same params in your .ajax request and
returning echoing instead a return sentence
$userid = $_GET['userid' ] ? $_GET['userid']: 0 ;
$bucketid = $_GET['itemid'] ? $_GET['itemid']: 0 ;
if(!$bucketid || !$userid )
echo json_encode( array("status" => false, "added" => false));
$sql = "SELECT * FROM membersbuckets where userid = $userid AND bucketid = $bucketid";
$bucketlist = mysql_query( $sql ) or die(mysql_error());
$bucketlist = mysql_fetch_array($bucketlist) ; //return FALSE in no rows
if($bucketlist){
$insert_sql = "INSERT INTO
membersbuckets
(memberbucketid, userid, bucketid, complete)
VALUES ('', '$userid', '$bucketid', '0')" ;
mysql_query($insert_sql);
//return with an echo
echo json_encode(array("status" => true, "added" => true));
}else {
echo json_encode(array("status" => true, "added" => false));
}
The hand/finger does not appear
because it is not defined to appear by default for anchors without the href attribute. Just add href="#" to your anchor or else assign cursor: pointer style to your anchor and it will point.
Returning error result
Like Thau has pointed out, in your ajax request processing code code, in the query you are using two variables $_GET['userid'] and $_GET['itemid'] but you are passing only itemid in the request. Is that the reason of the error? Did you find out?