can anyone fix this. jQuery $.post - javascript

i have a form like this (already add jquery latest)
echo '<form name="chat" id="chat" action="/pages/guicsdl.php" method="post">';
echo bbcode::auto_bb('chat', 'text');
echo '<textarea rows="3" name="text" id="text"></textarea><br/>';
echo '<input type="hidden" name="trave" value="'.$trave.'" /><input type="submit" name="submit" value="Gửi" /></form>';
and the js
$(document).ready(function() {
$("chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
and the file guicsdl.php
if(isset($_POST['submit'])) {
$noidung = functions::check($_POST['text']);
mysql_query("INSERT INTO `status` SET `user_id`='".$user_id."', `text`='".$noidung."', `time`='".time()."'");
mysql_query("UPDATE `users` SET `tongchat`= tongchat+1 WHERE id = '".$user_id."' ");
$trave = isset($_POST['trave']) ? base64_decode($_POST['trave']) : '';
header("Location: $trave");
}
i only want when i submit the form, the page doesn't refresh, the data insert to database. can any one help me fix? pls, and thanks. sorry for bad english.

You have to add return false; so that the browser 'understands' that it should not submit the form directly.
$(document).ready(function(){
$("#chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
return false;
});
});
Another way (which I myself prefer) is to tell the event to not do it's default behavior.
$(document).ready(function(){
$("#chat").submit(function(ev){ // note the extra parameter
ev.preventDefault();
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
Wilmer also noticed that you had forgotten to put a # for the jQuery identifier when selecting the chat form.

Related

Run a JavaScript function based off of PHP validation and form submit

I already have a php validation and form setup with PHP. So if someone forgets a username, the validation will add to the errors array and display it on the page when submitted. Now, instead of displaying some text for the error (Username can't be blank) I just want the input box highlighted in red, which I know needs JavaScript. I am having some trouble running this JavaScript function properly. Below is the code.
JavaScript:
<script type="text/javascript">
function myFunction() {
document.getElementById("usernameformitem").className = "formerror";
}
</script>
PHP:
if (isset($_POST['submit'])) {
$required_fields = array("username");
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
//the $value is now the un/pw without whitespaces
$value = trim($_POST[$field]);
//if the value does not exist/is blank
if (!has_presence($value)) {
//remember field is really un or pw
$errors[$field] = fieldname_as_text($field) . " can't be blank";
echo "<script>";
echo "myFunction();";
echo "</script>";
}
}
}
validate_presences($required_fields);
HTML:
<form action="new_user4.php" method="post">
<div id="usernameformitem">
<p>Username:
<input type="text" name="username" value="" />
</p>
</div>
<input type="submit" name="submit" value="Create User" />
</form>
Thanks in advance!
make sure the div exists before calling the function, for example echo the script after the div or use
window.onload=function() { if (myFunction) myFunction(); }
FIDDLE
But why even submit the form?
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
if (this.username.value="") {
myFunction();
return false; // stop submission
}
return true;
}
<?PHP if (!has_presence($value)) { .... ?>
if (myFunction) myFunction();
<?PHP } ?>
}
PS: NEVER call a form element name="submit" - it will block you from ever submitting by script
Right under the if submit area of php, I echoed
echo "<script type=\"text/javascript\">";
echo "function myFunction() {";
echo "document.getElementById(\"usernameformitem\").className = \"formerror2\";";
echo "}";
echo "</script>";
Then, in the HTML under the div that I am trying to affect, I entered:
<script>
window.onload=function() { if (myFunction) myFunction(); }
</script>
Only problem I ran into was that style had to be internally set. I'm not sure how to have it pull from my external css yet.
Big thanks to mplungjan!

How to check if username exists without refreshing page using wordpress

I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>
use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**

Confirm delete with php var

A sample of my code :
<form action="test.php" method="GET">
<input type="text" name="Delete_This" value="<?php if (isset($_GET['Delete_This'])) echo $_GET['Delete_This']?>">
<input type="submit" name="Deleting" value="Delete this">
<?php
// If the deleting button is pressed
if (isset($_GET['Deleting']))
{
$DeleteThis = $_GET['Delete_This'];
?>
<script type='text/javascript'>
if (confirm('Are you sure you want to delete <?php echo $DeleteThis ?> ?'))
alert('<?php echo $DeleteThis ?> deleted');
<?php
$sql_delete="DELETE FROM table WHERE Name like '".$DeleteThis ."'";
mysqli_query($db,$sql_delete);
?>
else
alert('Not deleted');
</script>
<?php } ?>
</form>
The confirm box opens proprely. My problem is that wether i click on OK or Cancel, $sql_delet is executed.
I know I should use Javascript on the top <head> of my document but if i do that I can't execute the Delete query and I must warn the user what he's going to delete. {$DeleteThis} works fine. I also used the onclick function on the input but I can't use {$DeleteThis}.
To synthesize : I want, if the confirm box is canceled, the query not to be executed and I must use php variable in the confirm and alert.
You may want to read up on the difference between server-side and client-side languages.
Everything you put in php code is executed before the html and javascript code is even sent to the user's browser.
In contrast, everything you put in javascript code can no longer affect the php code.
So what happens in your code is that php first checks whether there is a $_GET['Deleting'] variable. If there is one, it finds some html and javascript, and remembers that it should output that to the browser later. It then executes the delete query. And once it's done, it sends the following javascript (plus any surrounding html) to the browser:
<script type='text/javascript'>
if (confirm('Are you sure you want to delete your-deletion-value ? \nHey'))
alert('your-deletion-value deleted');
else
alert('Not deleted');
</script>
So hopefully, you see the disconnection between the two.
you could put confirmation in
if (isset($_GET['Deleting']))
{
$DeleteThis = $_GET['Delete_This'];
if(!isset($_GET['ConfirmDelete'])//if confirmation has not been initiated yet
{
?>
<script type='text/javascript'>
function deleteOrNot(formEle)
{
if (confirm('Are you sure you want to delete <?php echo $DeleteThis ?> ?'))
window.location += '&ConfirmDelete=yes';//casue a postback with ConfirmDelete attribute in $_GET
else
alert('Not deleted');
</script>
<?php }
else if($_GET['ConfirmDelete'] == 'yes')
{
$sql_delete="DELETE FROM table WHERE Name like '".$DeleteThis ."'";
mysqli_query($db,$sql_delete);
}
} ?>
Or you could use a a checkbox in your form with a required attribute then set the submit button to set the value of the checkbox before submitting with an onclick.
<input type="checkbox" name='ConfirmDelete'
required <?php if(isset($_GET['ConfirmDelete']))
echo 'checked=' . $_GET['ConfirmDelete']; ?> >
<input type="submit" name="Deleting" onclick=
'this.form.ConfirmDelete.checked = deleteOrNot(this.form)' value="Delete this">
and change your script like this
<script type='text/javascript'>
function deleteOrNot(formEle)
{
if(typeof formEle == 'undefined')
{
formEle = forms[0];
}
var result = confirm('Are you sure you want to delete' + formEle.Delete_This.value + ' ? \nHey');
if (result)
alert(formEle.Delete_This.value + ' will be deleted');
else
alert('Not deleted');
return result;
}
</script>
Note: I added the form as an argument to the deleteOrNot function and use that to get the value of the text box. The required on the checkbox will prevent form submission if it is not checked
onclick="return confirm('Are you sure you want to delete?');"

jQuery Mobile submit with PHP without AJAX and JavaScript

Sorry, I consider myself as a real newbie around jQuery Mobile. I'm not good at all regarding JavaScript. Here's the thing. I want to build a jQuery Mobile site without using AJAX. Just want the nice design from jQuery Mobile and then use PHP to submit forms etc.
I tried to build a simple page that submit first and last name to a MySQL database. It will submit, tell the user that it's submitted and then the user can press [Page 2] to see all the results. Now I use if(isset()) to display the message and else to display the form. So, the user who enter the site will get the form, when press [Submit] he/she will get the message that first and last name was submitted. Then press the button [Page 2] to see all the first and last names.
PHP (index.php)
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add">
</form><br>';
}
Page 2
PHP (page2.php):
$query = $db->query("SELECT * FROM name");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['fname'] . ' ' . $row['lname'] . '<br>';
}
$db = NULL;
echo 'Index';
Let's say I enter "Test" as first and last name. It will echo out "Test Test was added!". If I now press [Page 2] I will see that "Test Test" was added. BUT when I then press [Index] to go back I want it to display the form again, but the message "Test Test was added!" is displayed again instead of the form, why? I have to update the page to get the form. Now, if I enable data-ajax it's working with submitting and back-button. BUT then I have to press update at page2.php when I get there to see all the first and last names. Do I make myself understood what's the problem?
Sorry, really new at jQuery Mobile and I can't find the answer at Google. Everyone is using JavaScript to submit data. Is it possible this way or do I have to learn JavaScript to submit forms? Read somewhere that using buttons instead of submit-buttons affect it.
Thanks in advance! :)
I think you are looking to modify the DOM after the request? So post the form, add the user then display the results without having to click the button.
So on your ajax call use the done function to hide the form and show the results.
Take a look below and let me know if it helps.
EDIT: Added the .on click for the button. You may also want to look at adding a keypress checker to the inputs or an onsubmit on the form.
<div id="content">
<?php
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false" id="contentForm">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add" id="sendButton">
</form><br>';
}
?>
</div>
<script type='text/javascript'>
<!-- https://api.jquery.com/jQuery.ajax/ -->
$('#sendButton').on("click", function(){
$.ajax({
type: "POST",
url: "page2.php",
data: $('#contentForm').serialize()
})
.done(function( msg ) {
$('#content').html( msg );
});
});
</script>

jQuery load the same page after PHP submit

I'm currently struggling because I want to load the same page submited by PHP. To make this more clear, it's a comment section, where after people submit their message I would like to retrieve the same information PLUS the new one.
I'm having problems because I'm not doing this by AJAX.
So, the index.php has the following:
/* Before HTML tag */
if(Cookie::Exists('comment')){
$data = unserialize(stripslashes(Cookie::Get('comment')));
if($data['status'] == 1){
$page = "<script type='text/javascript'>set_product_id('" . $data['id'] . "')</script>";
}
Cookie::Delete('comment', time() - 3600);
}
/* Further ahead.. (inside body) */
<form method="POST" action="insert_info.php" data-ajax="false">
<input type="hidden" id="product_id" name="product_id"/>
<input type="text" id="name_" name="name_" required="required"/>
<input type="text" id="comment" name="comment" required="required"/>
</form>
/* After body */
<script type="text/javascript">
$(document).on("pagebeforeshow", "#page-comments", function() {
$(function(){
get_comments(objs.product_id);
});
});
var objs = {
product_id : ''
}
function set_product_id(id){
objs.product_id = id;
$.mobile.changePage('#page-comments', {role: 'dialog'});
}
</script>
/* After the HTML tag */
<?php echo $page; ?>
I do receive the correct ID, etc, also it works perfectly before submiting the comment. The page loads the content without any problem, etc.
insert_info.php
new_comment($host, $user, $pass, $db);
$arr = array("status" => 1, "id" => $_POST['product_id']);
Cookie::set('comment', serialize($arr), time()+60);
header("Location: ../index.php");
exit();
When I perform this operation, I do receive the following erro on google chrome console:
Uncaught TypeError: Cannot call method 'trigger' of undefined
Poiting to the line:
function set_product_id(id){
objs.product_id = id;
$.mobile.changePage('#page-comments', {role: 'dialog'});
}
What am I missing? Thanks.
EDIT: changing the set_product_id() function, to this:
$('#page-main').on('pagecreate', function(event) {
$.mobile.changePage('#page-comments', {role: 'dialog'});
});
The page of comments appears and disappears again. But if I remove the "dialog", the page stays and works correctly. But I need that to be on dialog.
Your $.mobile.changePage() needs to contain a url..
So this:
$.mobile.changePage('#page-comments', {role: 'dialog'});
Should be something like this:
$.mobile.changePage('../index.php', {role: 'dialog'});

Categories