Use jQuery to update database using POST method - php

I want to send every data from the form to an external php file and update the database values. It seems nothing happens. Console doesn't show any errors. I have searched for responses and nothing seems to work for me.
$(document).ready(function(){
$('#updatesettings').submit(function(e) {
e.preventDefault();
var lang = $(this).find('.dropdown-toggle').text();
console.log('lang=' + lang +'&'+ $(this).serialize());
$.ajax({
type: "POST",
url: "modules/game/updatesettings.php",
data: 'lang='+lang+'&'+$(this).serialize(),
}).done(function(data){
console.log(data);
})
.fail(function(error){
console.log(error);
});
;
});
});
<form id="updatesettings" method="post">
<p>
<label for="link">LINK</label>
<input type="text" name="link" class="textbox" id="link" value="<?php echo $tlink;?>" placeholder="LINK"> <?php if($tlink != "") echo'<i class="fa fa-check green"></i>'; else echo'<i class="fa fa-times red"></i>';?>
</p>
<p>
<label for="email">EMAIL</label>
<input type="text" name="email" class="textbox" id="email" value="<?php echo $email; ?>" placeholder="E-MAIL"><?php if($email != "") echo' <i class="fa fa-check green"></i>'; else echo' <i class="fa fa-times red"></i>';?>
</p>
<div class="btn-group">
<a class="btn dropdown-toggle btn-select" data-toggle="dropdown" href="#"><?php echo $langset; ?> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><span class="flag flag-usa flag-1x"></span> English</li>
<li><span class="flag flag-rou flag-1x"></span> Romana</li>
</ul>
</div>
<p><input type="submit" class="button" href="#" value="Save settings"></p>
</form>
The external php file that I try to use for update is this.
<?php
#include_once('modules/connections/dbconn.php');
$link = $_POST["link"];
$link = mysql_real_escape_string($link);
$email = $_POST["email"];
$email = mysql_real_escape_string($email);
$id = $_SESSION["id"];
$lang = $_POST["lang"]
if($lang=="English"){
$lang="en";
}
else {
$lang="ro";
}
mysqli_query($GLOBALS['connect'],"UPDATE users SET `link`='$link' WHERE `id`='$id'");
mysqli_query($GLOBALS['connect'],"UPDATE users SET `email`='$email' WHERE `id`='$id'");
mysqli_query($GLOBALS['connect'],"UPDATE users SET `lang`='$lang' WHERE `id`='$id'");
exit;
?>
Thank you so much for trying to offer your help!

You are not handling the result in case of success(done) or error(fail). Try:
$.ajax({
type: "POST",
url: "updatesettings.php",
data: 'lang='+lang+'&'+$(this).serialize(),
})
.done(function(data){
console.log(data);
})
.fail(function(error){
console.log(error);
});
done() is called when your request is correct, fail() in case of some error.
Tip: press f12 and go to Network tab to check your requests.
Check this pen

There's two issues in your code. Firstly the querystring you're building is malformed. You need to add a & between the lang value and the rest of the serialised form data. Secondly the DOM traversal to get the .dropdown-toggle text is incorrect. this will refer to the form element so you need to use find() to work down the DOM, not parents() to go up it.
It would also be worth adding a success and error handler, at least to aid debugging. Try this:
$('#updatesettings').submit(function(e) {
e.preventDefault();
var lang = $(this).find('.btn-group .dropdown-toggle').text();
$.ajax({
type: "POST",
url: "updatesettings.php",
data: 'lang=' + lang + '&' + $(this).serialize(),
success: function() {
console.log('it worked!');
},
error: function(x, s, e) {
console.log('it failed');
console.log(x, s, e);
}
});
});

Related

How do I pass 2 input fields one is static and on is on keyup?

I have a live search setup and working properly using on post value. I would like to add a parameter to my DB query that involves an additional "post" value. This is using php and ajax.
The variable $school shows up on in the text field and is populated by the $_GET['sch'] value. The query shows empty when the ajax is executed. (using echo $Query)
When "echoed", The &Query looks like this:
SELECT * FROM teachers WHERE FullName LIKE %test% and shcool_id = ''
Here is the PHP
<?php
if (isset($_POST['search'])) {
$school = $_GET['sch'];
$Name = $_POST['search'];
$Query = "SELECT * FROM teachers WHERE fullName LIKE '%$Name%' AND school_id='$school' ";
$ExecQuery = MySQLi_query($conn, $Query);
echo '<div class="list-group" style="text-align:left;">';
while($Result = MySQLi_fetch_array($ExecQuery)) {
?>
<a href="?id=<?php echo $Result['teacher_id']; ?>&sch=<?php echo $Result['school_id']; ?>" type="button" width="100%" onclick='fill("<?php echo $Result['fullName']; ?>")' class="list-group-item list-group-item-action">
<?php echo $Result['fullName']; ?>
</a>
<?php
}
}
$conn->close();
?>
</div>
Here is the script file:
function fill(Value) {
$('#search').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
$("#display").html("");
}
else {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
search: name
},
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
Here is the form:
<div class="input-group" style="margin-top: 5.5em;">
<button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Search By</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="/isbn/title/?sch=<?php echo $_GET['sch']; ?>">Book Title</a></li>
<li><a class="dropdown-item" href="/isbn/author/?sch=<?php echo $_GET['sch']; ?>">Author</a></li>
<li><a class="dropdown-item" href="/isbn/teacher/?sch=<?php echo $_GET['sch']; ?>">Teacher</a></li>
</ul>
<input placeholder="<?php echo $placeholder; ?>" class="form-control" aria-label="Text input with dropdown button"
onblur="this.focus()" onfocus="this.value=''" type="text" id="search" autocomplete="off" <?php echo $disabled; ?> />
<input class="form-control" type="text" id="school" value="<?php echo $_GET['sch']; ?>" />
<br>
<div id="display" style="width: 100%;"></div>
</div>
I tried to assign data. I've tried adding the var = school, etc
I've tried adding the GET value directy on the PHP page
I can see the value is populated in the id="school" text box.
data: {
search: name, school: school
},
to the ajax file
Get your query params before ajax call.
let sch = '';
let queryParms = new URLSearchParams(window.location.search);
if (queryParms) {
sch = queryParms.get('sch');
}
...
$.ajax({
type: "POST",
url: "ajax.php",
data: {
search: name,
sch: queryParms.get('sch')
},
success: function(html) {
$("#display").html(html).show();
}
});
At the backend use and check for non empty value.
$_POST['sch'];

AJAX doesn't insert data into database

I have several advertisements. Each of them has a 'garage' button. If I click this button, it should insert his own userid and motorcycle id into the database. I think the insert method is good but something isn't good with the ajax. I get the success message back, but the data doesn't get inserted to my database.
<form action="" method="POST" id="upload-to-garage<?php echo $row['id']; ?>">
<div class="float-right">
<input type="hidden" value="<?php echo $row['id']; ?>" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage"></i></button>
</div>
</form>
$(document).ready(function() {
$("#upload-to-garage<?php echo $row['id']; ?>").submit(function(e) {
e.preventDefault();
$.ajax({
url: "upload-to-garage.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function() {
alert('success');
}
});
});
});
upload-to-garage.php
<?php
session_start();
require_once("config.php");
// Add to garage
if (isset($_POST['garage'])) {
$advertId = $_POST['advert-id'];
$userid = $_SESSION['id'];
$stmt = $link->prepare("INSERT INTO garage (userid, motorcycleid) VALUES (?, ?)");
$stmt->bind_param('ii', $userid, $advertId);
$stmt->execute();
$stmt->close();
}
?>
Just checked and if I skip the AJAX part and using the simple PHP, it works fine. So the problem is with the AJAX for sure, but can't see what.
You can change your event handler like this $("form[id*=upload-to-garage]") instead of using php code for ids and then use $(this) to refer current form.Also, when you use serialize function submit button value doesn't get send so you can attach that as well using &parametername=somevalue
Demo Code :
$(document).ready(function() {
//form when submit
$("form[id*=upload-to-garage]").submit(function(e) {
console.log($(this).serialize() + "&garage=somevalue")
e.preventDefault();
$.ajax({
url: "upload-to-garage.php",
method: "post",
data: $(this).serialize() + "&garage=somevalue", //use this here
dataType: "text",
success: function() {
alert('success');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" id="upload-to-garage1">
<div class="float-right">
<input type="hidden" value="1" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage">i</i></button>
</div>
</form>
<form action="" method="POST" id="upload-to-garage2">
<div class="float-right">
<input type="hidden" value="2" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage">i</i></button>
</div>
</form>

Remove Label Tag / Add Input textBox Using Jquery/Bootstrap

I have a column in Database with name URL and ID(PK) i'm using PHP/MYSQL
Im displaying values from db now i want to perform EDIT(update) operation Using Jquery/Ajax.
When i click on Edit link it is replaced with Update/Cancel links Which is working fine and im able to perform update operations.
My requirement is when i click on edit Url data which im using lable tag should replace with input textbox and i should perform update operation
HTML Code
<div class='col-md-4'>
<label class="feed_label" id="feed_label" idl='<?php echo $row->id;?>'><?php echo $row->url; ?></label>
<input name="url1" class="form-control url1 feed_text" value="<?php echo $row->id;?>" id="url1" type="text" placeholder="enter url" style="display:none;">
</div>
<div class='col-md-2'>
<a ide='<?php echo $row->id;?>' id="edit" class='edit' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update btn btn-primary btn-sm' href='#' style='display:none;'>UPDATE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancel btn btn-warning btn-sm' href='#' style='display:none;'>CANCEL</a>
</div>
JQUERY CODE
JQUERY CODE
//EDIT,DELETE TO UPDATE,CANCEL
$('body').delegate('#edit','click',function(){
//alert();
$(this).siblings('#delete').hide();
$(this).siblings('#update,#cancel').show();
$(this).hide();
$('#feed_label').removeClass('feed_label').addClass('feed_url');
});
$('body').delegate('#cancel','click',function(){
//alert();
$(this).siblings('#edit,#delete').show();
$(this).siblings('#update').hide();
$(this).hide();
$("#update_url")[0].reset();
});
//ENDS
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
//alert(IdEdit);
//return false;
$.ajax({
url:"pages/feeds.php",
type:"post",
datatype:"json",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
//alert('success');
$('#id').val(show.id);
$('#url1').val(show.url);
//$('#add_feed_form')[0].reset();
//$('#showdata').load('pages/feeds.php');
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
//alert('update');
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
//alert();
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
//alert('updated');
$('input[type=text]').val('');
showdata();
$('#add_feed_form')[0].reset();
$('#showdata').load('pages/feeds.php');
}
});
});
//UPdate Ends
PHP Code
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
//Ends
Any help Is appreciated Thanks!!
Here i give sample for your case :
HTML
<div class="container">
<label>John</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
<hr/>
<div class="container">
<label>John Who</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
JS (you can simplified below code into one handler)
$(document).on('click', '.edit', function(e){
var data = $(this).prev();
if ( data.is('label') ) data.replaceWith('<input value="'+data.text()+'">');
});
$(document).on('click', '.delete', function(e){
var data = $(this).prev().prev();
if ( data.is('input') ) data.replaceWith('<label>'+data.val()+'</label>');
});
DEMO

Cancel submit jquery

This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/

jQuery ajax fails on form submit with link

In the sequence of this question, the content I've got in a form is now updating the DB. However, when I click this link
<a onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>
The jQuery .ajax function fires the error callback AND updates the DB with the information as well.
Here's the code
function doUpdate()
{
e.preventDefault();
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error: function(data){
$("#response-update").html("Erro na submissão");
}
});
}
I'd like to get the success callback, in order to display a nice message to the user when it saves the data.
However if I simply do this
Gravar
<script>
$(function(){
$('#commit-changes').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error: function(data){
$("#response-update").html("Erro na submissão");
}
});
});
});
</script>
The "submition" doesn't work at all.
How can I solve this problem? Been stuck with this part for days! :(
EDIT - HTML for the form (This is also a response loaded in the begging of the page)
$response.='<form id="validation" method="post">
<fieldset >
<input type="hidden" name="user_id" value="'.$_POST['user_id'].'"/>
<legend>Actualizar Dados Utilizador</legend>
<div class="section ">
<label>Nome<small>Insira o seu nome</small></label>
<div>
<input type="text" class="validate[required,custom[onlyLetterSp]] large" name="nome" id="f_required" value="'.utf8_encode($rcs_user->nome).'">
</div>
</div>';
$response.='<div class="section ">
<label> Email<small>Insira o seu email</small></label>
<div>
<input type="text" class="validate[required,custom[email]] large" name="email" id="e_required" value="'. utf8_encode($rcs_user->email).'">
</div>
</div>';
$response.= '<div class="section">
<label>Permissões<small>Seleccione o tipo de utilizador </small></label>
<div>
<select class="medium" name="role">
'.$role.'
</select>
</div>
</div>
<div class="section">
<label>Activo<small>Activar utilizador</small></label>
<div>
'.$activo.'
<span class="f_help">ON / OFF </span>
</div>
</div>
<div class="section last">
<div>
<a onclick="return doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a><a class="uibutton special" onClick="ResetForm()" title="Limpar Formulário" >Limpar Formulário</a>
</div>
</div>
</fieldset></form>
Have you put your jQuery code inside a document.ready handler?
jQuery(function ($) {
// put jQuery here
});
The first example will work without document.ready (but doesn't make much sense because you're using jQuery anyway). The second won't.
In order to behave doUpdate() function as expected, Try this
modify the anchor tag onclick attribute to
<a onclick="return doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>
and also change the doUpdate function to
function doUpdate()
{
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error: function(data){
$("#response-update").html("Erro na submissão");
}
});
return false;
}
The jquery ajax success/error callbacks will fire based upon whether the POST request was received or not, it has nothing to do with what actually happens within the file you have posted to. It's strange you would get the error callback and have the database updated, but you can try and have the php file you are posting to give a response and then run success/error based upon that response.
In your php file you could have something like this:
$testQuery = "QUERY STRING HERE";
if(!mysql_query($testQuery))
{
echo "error";
exit;
}
else
{
echo "sucess";
exit;
}
And then in your doUpdate function you can run the success callback and output based upon the html
function doUpdate()
{
e.preventDefault();
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
if(data == "success")
{
$("#response-update").html(data);
}
else
{
$("#response-update").html("Erro na submissão");
}
}
});
}
You can also use the "complete" callback which will fire even if the POST was not received, that wont tell you anything other than the function has been ran though
I've got a solution. Not the prettiest, as I wanted a pure jQuery solution, but, it works well.
Just needed to change the
<a onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>
To
<input onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form" value="Gravar" />
And now it works with the sucess callback firing.
Thanks for all the help on this.

Categories