php query not being processed that has been delivered by ajax post - javascript

I got two pages:
Page 1:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$('#mR-RateableFramePicture').dblclick(function () {
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function() {
}
});
});
</script>
Page 2:
<?php
session_start();
$userID = $_SESSION["ID"];
$ratedUserID = $_POST['rateableUserID'];
$ratedPictureID = $_POST['rateablePictureID'];
include '../../scriptMysqli.php';
$sql = $conn->query("UPDATE styles SET savedByUser = '$userID' WHERE userID = '$ratedUserID' AND pictureID = '$ratedPictureID'");
?>
<script>alert("success");</script>
But the $sql variable never gets executed and the part with the alert is not being shown on the original page (page 1) eiher :/
What am I doing wrong here?

From the comments the changed code:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
$('#mR-RateableFramePicture').dblclick(function () {
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function(scriptCode) { $('body').append(scriptCode); }
});
});
</script>
The important line is the success handler. It takes the response from your ajax call (echoed by your php script) and add it to the DOM, so it will executed in case of javascript code.

Related

How to get rid from the same id in while loop when submitting form using ajax

I am submitting form using ajax in the while loop but because of loop the same form id is using many times , so as a result the form is submitting only once . I think i have to make unique id every time in the loop for the form but don't know how.
Here is my code so far,
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form id="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$("#subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
submit_subcmt.php
<?php
$comtr_id =$_POST['comtr_id'];
$comment_id =$_POST['comment_id'];
echo $comtr_id;
echo $comment_id;
?>
Try this.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$(".subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
To illustrate the comment I made above you could try something similar to this perhaps.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while( $row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC) ){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?> <!-- use a class attribute here -->
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php
}//end loop
?>
<script src="jQuery v2.1.1"></script>
<script>
/* and assign event handlers to form objects with this class as per above */
$("form.subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(),
success: function(data) {
alert(data);
}
});
});
</script>

how to pass checkbox value to text input using Ajax and PHP?

I'm trying to evaluate the values of all checked checkboxes and pass the result
to html text input I'm trying to do that using php and ajax but I have no good result please help
this is my code:
$(document).ready(function ()
{
$("#check").click(function ()
{
var data = $("#check").val();
//get selected parent option
$.ajax(
{
type: "GET",
data:data,
url: "total.php?val="+data,
cache: false,
success: function (data)
{
$("#tot").html(data);
}
});
});
});
</script>
</head>
<?php
$conn = mysqli_connect("localhost", "root", "", "voucher_test");
$result = mysqli_query($conn, "SELECT * FROM vouchers where cat_id = 1");
while ($row = mysqli_fetch_array($result)) {
$userSet[] = $row;
}
?>
<form action="index.php" method="post">
<?php
foreach ($userSet as $key=>$value){
echo $value['service_name']."<input type='checkbox' id='check' name='{$value['service_name']}' value='{$value['service_price']}'>";
}
?>
<br>
<div id="tot"></div>
</form>
and this is total.php
<?php
$itot = 5;
$itot+=$_GET['val'];
echo"<input type='text' value='$itot'>";
You can use this code to sent value to server y o n
var data = ($("#check").is(":checked") ? 'y' : 'n';
If you want send the value of checkbox, try this code:
var data = new FormData();//Create FormData
if($("#check").is(":checked")){//Verified if the input os checked
data.append('data-check',$("#check").val());//Add data of the checkbox to FormData
}
$.ajax(
{
type: "GET",
data: data,
url: "total.php",
cache: false,
success: function (data)
{
$("#tot").html(data);
}
});
In yur php
$_GET['data-check'];
I don't think you need to use the total.php file, but if you really want to use it I recommend to change your code to this:
<?php
$itot = 5;
$itot+=$_GET['val'];
echo"<input type='text' value='" . $itot . "'>";
The only change is the concatenation of the string you are printing

Ajax form submission inside modal box

Ok here is a strange little problem:
Here is a test page, which user clicks to open:
When user clicks view results I have 3 selectboxes inside the modal box.
box1 => populates =>Box 2 => populates Box 3
My problem
When user clicks submit, instead of results being displayed from the query based on selectbox selections, the test page opens again inside the modalbox... as you can see in below image
On submit
Any idea why when form is submitted current page opens inside modalbox?
Submit Form
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) { $('#resultForm').append(data); }
});
}
});
</script>
Populate Textboxes
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm" action="result.php">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
Display result
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
$sql="Select * FROM Multiple_Picks WHERE tournament ='$tour' AND round='$round' GROUP BY member_nr";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result)){
$memNr = $row['member_nr'];
$pick = $row['pick'];
$score = $row['score'];
?>
echo $memNr;
echo $pick;
echo $score;
}
}
?>
It would appear that:
success: function(data) { $('#resultForm').append(data); } you are telling it to put the ajax response in the resultForm, which appears to be inside your modal. Is that not what is happening. Hard to tell from your question and code what SHOULD be happening vs what IS happening now.

Ajax delete data from database function not working

I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>&nbsp&nbsp<input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span> &nbsp&nbsp<input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}

is there a way to populate other textbox when onchange?

here's my code. I'm new to php. so sorry in advance.
I actually want to check my input in txtbarcode and if it is existing in my database I would like to populate the txtdescription but I don't know how to do it or is it even possible?
<?php
$barcode = $_POST['txtbarcode'];
$query = "SELECT * FROM product WHERE product_id = '$barcode'";
$query_exe = mysql_query($query);
$chk_query = mysql_num_rows($query_exe);
if($chk_query > 0)
{
$row = mysql_fetch_assoc($query_exe);
?>
<th class = "textbox"><input type = "text" name = "txtbarcode" value = "<?php echo $row['product_id']; ?>" style="width:80px"/></th>
<th class = "textbox"><input type = "text" name = "txtdescription" value = "<?php echo $row['product_name']; ?>" style="width:100px"/></th>
<?php
}
?>
You can do this using JQuery Ajax. Just using the change listener on the barcode field, it will send an ajax call to the check_barcode file - which will query the table and echo the data you want. The result will then be placed into the other textfield via JavaScript :).
The following is a separate PHP file.
<?php
//-----------------------------------
//check_barcode.php file
//-----------------------------------
if (isset($_POST['barcode'])) {
$query = mysql_query("SELECT * FROM product WHERE barcode = '".$_POST['barcode']."'");
$num_rows = mysql_num_rows($query);
if ($num_rows > 0) {
$row = mysql_fetch_assoc($query);
echo $row['product_name'];
}
}
?>
The following is your HTML and JavaScript code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#txtbarcode').change(function() {
var barcode = $(this).val();
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
success: function(result) {
$('#txtdescription').val(result);
}
});
});
});
</script>
<input type="text" name="txtbarcode" id="txtbarcode" />
<input type="text" name="txtdescription" id="txtdescription" />
UPDATE: Returning more data, and populating extra fields.
You'll need you echo a json array from the php script which contains both of the values.
For example:
echo json_encode(array('product_name' => $row['product_name'], 'unit_measure' => $row['product_name']));
and then within the JavaScript
<script>
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
dataType: 'json',
success: function(result) {
$('#txtdescription').val(result.product_name);
$('#unitofmeasure').val(result.unit_measure);
}
});
</script>

Categories

Resources