Processing form using jQuery - javascript

I need to process my form using jQuery (without refresh my site ) and using one buddon i want to add or delete row from my database .
Inserting to database works fine
Deleteting too but i dont know what i need to do that after first click i add to database but after second click i delete row from database.
My FORM
<form action="index.php" method="post" id="myForm">
<input type="hidden" name="option" value="com_mediamall" />
<input type="hidden" name="task" value="addToFav" />
<input type="hidden" name="addMediaId" value="<?php echo $media->id; ?>" />
<input type="hidden" name="delRow" value="<?php echo $del->id; ?>" />
<input type="submit" name="submit" id="sub" value="1"></input>
</form>
jQUERY
<script>
$("#sub").click( function() {
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray());
});
$("#myForm").submit( function() {
return false ;
});
</script>
FUNCTION INSERT OR DELETE
function addToFav() {
$user =& JFactory::getUser();
$db2 =& JFactory::getDBO();
$mediaid = $_POST['addMediaId'];
$delid = $_POST['delRow'];
if(isset($_POST['submit']) == '1') {
$query = ' INSERT INTO `#__mediamall_favourite_media` (`id`, `userid`, `mediaid`) VALUES ("","'.$user->id.'","'.$mediaid.'")';
}
elseif(isset($_POST['submit']) == '0') {
$query = ' DELETE FROM #__mediamall_favourite_media WHERE id = "'.$delid.'" ';
$db2->setQuery($query);
$db2->query();
}
}
Will be apriciate form your help because i spend a lot of hours to find the anwer and without the result .. Thanks

you need to use preventDefault
$('#myForm').submit(function(e){
e.preventDefault();
var url = $("#myForm").attr("action");
$.post(url,{data : $('#myForm').serialize()},function(data){
//process
});
});
and you can also use json to retrieve data from php so in your php file you can do
$data['res'] = 'ok';
$data['something_else'] = 'value';
echo json_encode($data);
Then process it like this
$('#myForm').submit(function(e){
e.preventDefault();
var url = $("#myForm").attr("action");
$.post(url,{data : $('#myForm').serialize()},function(data){
//process
console.log(data.res);
console.log(data.something_else);
}.'json');
});

Toggle submit button value after insert or delete like,
$("#sub").click( function() {
var url=$("#myForm").attr("action");
$.post(url, $("#myForm :input").serializeArray(),function(){
var val=$("#sub").val()==1 ? 0 : 1;// toggle value of submit for insert or delete
$("#sub").val(val);
});
});
In PHP change your condition from isset($_POST['submit'])=='1' to isset($_POST['submit']) and $_POST['submit'] == '1'
Code like,
if(isset($_POST['submit']) and $_POST['submit'] == '1') {
$query = ' INSERT INTO `#__mediamall_favourite_media` (`id`, `userid`, `mediaid`) VALUES ("","'.$user->id.'","'.$mediaid.'")';
}
elseif(isset($_POST['submit']) and $_POST['submit'] == '0') {
$query = ' DELETE FROM #__mediamall_favourite_media WHERE id = "'.$delid.'" ';
}
if($query)
{
$db2->setQuery($query); //after if - else conditions
$db2->query();
}

HTML
<form action="" onsubmit="return false;" method="post" id="myForm">
<input type="hidden" name="option" value="com_mediamall" />
<input type="hidden" name="task" value="addToFav" />
<input type="hidden" name="addMediaId" value="<?php echo $media->id; ?>" />
<input type="hidden" name="delRow" value="<?php echo $del->id; ?>" />
<input type="submit" name="submit" id="sub" value="1"></input>
JQUERY
$('#myForm').submit(function(){
$.post(url,$('#myForm').serialize(),function(success){
if(success=='success'){
alert('Data Sent);
// or do something else
}
});
});

Related

Form insertion into database not working asynchronously

I'm trying to get a text area's value inserted asynchrnously into my database, however it keeps redirecting to the PHP processing page, and echoing a result there. How would I get it to echo the result of the PHP script on the current HTML page?
JS:
$("#sub").click(function() {
$.post( $("#text").attr("action"), $("#text :input").serializeArray(),
function(info) { $("#result").html(info);});
});
$("#text").submit( function(){
return false;
})
PHP:
$sql = "UPDATE text
SET text_content = ? WHERE (id = 40) AND (number = $Number);";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql))
{
header("Location: ../create_text.php?error&prepare1111");
exit();
}
else
{
$stmt->bind_param("s", $content);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$connection->close();
echo "successfully saved";
}
HTML:
<form type="text" method="post" onSubmit="return validateText(); toHTML();" action="processing.php" id="text">
<textarea name="content" rows="45" id="auto-expand" class="text-box" type="text"><?php echo stripslashes($content) ?></textarea>
<input type="hidden" name="id" id="id" value="<?php echo $id ?>">
<input type="hidden" name="number" id="number" value="<?php echo $number ?>">
<input type="hidden" name="updated" value="<?php echo $updated ?>">
<button type="submit" id="sub" name="submit">Save</button>
<button type="button" onClick="validateText(); toHTML();">Check</button>
<span id="result"></span>
</form>
Any help would be so great! :)
Try preventDefault:
$("#text").submit( function(e){
e.preventDefault();
})

ajax form request still reloads page

I am trying to submit a form using ajax with jquery mobile without it refreshing the page and am having no luck..
I have this form -
index.php:
<script>
function SubmitForm() {
var name = $("#name").val();
$.post("bump.php", { name: name},
function(data) {
//alert(data);
});
}
</script>
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>
Here is bump.php
$date = date('y/m/d H:i:s');
$id = $_POST['name'];
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
I would like to maintain my position on the page but it refreshes each time? What am I doing wrong here?
Use event.preventDefault(); Cancels the event if it is cancelable, without stopping further propagation of the event.
Default behaviour of type="image" is to submit the form hence page is unloaded
function SubmitForm(event) {
event.preventDefault();
var name = $("#name").val();
$.post("bump.php", {
name: name
},
function(data) {
//alert(data);
});
}
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm(event);" value="Send" />
</form>
user return false in onclick`
function SubmitForm() {
//event.preventDefault();
var name = $("#name").val();
console.log(name);
$.post("message.html", { name: name},
function(data) {
alert(data);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="http://switchon.global2.vic.edu.au/files/2015/07/4x5-1jroh2i.png" id="searchForm" onclick="SubmitForm(); return false;" value="Send" />
</form>

PHP AJAX POST multiple same name

I have code like this:
<form method="post" id="result-image" name="result-image" action="" >
<?php $i=1; foreach ($data as $key => $datas) { ?>
<div class="col-md-2 thumb custom-size col-lg-3 col-xs-4">
<label class="btn btn-default turunin " >
<img class="thumbnail img-responsive img-check" src="<?php echo $datas['thumbnail'];?>" alt="<?php echo $datas['image_alt'];?>" title="<?php echo $datas['title']; ?>">
<div class="caption" style="text-align:center; margin-top:-15px; padding-bottom:0px;"><?php echo $datas['size'];?></div>
<input type="checkbox" name="cek[]" id="cek" class="hidden" value="<?php echo $i ?>" autocomplete="off" >
<input type="hidden" name="image[]" id="image[]" value="<?php echo $datas['image'] ?>" />
<input type="hidden" name="page[]" id="page[]" value="<?php echo $datas['page'] ?>" />
<input type="hidden" name="size[]" id="size[]" value="<?php echo $datas['size'] ?>" />
<input type="hidden" name="thumbnail[]" id="thumbnail[]" value="<?php echo $datas['thumbnail'] ?>" />
<input type="hidden" name="image_alt[]" id="image_alt[]" value="<?php echo $datas['image_alt'] ?>" />
<input type="hidden" name="title[]" id="title[]" value="<?php echo $datas['title'] ?>" />
</label>
</div>
<?php $i++; } ?>
<button type="submit" id="edit_submit" class="btn btn-success edit_submit">Next Step <i class="fa fa-arrow-right" aria-hidden="true"></i></button>
</form>
then I want POST via AJAX, this my little javascript:
jQuery(document).ready(function($) {
$('#result-image').submit(function(e) {
e.preventDefault();
data = { action : 'aad_edit_results',
//////////// WHAT I SHOULD WRITE /////
// image : $("#image").val(), /// This work if one
// page : $("#page").val(), /// This work if one
// size : $("#size").val(), /// This work if one
// title : $("#title").val(), /// This work if one
//////////// WHAT I SHOULD WRITE /////
beforeSend : function(){
$('#myPleaseWait').modal('show');
//$('.edit_submit').attr('disabled',true);
},
};
$.post(ajaxurl, data, function(response) {
$("#edit-image-modal").html(response).modal();
$('#myPleaseWait').modal('hide');
//$('#edit_submit').attr('disabled',false);
});
return false;
});
});
how can I change this code, because it only work if single name is used?
// image : $("#image").val(), /// This work if one
// page : $("#page").val(), /// This work if one
// size : $("#size").val(), /// This work if one
// title : $("#title").val(), /// This work if one
I have tried many more concepts but they are not working, can anybody help me?
I think it will help you. Convert form data to JavaScript object with jQuery
You can send this converted data with ajax, but if you want to send to ajax only checked elements you can use it.
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// you can also change it to $('#result-image').submit(function(){});
$("#edit_submit").on({
click: function (e) {
e.preventDefault();
var form = $('#result-image'),
data = form.serializeObject(),
checkbox = form.find('input[type=checkbox]:checked'),
sendAjaxData = [];
$.each(checkbox, function (i, k) {
sendAjaxData[i] = {
image: data['image[]'][k.value - 1], // why -1? because of your checkbox value starts from 1, but `i` starts from 0
page: data['page[]'][k.value - 1],
// ...... write your other inputs
};
});
console.log(sendAjaxData); // send to ajax `sendAjaxData`
// .. ajax request goes here.
$.ajax({
url: "sendRequest.php",
method: "POST",
data: {data:sendAjaxData},
dataType: "json", // if you want to get object data use json, but you want to get text data then use html
success: function (data) {
},
error: function (data) {
}
});
return false;
}
});
PHP File sendRequest.php
<?php
print_r($_POST);
//also you can get with $_POST["data"];
I hope it will help you.
Use classes, not IDs. ID (= unique IDentifier) must be unique across the DOM.
var values = $.map( $(".someInputClass"), function(elem){
return $(elem).val();
})
console.log(values);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="someInputClass" value="Input 1"/>
<br>
<input class="someInputClass" value="Input 2"/>
<br>
<input class="someInputClass" value="Input 3"/>
<br>
<input class="someInputClass" value="Input 4"/>
This code grabs all the <input>, reads their values and puts them in an array. Then send the array of values to the server. That's one way to do it.

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

SESSION variable slow to update textfield in php

I have a form, contained 3 fields, which when the submit button in submitted,
it will changes the session variable values according to the fields, in this case there are 3 variables. then i echo back the variable onto the fields.
For the first time submit, it stores the value beautifully and display in the fields correctly, the problem is that, when i submit the second time, the values are still the same. after i refresh the page, then the values in the fields are changed.
this is partially the codes i'm using now.
<?php
session_start();?>
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
}
?>
After i refresh(F5), then the value changed. i want it to be, when i clicked the submit button, it will change to the new value.
PHP Code:
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
echo '<script type="text/javascript">'
, 'jsfunctionToPrintUpdatedValues();'
, '</script>'
;
}
?>
Javascript Sample Code
function jsfunctionToPrintUpdatedValues()
{
/* retrieve the updated session variables in javascript variables */
var acc_main_js = <?php echo $_SESSION['acc_main']?>
var acc_id_js = <?php echo $_SESSION['acc_id']?>
var acc_cat_js = <?php echo $_SESSION['acc_cat']?>
document.getElementById("main").value=acc_main_js;
document.getElementById("id").value=acc_main_js;
document.getElementById("cat").value=acc_main_js;
}
in the input fields you have to write like this
`
Below
`
<input type="text" name="acc1" value="<?php if(isset($_SESSION['acc_main'])) echo $_SESSION['acc_main']" />
Use if(isset($_POST['submit']) != '') before the form. Change your code to this:
<?php
session_start();
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
}else{
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
<?php } ?>

Categories

Resources