Sorry for disturbing again with my very basic question. First of all, sorry if my English is a little bit hard to understand. My current situation is I want to do a popup modal in my drag and drop boxes. In my popup modal, I can view and edit the details of the user based on what we click in the button in the box. The problem is, I cannot SELECT the data by id. But, when I SELECT all the data, the data appear in the modal boxes. But, it appears all the data. I just want the selected id. Back to my question for past few days, I've redo again to get more understanding on this popup modal part. I've done ajax and a little bit JavaScript, also, I tried to debug my code just what I've been told but I got an error saying "Parameter is missing" . What is causing by that ? I've done some reading about parameter but I still don't get the actual understanding about it. Can someone give an idea what is actually parameter is missing . And what I suppose to do by it?
Here what I've tried so far.
This is the button
<button data-id="<?php echo $row['userid'];?>" data-target="doubleClick-1" class='jobinfo' type='button' id='btnInfo' ondblclick="document.getElementById('doubleClick-1').style.display='block'">Info</button>
This is the modal popup
<div id="doubleClick-1" class="modal">
<label class="tabHeading">User Info</label>
<div class="contentTechJobInfo">
<div class="tech-details">
<div class="techClose" onclick="document.getElementById('doubleClick-1').style.display='none'" >×</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.jobinfo').click(function() {
var userid = $(this).data('userid');
// AJAX request
$.ajax({
url: 'ajaxhome.php',
type: 'post',
data: {userid: userid},
success: function(response) {
// Add response in Modal body
$('.tech-details').html(response);
// Display Modal
$('#doubleClick-1').modal('show');
}
});
});
});
</script>
This my ajaxhome.php
<?php
$connection = mysqli_connect("", "", "");
$db = mysqli_select_db($connection, '');
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$userid = intval($_GET['userid']);
$query = "SELECT * FROM user WHERE userid ='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
while ($row = mysqli_fetch_array($query_run)) {
?>
<div class="input-box">
<label for="">Name</label>
<input type="text" id="username" name="username" value="<?php echo $row['username']?>">
</div>
<div class="input-box">
<label for="">Number</label>
<input type="text" id="usernumber" name="usernumber" value="<?php echo $row['usernumber']?>">
</div>
<div class="input-box">
<label for="">Class</label>
<input type="text" id="userclass" name="userclass" value="<?php echo $row['userclass']?>">
</div>
<button type="submit" id="submit" name="update" class="btn btn-primary"> Update Data </button>
<?php
if (isset($_POST['update'])) {
$username = $_POST['username'];
$usernumber = $_POST['usernumber'];
$userclass = $_POST['userclass'];
$query = "UPDATE user SET username='$username', usernumber='$usernumber', userclass='$userclass' WHERE userid='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
echo '<script> alert("Data Updated"); </script>';
header("location:homepage.php");
} else {
echo '<script> alert("Data Not Updated"); </script>';
}
}
} ?>
<?php
}
?>
In short, I think the problem comes from these lines of code in your modal:
var userid = $(this).data('userid');
you should replace it with
var userid = $(this).data('id'); // you should pass 'id' to .data() function instead of 'userid'
With your current code userid variable in your modal will always be undefined. It means it wont exist in $_GET when you send ajax request to PHP. And it causes your ajaxhome.php moves to die("Parameter is missing!");.
To get data-xxx attribute with jQuery, you should use pass 'xxx' to .data() function.
var xxx = $(this).data('xxx');
In your button, you are storing userid in data-id attribute
<button data-id="<?php echo $row['userid'];?>"
so if you need to get that userid you should pass 'id' into .data() function
Update:
In your ajax, you are using type: 'post', so in your php code you should check $_POST instead of $_GET
I don't think the value of user has been obtained
var userid = $(this).data('userid');
you can try
var userid = $(this).data('id');
Related
I try to post my form to Mysql without refreshing page. I did these with looiking sources but not working. Could you help me?
<script>
$('#submit').click(function() {
$.ajax({
url: 'submit.php',
type: 'POST',
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
});
});
</script>
<form method="post">
<textarea name="message" rows="3" cols="30">
</textarea><br><br>
<input type="submit" value="Submit">
</form>
Submit.php
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}?>
In jQuery, the click event is being triggered on an element that has an id of submit (it is id because it is represented by #)
$('#submit').click(function() {
Your submit button does not have the ID of "submit"
Change the input tag as follows:
<input id="submit" type="submit" value="Submit" />
Another problem, as #Rajan in comments pointed out, you have an extra brace. So, change:
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
to:
data: {
message: '*I couldnt find this partwhat should i write*'
}
Also, I recommend that you show return some kind of message from submit.php page, for example:
echo 'Entry Added';
The above is just an example output to get you going... you really should be doing checks such as: did the entry get inserted without any errors, etc.
Edit
Also note: you are using type as one of the settings. Per the official jQuery documentation of jQuery.ajax(), type is:
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
(i.e. use method instead, if using jQuery version >1.9.0)
Lastly, take a look at the answer provided by #Faisal as well...
You are submitting form data through Ajax query, hence you do not need to include header('Location: ' . $_SERVER['HTTP_REFERER']); in your submit.php file.
<form>
<textarea name="message" rows="3" cols="30"></textarea>
<br>
<input type="submit" value="Submit">
</form>
<script>
$(document).ready( function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
$.post("submit.php", $("form").serialize()); // Post the data
$('textarea[name=message]').val(''); // Clear the textarea
});
});
</script>
Also, are the variables $a and $b defined in submit.php file?
$.post('../submit.php',{message:message}, function(data) {
$('.results').html(data);
});
use a div where you want to display the result
<div class="results"></div>
to finish your submit.php have to send something at the end so try this
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}
echo "it works";
?>
I'm trying my best to get this to work. But AJAX is pretty new to me. So hang in there...
Ok, I've asked a couple of questions here about getting this issue that I'm having to work. I (We)'ve come a long way. But now the next issue is here.
I'm trying to echo a session in a div using AJAX.
The AJAX code is working, I can echo plain text to the div I want it to go. The only problem I have is it does not display the title of the item.
I have some items (lets say 3 for this example) and I would like to have the custom save the Items in a Session. So when the customer clicks on save. The ajax div displays the title. And if the custom clicks the 3rd item it show the 1st and 3rd item, etc...
My HTML:
<button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-<?php the_ID(); ?>" data-attribute="<?php the_title(); ?>" data-whatever="<?php the_title(); ?>">Sla deze boot op <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
My AJAX code:
$(".ajaxform").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "example.com/reload.php",
success: function(data) {
$(".txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
My PHP reload.php:
<h4>Saved Items</h4>
<p>Blaat...</p>
<?php echo "Product Name = ". $_SESSION['item'];?>
I saw this code on here: I'm not using this code. Only wondering if I can use it for my code, and then how?
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
How I'm getting my title();:
<?php
// Set session variables
$_SESSION["item"][] = get_the_title();
?>
Is this some thing I can use? And could someone help me with the code?
Thanks in advance!
I'm not too sure on what exactly you're trying to accomplish, but here's a quick and dirty example of making an HTTP request (POST) with a name of a product, storing it in a PHP session, and outputting all product names in the session:
HTML
<p>Product A <button class="add-product" data-product="Product A">Add Product</button></p>
<p>Product B <button class="add-product" data-product="Product B">Add Product</button></p>
<p>Product C <button class="add-product" data-product="Product C">Add Product</button></p>
<div id="response">
</div>
JavaScript
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('addProduct.php', {productName: productName}, function(data) {
$('#response').html(data);
})
});
PHP (addProduct.php)
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Your added products:</h4>
<ul>
<?php foreach ($_SESSION['products'] as $product): ?>
<li><?php echo htmlspecialchars($product); ?></li>
<?php endforeach;?>
</ul>
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){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
});
});
</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
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');
}
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.
html() in your function replacing current html with your comment html, thats why u see only new comment. Change your method to append().
$("#comment_part").append(html);
Change this line
$("#comment_part").html(html);
to this
$("#comment_part").html('<div class="comment" >' + $('#userInput').val() + '</div>' + $("#comment_part").html()).promise().done(function(){$('#userInput').val('')});
I have blog post list and that post have comments. Posts and comments i loop with foreach from database.So i have problem when i want to create new comment via ajax. I have form and one hidden field for holding post id.
When from jquery i try to access to that element post_id is all time the some. I try on submit to debug with alert to see witch post_id will be returned. All time return 270. And when i click to other post comment submit id is not changed.
Posts and comments
<?php foreach($posts as $post): ?>
<h1><?= $post->title; ?></h1>
<p><?= $post->text; ?></p>
<?= if($comments = postComments($post->id): ?>
<?= foraech($comments as $comment): ?>
<form id="post_add">
<input type="text" placeholder="Say somthing..." name="comment">
<input type="hidden" name="pid" class="pid" value="<?= $post->id">
<input type="submit">
</form>
<?= endforeach; ?>
<?= endif; ?>
<?= endforeach; ?>
submiteComment: function() {
var comment_form = $("#comment_add");
var comment_text = $(".comment_text");
var pid = $(".pid"); // post id
$("body").on("submit", comment_form, function(e) {
e.preventDefault();
alert(pid.val()); // debug all time return 270 for all comments
if($.trim(comment_text).length) {
$.ajax({
type: 'post',
url: baseurl + '/comment/create',
data: {item_id: post_id.val(), comment_text: comment_text.val()},
success: function(data) {
alert('success');
},
error: function(t, r, j) {
alert(r.responseText);
}
})
}
});
Because you are giving each of the post id fields in the form the same name and class, when you access it like this:
var pid = $(".pid");
You will receive all three of the pid elements for your comments into the variable pid. When you do pid.val() it will just return the value of the first one, which is why you will always be seeing the same pid no matter which comment you submit.
I have this code to insert some data that comes from a while, in a db. I'm trying to use jQuery serializearray and jQuery post together. But it seems I do some errors
$query= "SELECT * FROM barcode_prodotti";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo'
<input type="text" name="prodotto[]" class="prodotto" value="'.$row["prodotto"].'"></div>
<input type="text" name="prezzo[]" class="price" value="'.$row["prezzo"].'">
<input type="text" name="quantita[]" class="price" value="'.$row["quantita"].'">';
}
?>
<script src="js/mine.js"></script>
<button>Serialize form values</button>
</form>
<div id="results"></div>
This is my jQuery code I put in mine.js
$(document).ready(function(){
$('form').submit(function(msg) {
var mia =$(this).serialize();
$('#results').text(mia)
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("testtest.php",$(this).serializeArray(),function(data){
alert(data);
});
return false; });
});
This is my php file (testtest.php)
mysql_connect("localhost","root","");
mysql_select_db("db");
$arr = $_POST;
$sql="INSERT INTO table VALUES(
'".$arr['prodotto']."',
'".$arr['quantita']."',
'".$arr['prezzo']."'
)";
$rssql = mysql_query($sql);
?>
So I the serialize is ok (i tried to assign in a div a value to see if it was ok), but I can't insert values in my db
Your INSERT query ends up looking like this after variable substitution.
INSERT INTO table VALUES( 'product', '123', '321')
If your table has exactly three columns this will work fine. Otherwise it will fail. You may wish to use this query instead.
INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')
which enumerates the columns where you want your data.
After doing an insert (and after any query) you should check for errors. This can be done with code like this.
$res = mysql_query($q);
if ($res === false) {
echo $mysql_error ();
}
Note well: The mysql_xxx() interface is being removed from PHP for a good reason: it is vulnerable to cybercriminals. Please adopt mysqli_xxx() or PDO as soon as possible.
The simplest way to do this:
<form id="myform" method="post">
<input type="text" name="prodotto" id="prodotto">
<input type="text" name="prezzo" id="prezzo">
<input type="text" name="quantita" id="quantita">
</form>
Jquery is pretty simple too:
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'url/to/yourfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res); //the ajax response. you can alert it or whatever...
});
You can parse the fields in the ajax file like that:
yourfile.php
<?php
$product = mysql_real_escape_string($_POST["prodotto"]);
$prezzo = mysql_real_escape_string($_POST["prezzo"]);
$quantity = mysql_real_escape_string($_POST["quantita"]);
//here you have the variables ready to add them as values to database
$ins = "INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')";
mysql_query($ins);
?>