I have an error when sending data by POST with javascript - javascript

I am trying to send data via post in Javascript, but I am new to this.
I leave my code, I want to know what I do wrong.
To begin with I have a file where I call a query in my mysql database as long as the code and the date are entered.
public function listusuerdate($date,$name) {
try {
$sql= "select * from markers where name_user = :p_user AND date_user = :p_dat";
$statement = $this->dblink->prepare($sql);
$statement->bindParam(":p_user", $name);
$statement->bindParam(":p_dat", $date);
$statement->execute();
$result= $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
} catch (Exception $exc) {
throw $exc;
}
}
I have another file where he passed the variables by means of POST in the following way:
<?php
require_once '../negocio/ShowMap.clase.php';
$date= $_POST["p_dat"];
$name= $_POST["p_user"];
$objUser = new ShowMap();
try {
$result = $objUser ->listusuerdate($date,$name);
} catch (Exception $exc) {
header("HTTP/1.1 500");
echo $exc->getMessage();
}
?>
When I use Postman works good
Here comes my problem I have created a form to send the date and the name of the user as follows:
<form>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Título de la ventana</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-2">
<p>Code<input type="text" name="txtcode" id="txtcode" class="form-control input-sm text-center text-bold" placeholder="" readonly=""></p>
</div>
<div class="col-xs-4">
<p>Name <font color = "red">*</font>
<input type="text" name="txtname" id="txtname" class="form-control input-sm" placeholder="" required=""><p>
</div>
<div class="col-xs-3">
<p>Date
<input type="date" class="form-control input-sm" id="txtdate" name="txtdate" /></p>
</div>
<div class="modal-footer">
<a class="btn btn-primary btn-lg" value='Click' href='javascript:;' onclick="toshow();" role="button"></a>
</div>
</div>
</div>
</div>
</form>
Finally I am trying to send the date and the name of the user by means of javascript in the following way:
function toshow(){
var name = document.getElementById("txtname").value;
var date = document.getElementById("txtdate").value;
$.post(
"../controlador/ruta.controlador.php",
{
p_user : name,
p_dat : date
}
).done(function(){
alert( "exit" );
}).fail(function(error){
alert(error.responseText);
});
};
I could not make it work

You need to write a js function properly check its syntax
function toshow(){
var name = document.getElementById("txtname").value;
var date = document.getElementById("txtdate").value;
$.ajax(
method:'POST', // here you can spasify post or get
url:"../controlador/ruta.controlador.php",
data : {
p_user : name,
p_dat : date
},
).done(function(){
alert( "exit" );
}).fail(function(error){
alert(error.responseText);
});
};

Related

Submitted Information from a Modal Into mySQL

I was having some problems submitted information from a modal into mySQL, this is what I have tried.
<script>
var cells = document.querySelectorAll('.table-row > td');
var cellIndex = -1;
cells.forEach((e, index) => {
e.addEventListener("click", () => {
//show modal
$('.modal').modal("show");
//update grid
// This is the row number
console.log("Row number: ", index)
cellIndex = index
})
})
function updateTable(e) {
let name, email, phonenumber, tableRow, row;
name = document.getElementById("name").value;
console.log(name, email, phonenumber);
// Get the row that you want
row = cells[cellIndex];
$(row).html(name);
$('.modal').modal("hide");
}
document.getElementById("submit-btn").addEventListener("click", updateTable);
//store in database
$.ajax({
url:"insert.php",
method:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
alert('form was submitted');
}
})
</script>
This is my insert.php:
<?php
$conn = new
mysqli("127.0.0.1","root","password");
if($conn->connect_error){
die("Connection failed: " . $conn-
>connect_error);
}
if(!empty($_POST))
{
$output = '';
$name =
mysqli_real_escape_string($connect,$_POST["name"]);
$phonenumber =
mysqli_real_escape_string($connect,$_POST["phonenumber"]);
$email =
mysqli_real_escape_string($connect,$_POST["email"]);
$query = "INSERT INTO users(name,phonenumber,email) VALUES('$name',
'$phonenumber','$email' )";
}
echo "Connected successfully";
?>
My understanding of the problem is that I need to use ajax to send a request to the web server that would store the information from the modal to the mySQL database with the given query in php. Perhaps I don't have a good understanding of the problem. I am not sure how to get the values from the modal, and in conjuction use ajax to send a post to the server. Any help would be appreciated.
Here is my Modal:
<div class="row">
<div class="col-md-12">
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1>Reservation</h1>
</div>
<div class="modal-body">
<input type="text" name="field1" placeholder="Name" id="name">
<input type="text" name="field2" placeholder="Email" id="email">
<input type="text" name="field3" placeholder="PhoneNumber" id="phonenumber">
</div>
<div class="modal-footer">
<input id="submit-btn" name="submit" class="btn submit" value="Submit">
<input class="btn btn-default" data-dismiss="modal" value="Close">
</div>
</div>
</div>
</div>
</div>
</div>

Returning json array does not shows up result on the calling script

I am posting a value on a modal dialog box and then some database operations. Now I am returning a value through
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
Is this a right way? All the database operations are performed correctly but console.log(result) does not show anything on the calling script. Something's wrong with the couple of lines above. It would be very helpful if somebody points out the error.
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation <b>PIN</b><font color="red">*</font><br>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
<p style="font-size:11px"><b><font color="red">*</font><font color="grey"><b>PIN</b><i> is mentioned in your welcome email.</font></i></b></p><br>
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Continue</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result){
if(result['status'] == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And processActivation.php,
<?php
$uid = $_SESSION['session_user_id'];
$dobCheck = $db->idToField("tbl_user", "dob", $uid);
$dob = explode("-", $dobCheck);
$pin = $_REQUEST['pin'];
$moduleId = $_REQUEST['module_id'];
$chapterId = $_REQUEST['chapter_id'];
$time_taken = $_REQUEST['seconds'];
$created = date("Y-m-d h:i:s");
if($pin != $dob[0])
{
echo "Please enter valid PIN."; die;
}
else
{
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
}
?>
And my browser tool shows,
Loading failed for the <script> with source “http://localhost/project/js/compatibility.js”.
studyChapterpdf.php:54
Use of captureEvents() is deprecated. To upgrade your code, use the DOM 2 addEventListener() method. For more help http://developer.mozilla.org/en/docs/DOM:element.addEventListener
studyChapterpdf.php:240:36
ReferenceError: fakewaffle is not defined[Learn More]
studyChapterpdf.php:492:3
Warning: Setting up fake worker.
pdf.js:1489:5
progress
Object { loaded: 131072, total: 551963 }
bootstrap-pdf-viewer.js:563:9
progress
Object { loaded: 551963, total: 551963 }
bootstrap-pdf-viewer.js:563:9
page=1 - getOperatorList: time=522ms, len=755
Found out the reason for it. There was an uncommented line left in one of the included files. So, the response was having the whole commented line as well as the actual return status==active. Fixed it. Thanks everyone for guiding.

Modal Ajax Failing to Populate

I'm not sure why this modal isn't populating the post ajax data. Its actually supposed to update a row in my SQL DB upon success but the error I'm getting is "Uncaught TypeError: Cannot read property 'value' of null." Does anyone have any idea why this failing?
Updated: I apologize for leaving out the php which generated the partners item.
HTML:
while($row = mysqli_fetch_array($partners)) {
// $optionsPartners .="<option>" . $row['Partners'] . "</option>";
$optionsPartners.="<input type='checkbox' name='Partners[]' value=".$row['Partners']."> ".$row['Partners']."<br>";
}
$partnersmenu=
/*"<select name='Partners' id='Partners'>
" . $optionsPartners . "
</select>"*/
$optionsPartners;
?>
<div id="id02" class="modal">
<span onclick="document.getElementById('id02').style.display='none'"
class="close" title="Close Modal">×</span>
<!-- Modal Content -->
<form class="modal-content animate" action="modify_records.php" method="post">
<div class="container">
<h3>Edit an Existing Project</h3>
<label for="Project_Name" class="ui-hidden-accessible">Project Name:</label>
<input type="Project_Name" name="Project_Name" id="Project_Name" placeholder="Project Name">
<br><br>
<label for="Partners" class="ui-hidden-accessible">Partners:</label>
<?php
echo $partnersmenu;
?>
<br><br>
<input type="button" id="edit_button<?php echo $row['id'];?>" class="btn" value="Submit" data-dismiss="modal" onclick="edit_row('<?php echo $row['id'];?>');">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
</div>
<div class="container" style="background-color:#f1f1f1">
</div>
</form>
</div>
PHP:
if(isset($_POST['edit_row']))
{
$row=$_POST['id'];
$Project_Name=$_POST['Project_Name'];
$Partners=$_POST['Partners'];
mysqli_query($conn,"update Project_Detail set Project_Name='$Project_Name',Partners='$Partners' where id=$row");
echo "success";
exit();
}
JS:
function edit_row(id)//save_row(id)
{
//var id=document.getElementById("id"+id).value;
var id=document.getElementById("id"+id);
var Project_Name=document.getElementById("Project_Name"+id).value;
var Partners=document.getElementById("Partners"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
id:id,
Project_Name:Project_Name,
Partners:Partners,
},
success:function(response) {
if(response=="success")
{
//document.getElementById("id"+id).innerHTML=id;
document.getElementById("Project_Name"+id).innerHTML=Project_Name;
document.getElementById("Partners"+id).innerHTML=Partners;
//document.getElementById("edit_button"+id).style.display="block";
// document.getElementById("save_button"+id).style.display="none";
}
},
error: function(response) {
alert("some error");
}
});
}
I see a few problems and they all pertain to how you are calling you elements in your javascript and how your elements are labeled in your html.
Example:
<input type="Project_Name" name="Project_Name" id="Project_Name" placeholder="Project Name">
Should look like this:
<input type="text" name="Project_Name" id="Project_Name<?php echo $row['id']; ?>" placeholder="Project Name">
Look through all your elements and then look through your js so your are calling the correct ids.
Also in your html I copied in above, I changed the type to "text".
Also, I do not see an element with the id of "Partners" let alone "Partners" + id.
Hope that helps.
try
var id=document.getElementById("id");
instead of
var id=document.getElementById("id"+id);

jquery .post can't pass the value into php for checking

I have a question in jquery - Post . when I input the email in the form, the js - jquery will pass the email into sendResetPasswordMail1.php to check email is valid or not.
but now, $.post("sendResetPasswordMail1.php",mail:email},function(resetPasswordMsg) can not work in js.
I can't find what wrong. Distress.
Could you help me please.
Many Thanks.
php
<!--reset Password Popup start-->
<div class="resetPasswordLayer" id="resetPassword" tabindex="-1">
<div class="resetPasswordLayerWall" id="resetPasswordLayerWall">
<button type="button" class="close resetPasswordCloseButton" aria-label="Close"><span aria-hidden="true">×</span></button>
<p><h3 class="layerTittle">Reset Password</h3></p>
<div class="row">
<!--<form class="form-horizontal" action="ResetPassword/sendResetPasswordMail.php" method="post" id="login-form">-->
<div class="form-horizontal form-group">
<div class="input-group">
<p><strong>User can retrieve the password through the mailbox</strong></p>
<!--<p><strong>Enter your registered e-mail, retrieve your password:</strong></p>-->
<p><input type="text" class="form-control" name="resetPasswordEmail" id="resetPasswordEmail" placeholder="Enter your registered e-mail, retrieve your password."><span id="chkresetPasswordMsg"></span></p>
</div>
</div>
<div class="form-group">
<div class="input-group"><!--<div class="col-md-11 col-md-offset-1">-->
<p><input type="button" class="btn btn-success" id="subSendResetPassword_btn" value="Reset"></p>
<!--<button type="submit" class="btn btn-success"id="subSendResetPassword_btn">Reset</button>-->
<span id="resetPasswordMsg"></span>
</div>
</div>
<!--</form>-->
</div>
</div>
</div>
<!--reset Password Popup End-->
js - jquery
$(function(){
$("#subSendResetPassword_btn").click(function(){
var email = $("#resetPasswordEmail").val();
var preg = /^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/; //match Email
if(email=='' || !preg.test(email)){
$("#chkresetPasswordMsg").html("Please fill in the correct email!");
}else{
$("#subSendResetPassword_btn").attr("disabled","disabled").val('Submit......').css("cursor","default");
alert(email);
$.post("sendResetPasswordMail1.php",{mail:email},function(resetPasswordMsg){
if(resetPasswordMsg == ""){
alert("No Msg Return!");
}
if(resetPasswordMsg=="noRegister"){
$("#chkresetPasswordMsg").html("The mailbox is not registered yet!");
//$("#subSendResetPassword_btn").removeAttr("disabled").val('Submit').css("cursor","pointer");
}else{
$(".resetPasswordLayer").html("<h3>"+resetPasswordMsg+"</h3>");
}
});
}
});
})
php - sendResetPasswordMail1.php
$email = stripslashes(trim($_POST['mail']));
$sql = "select * from user where email='$email'";
$query = mysql_query($sql);
$num = mysql_num_rows($query);
if($num==0){//The mailbox is not registered yet! Return 'noRegister'
$resetPasswordMsg = "noRegister";
echo $resetPasswordMsg;
exit;
}
Prevent the default click event
$("#subSendResetPassword_btn").click(function(e){
e.preventDefault()
});

Ajax is not updating data

I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code :
<button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal<?php echo $list['id']; ?>">
Edit <i class="fa fa-pencil-square-o"></i>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $list['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="container">
<form style="width: 550px;" action="" method="post" id="signin-form<?php echo $list['id']; ?>" role="form">
<input type="hidden" name="commentID" value="<?php echo $list['id']; ?>">
<div class="from-group">
<label for="title">Title: </label>
<input class="form-control" type="text" name="title" id="txttitle" value="<?php echo $list['title']; ?>" placeholder="Page Title">
</div>
<div class="from-group">
<label for="label">Label: </label>
<input class="form-control" type="text" name="label" id="txtlabel" value="<?php echo $list['label']; ?>" placeholder="Page Label">
</div>
<br>
<div class="from-group">
<label for="body">Body: </label>
<textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"><?php echo $list['body']; ?></textarea>
</div>
<br>
<input type="hidden" name="editted" value="1">
<br>
<br>
<input type="submit" id="btnupdate" value="Edit">
</form>
</div>
</div>
as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below :
case 'postupdate';
if(isset($_GET['editted'])){
$title = $_GET['title'];
$label = $_GET['label'];
$body = $_GET['body'];
$action = 'Updated';
$q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID'];
$r = mysqli_query($dbc, $q);
$message = '<p class="alert alert-success"> Your Post Is Succesfully '.$action.'</p>' ;
}
and here is the ajax code snippet;
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempUrl = "index.php?page=postupdate"+"&title="+tempTitle+"&label="+tempLabel+"&body="+tempBody+"&commentID=30&editted=1";
$.get(tempUrl);
});
I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)
This (untested code) may be similar to what you should do:
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempParams = {"page":"postupdate","title":tempTitle,"label":tempLabel,"body":tempBody,"commentID":30,"editted":1};
$.post("index.php",tempParams,function(data) {
alert(data);
});
});
UPDATE
Try ajax instead of get to see if some error occurs in the loading
$.ajax( {url:"index.php",data:tempParams,type: "POST"} ).done(function() {
alert( "success" );
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});`
UPDATE
Start testing if the click handler works then (just to be sure!):
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
UPDATE
Start testing if the script gets executed then:
alert("yes at least the script gets executed");
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
If not you must have a javascript error somewhere.
https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
If yes, your button does not get caught by JQuery (no idea why)
anyway it's got nothing to do with ajax or get!

Categories

Resources