jQuery GET overwiting POST - php

I've got a simple jQuery script that isn't behaving correctly. What am I doing wrong? The idea is that the user enters a value into a textbox and then clicks a button. The jQuery then uses POST to send the value to a PHP file. The PHP file then runs a simple SQL query and gives a response. jQuery .load is then used to refresh the div containing the original php.
Using Chrome's tools, I've noticed that the response for POST is perfect. However, it then gets overwritten by a GET with no data.
jQuery:
$("#GOtest").click(function() {
var customer = $("#customer").val();
if (customer == '') {
$('#alert_formula_save_failed').show();
}
else {
$.post("../assets/forms/formulations/set_session.php", {
customer: customer,
}, function(data) {
$('#alert_formula_save_success').show();
$('#dynamic').load('../assets/forms/formulations/set_session.php');
$('#alert_formula_save_failed').hide();
setTimeout(function() { $('#alert_formula_save_success').fadeOut('fast'); }, 3000);
});
}
});
PHP:
<?php
$customer = null;
$customer = 'Test' ;
$customer2 = $_POST['customer'] ;
.. db connection bits ;
try
{
$PDO = new PDO( "mysql:host=".$host.";"."dbname=".$dbname, $user, $pass);
}
catch(PDOException $e)
{
die($e->getMessage());
}
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM db_customers where customer = '$customer' ";
$stmt = $PDO->prepare($sql);
$stmt->execute(array($id));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$PDO = null;
$iscurrent = $data['iscurrent'];
echo '<br>' ;
echo 'Response 1-' ;
echo $iscurrent;
echo '<br>' ;
echo 'Response 2-' ;
echo $customer2 ;
?>
HTML:
<form id="testform" name="testform" method="POST">
<button type="button" name="GOtest" id="GOtest" class="btn btn-info">
<i class="fa fa-frown-o"></i>
SET SESSION
</button>
The idea being that 'response 1' just echoes a predefined value. Response 2 should just echo out whatever is typed into the text input box.. but the GET overwrites everything.

The "issue" is this line:
$('#dynamic').load('../assets/forms/formulations/set_session.php');
It uses GET by default.
Try using this in its place:
$('#dynamic').html(data);

Related

How to update more then one database column

I was following one guy's tutorial on how to update database with ajax but I had some other intentions, he wanted to make a new row each time he updates his form, where I wanted to update an existing row. I Successfully updated the code to my needs but I want to update more then one column in that same row.
My form has 2 values, Show Announcement and Announcement Content where In text field I update Show Announcement to either 0 or 1 (true, false) and in Announcement Content to some text I want.
Now, the problem is that when trying to add && isset($_POST['anncontent']) && $_POST['anncontent']!='' in if statement in line 19 (marked where it is) and adding another SET option in $sql (SET announcement=('".addslashes($_POST['anncontent'])."')), it gives me status code 500 and neither of these 2 content updates in a database.
.submit.php
<?php
$host = "localhost";
$database = "";
$username = "";
$password = "";
try
{
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$response = array('success' => false);
LINE 19 ---> if(isset($_POST['name']) && $_POST['name']!='' && isset($_POST['anncontent']) && $_POST['anncontent']!='' )
{
$sql = "UPDATE settings SET ann=('".addslashes($_POST['name'])."') AND SET announcement=('".addslashes($_POST['anncontent'])."')";
//$sql = "UPDATE settings SET announcement=('".addslashes($_POST['anncontent'])."')";
if($conn->query($sql))
{
$response['success'] = true;
}
}
echo json_encode($response);
?>
index.php
<form action="" method="post">
<div> Show Announcement <input type="text" name="name" value="" /></div>
<div> Announcement Content<input type="text" name="anncontent" value="" /></div>
<div><button type="button" onclick="submitForm();" name="save_announcement" value="Save"/>Update</button></div>
</form>
</body>
<script type="text/javascript">
function submitForm()
{
var name = $('input[name=name]').val();
var anncontent = $('input[name=anncontent]').val();
if(name != '')
{
var formData = {name: name, anncontent: anncontent};
$('#message').html('<span style="color: red">Updating...</span>');
$.ajax({url: "https://localhost/admin/api/submit.php", type: 'POST', data: formData, success: function(response)
{
var res = JSON.parse(response);
console.log(res);
if(res.success == true)
$('#message').html('<span style="color: green">Successfuly updated.</span>');
else
$('#message').html('<span style="color: red">Error while updating.</span>')
}
});
}
else
{
$('#message').html('<span style="color: red">Please fill all the fields</span>');
}
}
</script>
Maybe the problem is in my sql call? I am not sure if that's the right way to update 2 columns in the same line.
I tried adding additional $sql call with only SET announcement but that didn't work. Same error code.
When I try to write something only in Show Announcement text field and press Update, I get #Error While updating# message (The one I set for if success = false) but when I try to set some content in another text field as well, I get a message "Updating..." and I get stuck on that.
https://prnt.sc/_MexIxx6dSdJ
Please, let me know if I need to provide more information for this case for you to understand the problem.
I would advice using !empty() "not empty", which does both checks for you.
Except that, you can bind 2 parameters doing something like:
if (!empty($_POST['name']) && !empty($_POST['announcement'])) {
$stmt= $pdo->prepare("UPDATE settings SET name = :name, announcement = :announcement");
$stmt->execute([
'name' => $_POST['name'],
'announcement' => $_POST['announcement']
]);}
Here is more about PDO

PHP - AJAX - is it possible to generate HTML using PHP and return that to AJAX to replace the contents of a <div>

I am working on a web application where it allows you to post a simple comment to the database on a form submit, what I want to do is generate a new list of all comments written and use AJAX to replace a div where comments are to be stored, this to show the newest written comment after submitting it.
$(document).ready(function() {
$('#postCommentForm').submit(function (e)
{
e.preventDefault();
console.log("JS Submitted");
function addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id)
{
$.ajax(
{
url : "funcsAJAX.php",
type : "post",
dataType : "json",
data : {
'commentTitleBox' : commentTitleBox,
'commentBox' : commentBox ,
'source_name' : source_name ,
'place_id' : place_id ,
'city_id' : city_id
},
success : function(response)
{
console.log(response);
$('#g').html(response);
},
});
}
var commentTitleBox = $('#commentTitleBox').val();
var commentBox = $('#commentBox').val();
var source_name = $('#source_name').val();
var place_id = $('#place_id').val();
var city_id = $('#city_id').val();
addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id);
});
});
This is the jQuery code I use to pull data from the form and post it to the webserver, note that the success part is unfinished as it never fired for me, #g is the div which contents I want to replace.
Next is the handler for the AJAX call
extract($_POST);
#addCommentAJAX_call handler
$user = 'user';
$pass = 'pass';
try
{
$db = new PDO('mysql:host=localhost;dbname=twincities;charset=utf8',$user,$pass);
}
catch(PDOException $e)
{
die("<h3>connection to be failed, not surprising really heres why ".$e->getMessage());
}
addComment($db,$city_id,$place_id,$commentTitleBox,$commentBox,$source_name);
$allComments = showCommentsForAJAX($db,$city_id,$place_id);
$db->connection = null;
echo json_encode($allComments);
This will create PDO object and then addComment() will add the comment to the database, it works fine with no issues.
showCommentsForAJAX() is the function I want to use that returns the comments from the database
function showCommentsForAJAX($db,$cityID,$placeID)
{
try
{
if($cityID && $placeID)
{
$query = "select * from comment where place_place_id = :place_place_id and city_city_woeid = :city_city_woeid";
$queryVars = ['place_place_id' => $placeID,'city_city_woeid' => $cityID];
}
else if($cityID)
{
$query = "select * from comment where city_city_woeid = :city_city_woeid";
$queryVars = ['city_city_woeid' => $cityID];
}
$query = $query." ORDER BY `timestamp` desc";
$stmt = $db->prepare($query);
$stmt->execute($queryVars);
$returnHTML = "";
$returnHTML = $returnHTML . '<div id=comments>';
while($comment = $stmt->fetch())
{
$returnHTML = $returnHTML . '<div id=commentIDis'.$comment['comment_id'].'>
<h3>'.$comment['title'].'</h3>
<br>
<p>'.$comment['content'].'</p>
<br>
<p>-'.$comment['source_name'].'</p>
<br>
';
$returnHTML = $returnHTML . '</div>';
}
$returnHTML = $returnHTML . '</div>';
return $returnHTML;
}
catch(PDOException $e)
{
die("<h3> ROLLBACK something broke, not surprising really heres why ".$e->getMessage());
}
}
I want to based off the entries in the database, to build the comments' HTML and return that to AJAX, I am not sure how to encode the result for AJAX to understand it, and I believe that the logic for $returnHTML is incorrect and there is a better method of doing what I want but I am not sure how to achieve that, I have done a similar thing using Flask before where I used jinja templating to generate the HTML and successfully replace the contents of a div, but due to this university project I need to use PHP.
Suggestions to code layout are also very appreciated

POST form with JQuery using $.post()

I have the following form
<form id="colorTest" method="POST">
<input type="text" id='responseText' name="responseText" value="">
<input type="button" id='confirm' name="confirm" value="confirm">
<input type='text' id="idNum" name="idNum">
<input type='text' id='correct' id="correct">
</form>
Only the value for #responseText is actually typed in, #idNum is passed from another page, while the other fields are filled by this function:
<script type="text/javascript">
var arr = [2,5,6,7,10,16,29,42,57];
x = 0
/* idNum is passed from another page to this one */
$(document).ready(function() {
document.getElementById('idNum').value = localStorage.memberID;
/* when something is typed in the form */
$('#responseText').on('input', function() {
/* the value is stored */
var response = document.getElementById('responseText').value;
/* and compared with the vector arr that contains the correct answers*/
if( response == arr[x]){
$("#correct").attr('value', 'yes');
}else{
$("#correct").attr('value', 'no');
};
});
/* confirm is the button to send the asnwer */
$('#confirm').click(function(){
$.post("testColor.php", $("#colorTest").serialize());
x = x + 1;
});
});
</script>
And here is my php:
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$response = $_POST["responseText"];
$memberID = $_POST["idNum"];
$timeStmp = time();
$correct = $_POST["correct"];
$sql = "INSERT INTO colorBlind (memberID, response, correct, timeStmp)
VALUES ('$memberID', '$response' ,'".$correct."','".$timeStmp."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn -> close();
?>
Now, I am sure the php is called correctly when the click event occurs on #confirm, because the timestamp invoked in the php is recorded in my db. Nevertheless, none of the value in the fields is passed in the php. Namely if do somethin like:
echo $_POST["idNum"];
I get back an empty field.
Anybody has any idea what I am doing wrong or any suggestions on how to debug it? I have been spending days on this without any progress.
The first thing I noticed is that your
<input type='text' id='correct' id="correct">
contains id="correct" twice. I'm sure you meant to add name="correct".
When you use $("#colorTest").serialize(), that will return
responseText=foo&idNum=bar&correct=foobar
I can see how this would be used for a GET request. But seeing as you're using $.post(), you'll want to pass in an object of key/value pairs for your POST data.
For example, this should work:
var params = {
responseText: 'foo',
idNum: 'bar',
correct: 'foobar'
};
$.post("testColor.php", params);

$(form id).serialize() returns empty string

I have a simple search form whose content I want to send to my php query as a POST request. I'm using AJAX to send it, and so far everything works fine, but for some reason instead of sending the actual value of the input field, it always sends an empty string.
Can someone please explain what I'm doing wrong here?
my html:
<form id="searchbox">
<input type="text" placeholder="author, title, keyword...">
<input type="submit" value="Search">
</form>
my js (the console.log line is there in order to see what's getting posted, ie for checking what's wrong with my code):
$("#searchbox").submit(function(e) {
e.preventDefault();
console.log($("#searchbox").serialize());
$.post(
"db_queries/all_articles.php",
$( "#searchword" ).serialize(),
function(data) {
console.log(JSON.parse(data));
} //end response function
); //end search article POST request
})
my php:
try {
$hostname = "localhost";
$username = "root";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
if (!empty($_POST)) {
$query = $db->prepare('SELECT * FROM articles WHERE title = :title');
$query->execute(array(':title' => 'test1'));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
else {
$query = $db->prepare('SELECT * FROM articles');
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your input tags must have a name attribute in order to be serialized.

Having an Ajax Save button and save in database

I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.
Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?
Not very sure with AJAX and all so Thanks for helping!
This is for the "Save" button.
<input type="button" onClick="save();" value="Save">
This is the insert query whereby it will be inserted in database.
<?php
include("dbFunctions.php");
$idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);
while ($row = sqlsrv_fetch_array($idResult)) {
$fcID = $row['id'];
$question = $row['question'];
$surveyTitle = $_SESSION['surveyTitle'];
$input = $row['input'];
if (isset($_POST['qns' . $fcID])) {
$answer = implode(",", $_POST['qns' . $fcID]);
$newAns = str_replace($singleQuote,$changeQuote,$answer);
} else {
$newAns = '';
}
if (isset($_POST['others'.$fcID])) {
$others = $_POST['others' . $fcID];
$newOthers = str_replace($singleQuote,$changeQuote,$others);
}else {
$newOthers = 'N.A.';
}
$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo);
if ($input != 'Normal text line, no input required*') {
$query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";
$status = sqlsrv_query($newconn, $query);
} }
if ($status === false) {
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
You can use jquery $.ajax() to send data from client side to PHP. (eg)
$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});
Then in PHP page, use $_POST[] to capture data and insert it into database.
$id = $_POST['id'];
$name = $_POST['name'];
Make sure you escape the values and make it safe for sql insert.

Categories