Trouble inserting data with PHP and Jquery - javascript

I have been at this for few hours now and need some help. I am a little new to jquery - it seems straightforward enough, but I can't get this to work. If I submit the data through a form straight to the php page, it works perfectly, but I can't get the ajax to execute. It is pretty simple with just one variable to send for marking an item for review. Any help is appreciated.
<input type="hidden" id="flag_item" name="flag_item" value="<?php echo $row[0]; ?>" />
<input type="button" class="grn_button2" id="report_btn" name="report_btn" onclick="MM_changeProp('flag1','','display','none','SPAN'), MM_changeProp('flag2','','display','inline','SPAN')" value=" Report Item "/>
the jquery code
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click','#report_btn',function(e) {
var data = $("#flag_item").val();
$.ajax({
data: data,
type: "POST",
url: "flag.php",
success: function(data) {
alert("Item has been reported");
}
});
});
});
</script>
and the php
$flag_item = mysqli_real_escape_string($dbgo, $_POST["flag_item"]);
$query = "SELECT flag FROM listings WHERE item_num = '$flag_item'";
$result = mysqli_query($dbconnect, $query);
if(!$result){
die('Invalid query: ' . mysql_error());
}
$row = mysqli_fetch_row($result);
$new_row = $row[0] + 1;

You missed param name here:
var data = $("#flag_item").val();
Try this:
var data = {"flag_item":$("#flag_item").val()};

I got it working now. I ditched the jquery I was using and started over. This jquery code is working.
$('#flag_form').submit(function(){
return false;
});
$('#flag_form').click(function(){
$.post(
$('#flag_form').attr('action'),
$('#flag_form :input').serializeArray(),
function(result){
alert("Item has been reported");
}
);
});
I also added the form tag and the action to input fields. Thank you for trying to help, I appreciate it.

Related

How to store div content to DB with Ajax

In my project, I want to store div content to DB. The content is like:
<span>name:</span><input type="text" id="inputid" value="John"><br />
So I chose innerHTML to fetch them successfully. And with Ajax, the content would be stored to DB.
Yesterday, I found that stripslashes() should be called to format the content, and it could be updated successfully.
But today stripslashes() made nothing done. Here is my js code:
var slcId = $('#slcStNum').val();
var tmTgDvHtml=document.getElementById("timeTagDiv").innerHTML;
$.ajax({
dataType:'html',
type:"POST",
url:"get_ajax_csc_div.php",
data:{htmlCnt:tmTgDvHtml,slcId:slcId},
success:function (data)
{
alert("test");
}
});
Here is html code:
<div id="timeTagDiv"><span>name:</span><input type="text" id="inputid" value="John"><br /></div>
Here is get_ajax_csc_div.php code
<?php
if(isset($_POST['htmlCnt']))
{
include("DB.php");
$htcnt=stripslashes(".$_POST['htmlCnt'].");
$sql="update IDC SET stprocess='$htcnt' where id='".$_POST['slcId']."';";
$sel = $conn->exec($sql);
}
?>
I changed dataType:'html' to dataType:'json', but it failed again. Who can help me?
It's because you have your _POST[] superglobal surrounded by quotes, making it a string.
Change this
$htcnt = stripslashes(".$_POST['htmlCnt'].");
With this
$htcnt = stripslashes($_POST['htmlCnt']);
change your get_ajax_csc_div.php to
include("DB.php");
if(isset($_POST['htmlCnt'])) {
$htcnt = stripslashes($_POST['htmlCnt']);
$sql = "update IDC SET stprocess='$htcnt' where id='".$_POST['slcId']."'";
$sel = $conn->exec($sql);
}

working with ajax, mysql and php

I have to transfer data from one div to another, I am using AJAX to do this.
<script type="text/javascript" src="lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#aq").click(function(){
var name1 = $("#n1").val();
$.ajax({
type: "POST",
url: "risultato.php"
data: "name1=" + name1 ,
dataType: "html",
success: function(msg)
{
$("#risultato1").html(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...");
}
});
});
});
</script>';
<form name="modulo1'.$dationennx['id'].'">
<input type="hidden" name="name1" value="'.$dati['id'].'"
id="n1'.$dationennx['id'].'">
<a href="javascript:rispondithread(\'homeq\');"
id="aq">'.stripslashes($dationennx['oggetto']).'</a><br>
</form>
<script>
function rispondithread(h) {
$("#rispondithreadforum").attr("style", "display:block;");
}
</script>`
I am fetching the data from my table from the 'risultato.php' page, which i want to use to show a textarea on my main page with the fetched data.
<?php
$nome = $_POST['name1'];
$query = "SELECT * FROM login2.podcast
WHERE login2.podcast.id = '$nome'
ORDER BY login2.podcast.data DESC";
$dati = mysql_query($query);
while($ris = mysql_fetch_array($dati) ){
echo'
<textarea class="form-control textareaabc" readonly tabindex="8">'.stripslashes($ris['testo']).'</textarea>';
}
?>
It doesn't work if i try to fetch the data using mysql_query, but it does when i try echoing the post data in the page.
$nome = $_POST['name1'];
echo $nome
This writes the '$nome' variable in my main page.
$nome = $_POST['name1'];
echo'<input type="text" value="'.$nome.'" name="nome">';
i don't understand this. why it doesn't work? what's wrong?
It is highly likely that there is no data for the '$nome' variable in your table
Make sure that you are actually receiving data from the database, does it print out the textarea? If not, you do not have any id in your podcast table table matching the '$nome' variable.
Testing your code
Try checking if you actually get anything back when you print something out in that page, could you possibly be pointing to the wrong page?
other
Overall, i would recommend using PDO or atleast mysqli, MySQL is no longer supported since PHP 7 and deprecated since PHP 5. See: PHP.net documentation about mysql extension
sorry, i forget to include the connection to the database into the file risultato.php :P
thanks to everybody

Updating div content with jQuery ajax function over PHP

I am trying to update my div content (#update_div) by sending the value of two input fields to a php file (search_value.php) using the .ajax() function from jQuery.
It works, if I just redirect the two values of the input fields using the html form POST method. So the search_value.php should be correct.
My HTML Code:
<form id="my_form">
<input id="food" name="food">
<input id="amount" value="amount in gram" name="amount">
<input type="button" value="Update" id="submit" name="submit" />
</form>
<div id="update_div">
</div>
My Javascript Code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'GET',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data);
}
});
});
My PHP Code:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $GET_['food'];
$amount = $GET_['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
I do not really get a feedback by clicking the button. Maybe you guys can tell me why?
For GET request, there should not be data part, make it as a query string as below js code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php?food='+ food + '&amount='+amount,
type: 'GET',
datatype: "html",
success: function(data)
{
$('#update_div').html(data);
},
failure : function(ex)
{
console.log(ex);
}
});
});
And use $_GET instead of $GET_ in php
Are you running your code after the page has loaded? I've made that mistake several times, and if you're not, I suggest wrapping the whole thing in a $(function(){ /* Everything you have */ });
I prefer using post
in your php script replace $GET_ by $_POST
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $_POST['food'];
$amount = $_POST['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
in your javascript code the result is found in data.responseText
here the new script
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'POST',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data.responseText);
}
});
});
Tested and your JavaScript code works. The issue may be in the PHP code.
Have you tried correcting the "$_GET" as suggested by others?

Like system: Looping forms unique id, getting these id's with jQuery/Javascript to post Individually

I'm just messing arround with simple PHP and Java by building my own Like system IP based.
Tryed looking for a solution, but no luck so far.
HTML generated forms in a while loop in php EOT obviously with every form unique id's. There are 25 forms with a Like button present. These forms are within a Bootstrap Modal. So because it is in a Modal, I do not want it to refresh the page and reset my Show More list. There for I'm trying to get all forms to be able to submit a Like by id by item using javascript. Code below.
Any suggestions or different approaches?
HTML - PHP While loop (forms within Modals):
<p id="result{$itemID}"></p>
<form enctype="multipart/form-data"
action="{$postLike}"
id="myform{$itemID}"
name="{$itemID}"
method="post">
<input type="hidden"
name="itemids"
value="{$itemID}">
<input type="hidden"
name="ips"
value="{$ips}">
<button id="submit-btn{$itemID}"
class="btn btn-{$optionLikeColor}" {$optionLikeDisabled}>
<span class="glyphicon glyphicon-thumbs-up glyphr"
aria-hidden="true">
</span> {$optionILikeText} {$likes}
</button>
</form>
PHP:
<?php
require 'init.php';
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['itemids'])){
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$itemsid = mysqli_real_escape_string($link, $_POST['itemids']);
$itemsip = $_SERVER['REMOTE_ADDR'];
if ($result = mysqli_query($link, "SElECT * FROM likes WHERE itemID='$itemsid' AND ip='$itemsip'")) {
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0){
echo 'You\'ve have already liked this item.';
} else {
$sql = "INSERT INTO likes (itemID, ip) VALUES ('$itemsid', '$itemsip')";
if(mysqli_query($link, $sql)){
echo 'Thank you!';
} else {
echo 'Something went wrong, try again later!';
}
}
}
} else {
echo 'Something went wrong, try again later!';
}
mysqli_close($link);
?>
Javascript working, but only for the first form:
So i'm guessing I need to pass the form / id variable into: $('#myform'), $('#insert'), $('#myform :input') and $('#result')
$('#myform').submit(function(){
return false;
});
$('#insert').click(function(){
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
Javascript concept not working obviously:P Suggestions?
$("[id^='myform']").submit(function(){
var ID = $(this).attr('name');
return false;
});
$(document).ready(function(){
$(document).on('click','#submit-btn'+ID,function(){
$.post(
$('#myform'+ID).attr('action'),
$('#myform${ID} :input').serializeArray(),
function(result){ $('#result'+ID).html(result); }
);
});
});
Give all your forms the same class, or have some way to uniquely select those forms. You don't need unique ids for all those elements.
Then:
$(".myFormClass").on("submit", function () {
var $f = $(this); // the form that got submitted
$.post(
$f.attr('action'),
$f.find('input').serializeArray(),
function(result){
// not sure where you wanted the result.
// The point is that you should select it relative to the form $f that you already know.
$f.find('span').html(result);
}
);
});
Works like a charm! Thanks!
$('.myFormClass').submit(function(){
return false;
});
$('.myFormClass').click(function() {
var $f = $(this);
$.post(
$f.attr('action'),
$f.find('input').serializeArray(),
function(result){
$f.find('#submit-btn').remove(),
$f.find('#result').html(result);
}
);
});

asynchronous commenting using ajax

I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.

Categories