How to use x-editable to submit a form - php

I'm trying to submit my data to my php function (My app is based on an MVC framework), but all it does is erasing my data.
Here is my code in php that i want to replace by an inline x-editable:
<form method="post" action="<?php echo URL; ?>mylist/editSave/<?php echo $this->oneList->list_id; ?>">
<label>Change my list name: </label>
<input type="text" name="list_name" value="<?php echo $this->oneList->list_name; ?>" />
<input type="submit" value='Change' />
</form>
I have tried to do this:
echo '<td>Edit</td>';
But it doesn't work. What i want to do, is send $value->list_id and my new $value->list_name which has to be received by my php function URL/mylist/editSave/
Please help!
Thank you :)

I use success method with own function formatXEditable and you must always disable default display function.
function formatXEditable($item, $val){
$val = $val.replace(/<br\s*\/?>/mg,"\n");
$($item).text($val);
$($item).on('shown', function(e, editable) {
editable.input.$input.val($val);
});
}
$('#identifier').editable({
...
display: function(value, response) {
return false; //disable this method (success displays value information)
},
success: function(response, value) {
if(response.status == 'error') return response.msg; //msg will be shown in editable form
formatXEditable($('#identifier'), response.identifier);
$('#pagesForm-identifier').val(response.identifier);
},
error: function(errors) { }
});
Hope it helps.

Related

Try to using ajax form instead of form action (solve)

I would like to improve user experience at my website. So I try to change the form action ajax, and I has been try some tutorial but I still getting stuck.
I am using a php forum program/source code call !Discuz and it was from China. Below is my coding now.
In html.
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn">submit</button>
</form>
in PHP, file name plugin.php
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
showmessage('message here','redirectlink');//this is !Discuz program function and it is fine.
}
}
?>
The above script is working fine while using form action, and redirect to my output page. If I would like to change to ajax, how do I adjust the below source code?
<script type="text/javascript">
function login() {
$.ajax({
type: "POST",
dataType: "json",//? is it can use json? since my form data can get as array
url: "plugin.php?id=cc&do=shop" ,//url
data: $('#jnfarm_pop').serialize(),
success: function (result) {
console.log(result);
if (result.resultCode == 200) {
alert("SUCCESS");
}
;
},
error : function() {
alert("ERROR");
}
});
}
</script>
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login()">submit</button>
</form>
And is it have to adjust the plugin.php source code?
Updated, below is work for me, thanks fayis003.
html change the <script></script>
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
alert(result.final);//alert message here
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
PHP
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
$final = 'message here';
echo json_encode(['final' => $final]);
}
}
?>
You can not initiate a direct browser redirect using server-side code on ajax request like you do with synchronous requests. instead, you have to return a URL to which you want to get redirected to and then do something like location.href = result.link in the result callback.
for ajax request, the simplest option is using as follows
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
let final = result.final;
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
now in the server-side code instead of creating a redirect from PHP return something like
return json_encode(['link' => 'somlink']);
of just return success message as usual.

Simple Validation with PHP using AJAX and JQuery

I am new to AJAX, and I want to learn how to validate a form. Suppose, I have a form with two input fields. When I click in submit I want to check the page with a php script. When the validation is succesfull I want to redirect to the action="submitForm.php". When one or more fields are not valid according to the validation.php I want to stay on the page and gives a error message next to the field.
What is the best way to do that?
<html>
<head>
</head>
<body>
<form action="submitForm.php" action="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
</html>
submitForm.php:
<?php
echo $_POST["username"];
echo "<br />";
echo $_POST["password"];
?>
In order to process the fields before actually submitting the form, you can catch its submit event:
<form action="submitForm.php" action="post" onsubmit="return MyValidation()">
Then, in your javascript:
function MyValidation() {
var valid = false;
$.ajax({
type: "POST",
url: "validation.php",
async: false,
data: { name: $('#username').val(), password : $('#password').val() }
})
.done(function( data ) {
if(data == 'true') {
valid = true;
}
});
// not valid, return false and show some hidden message
return valid;
}
(you need to add an ID to the <input> fields in order for the jquery selectors to work...)
There is two solutions who might help you
http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php
http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59

$.post with serialize doesn't send post variables and values

I want to post data with jquery to process.php, and return everything what happens in the process.php file.
I already managed to load the file with ajax. if I type
echo "Hello world!";
it does return Hello world! but it does not return the echoes where I use $_POST.
The form
<form class="calc" method="POST" action="process.php">
<input id="calc-average" type="text" name="calc-average" placeholder="Goal"/>
<input id="calc-weight" type="text" name="calc-weight" placeholder="Weight"/>
<input id="calc-calculate" type="hidden" name="calc-calculate" value="1" />
<input type="submit" class="btn btn-primary calc-submit" value="Calculate">
</form>
The script
$(".calc").submit(function(event) {
event.preventDefault();
$.post( 'process.php', $(".calc").serialize(),
function( data ) {
$(".result").append(data);
}
);
});
Process.php
if(isset($_POST["calc-calculate"])&&isset($_POST["calc-weight"])&&isset($_POST["calc-average"])){
if(!$_POST["calc-calculate"]==""&&!$_POST["calc-weight"]==""&&!$_POST["calc-average"]==""){
if($_POST["calc-calculate"]==$subjectid){
$a = $_POST["calc-weight"];
$y = $_POST["calc-average"];
$q = $weights;
$z = $average;
$tobe = (-($a*$y+$q*$y-$q*$z)/$a)*-1;
if($tobe>10 or $tobe<0){
echo " | Not possible yet";
}else{
echo " | The grade you need is: " . round($tobe,1);
}
}
}
}
echo "Hello wordl!";
If I remove the if statements it returns that they are unidentified.
So does anyone know how I can get this to work?
Thanks!
hi can you please try this in your jquery code
$(".calc").submit(function(event) {
event.preventDefault();
$.post( 'process.php', $(".calc :input").serialize(),
function( data ) {
$(".result").append(data);
}
);
});
This code is working fine for me.
try adding return false after post request.
$(".calc").submit(function(event) {
event.preventDefault();
$.post( 'process.php', $(".calc").serialize(),
function( data ) {
$(".result").append(data);
}
);
return false;
});
I already had the same problem. My code had a duplicate "id" on the page. That was my issue.
Please, make sure you have an exclusive id or class "calc" in the form to "serialize" command call the correct element.

jQuery Trigger Form Submit on Page Load if GET Parameters are set

I am trying to submit the form on my page upon page load if there are certain parameters set in the query string. The form submits using ajax and works fine and the pre-population of the form fields from the query string is fine aswell but no matter what I try to automatically submit the form, I end up in an infinite loop of page loads.
PHP
// top of page
<?php
if (isset($_GET['postcode'])) {
$postcode = trim($_GET['postcode']);
} else {
$postcode = '';
}
if (isset($_GET['phone_num'])) {
$phone_num = trim($_GET['phone_num']);
} else {
$phone_num = '';
}
?>
jQuery
/*
// causing infinite page loads
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
return false;
}
*/
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<button type="submit" class="btn btn-primary" id="check">Check</button>
</form>
Instead of using a click function for the auto form submit I've tried doing the same $('form').submit but I get the same problem. I was expecting the page to function as normal so that if the parameters were set then the ajax call would automatically be made but this is obviously not the case.
You're exiting your code before you bind the submit event. Remove the return false in your if statement, then move the if statement to after the submit binding.
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
//return false;
}
Try something like this:
if($('input[name="phone_num"]').val() && $('input[name="postcode"]').val()) {
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
}).submit();
}
use this line on your code.
$('form').trigger("submit");
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<input type="button" class="btn btn-primary" id="check">Check</button>
</form>
jQuery
$('#check').click(function(e) {
e.preventDefault();
$.get("script.php", $('form').serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
}
When using a submit button, you are performing the default event (submitting the form) as well as processing the handler of the .click() event. To avoid this, use e.preventDefault(); causing only the scripted portion of the event to process.

jQuery: form returned on "success" needs re-binding

a quick question. I am using the jQuery.forms.js plug-in.
I have a form that posts to a php page and returns data with jSon.
The data that is returned is code for a new form (it replaces the form that was used to post the information). The new form is not bound to any jQuery functions, as it was not around when the page loaded.
So, how can I get ajax form to recognize the new form, so that if i need to use the form a second time, it is also utilizing the jQuery function?
// jQuery for submitting info to php doc and, on success, replacing the form
$(document).ready(function() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
});
<!-- /////////////////////// POST ONLINE /////////////////////// -->
<div id='onlineStatus<?php echo $b_id ?>' class='postOnline'>
<form name="postOnline" id="postOnline<?php echo $b_id ?>" action="postOnline.php" method="post">
<input type="hidden" value="<?php echo $b_id ?>" name="b" />
<input type="hidden" value="1" name="p" />
<input type="submit" class="button" value="Post Online" />
</form>
</div>
<!-- /////////////////////// POST ONLINE /////////////////////// -->
// ... code for entering data into database and then...
$result = mysql_query( $sql );
if($result) {
if($show == '1'){$val = 'remove from online'; $num='0';}
if($show == '0'){$val = 'show online'; $num='1';}
$return = "
<form name='postOnline' id='postOnline$id' action='postOnline.php' method='post'>
<input type='hidden' value='$b_id' name='b' />
<input type='hidden' value='$num' name='p' />
<input type='submit' class='button' value='$val' />
</form>
";
print json_encode(array("rid" => $id, "formed" => $return));
}
?>
The easiest solution to this is not using jQuery's form plugin and doing it manually, which is really not very difficult:
$(document).ready(function() {
jQuery('form[id*=postOnline]').live('submit', function() {
var formdata = $(this).serialize();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
dataType: 'json',
data: formdata,
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
return false;
});
});
Now since you are using jQuery's new (1.3) live functionality, any forms you add that match the form[id*=postOnline] selector will still be wired with this event.
Alternatively, you can open up the jquery forms code and find wherever it does its binding and try to modify it so that it uses it live. Even another alternative would be to encompass the wiring in a function, and call it at the end of your success function, like so:
function bindForm() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
bindForm();
}
});
}
$(document).ready(function() {
bindForm();
});
I don't think it is very neat, but it should work.
You need to rebind the event handlers after the ajax call. I heard about a new feature in the newer version of jquery called live events, that would make this unnecessary though.
If for whatever reason you're stuck with a pre-1.3 version of jQuery, use the "livequery" plugin.

Categories