i'm a beginner with databases, ajax and php. I want a user to make a choice from a list with checkboxes and when a choice is made, the choice is sent to the database. I have this code:
<form method="post" action="post" class="registry-form">
<div class="list">
<div>
<input id='label-1' type='checkbox' />
<label for='label-1'>
<h3>
<span>Studio Noos Mom Bag | Urban Woollish</span>
<span>
<br />
Bekijk product
</span>
</h3>
</label>
</div>
...
</div>
</form>
<input type="submit" class="gift-btn" value="submit choice" />
<script>
$(document).ready(function() {
$(".list div input[type=checkbox]").change(function() {
$(this).parent().toggleClass('checked');
});
$('.registry-form').submit( function(e) {
e.preventDefault();
var geboortelijst_beschrijving = $(".list .checked h3 span:first-child").html();
console.log(geboortelijst_beschrijving);
$.ajax({
type: "POST",
url: "post.php",
dataType:'json',
data: geboortelijst_beschrijving,
success: function(data){
$(".list .checked").addClass('taken');
}
});
return false;
});
});
</script>
post.php:
<?php
header("Content-Type: application/json", true);
$conn = mysqli_connect("localhost","root","root","geboortelijst");
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$geboortelijst_beschrijving = $_POST['geboortelijst_beschrijving'];
//$geboortelijst_beschrijving = mysqli_real_escape_string($conn, $_POST['geboortelijst_beschrijving']);
if(mysqli_query($conn, "INSERT INTO geboortelijst(geboortelijst_beschrijving, geboortelijst_status)
VALUES('" . $geboortelijst_beschrijving . "', '1')")) {
echo '1';
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn);
?>
The response i get from post.php is always 200 0K, but i have no idea why the "geboortelijst_beschrijving" is not being sent to my database. This value is empty and i always and only get "1" (which of course comes from geboortelijst_status).
Anybody have some insights?
$(".list .checked h3 span:first-child") is not the correct selector. This is looking for an h3 that's contained in the checkbox element, but checkboxes aren't containers.
You want the h3 that's a sibling of the checkbox, not a descendant, and then find the first span in that.
var geboortelijst_beschrijving = $(".list .checked").siblings("h3").find("span:first-child").html();
Something like this
$(document).ready(function() {
$('.registry-form').submit( function(e) {
e.preventDefault();
let checkboxes=$.find("input[type='checkbox']");
for(let i=0; i<checkboxes.length; i++)
{
let checkbox=checkboxes[i];
let id=checkbox.getAttribute("id");
if (id!=null && id.contains("label-") && checkbox.checked)
{
let label=$.find("label[for='"+id+"']")[0];
if (label!=null)
{
var geboortelijst_beschrijving = $(label).html();
console.log(geboortelijst_beschrijving);
$.ajax({
type: "POST",
url: "post.php",
dataType:'json',
data: "geboortelijst_beschrijving="+geboortelijst_beschrijving,
success: function(data){
$(checkbox.parentElement).addClass('taken');
}
});
}
}
}
})
});
Related
I want to get the value of jquery in php form in popup.
my jquery is
$(document).ready(function(){
$("#submit").click(function() {
var mobileNumber = $("#mobileNumber").val();
if(mobileNumber=="")
{
alert("Please Enter Mobile Number");
}
else
{
$.ajax({
type: "POST",
url: "<?php echo base_url('test'); ?>",
data: {mobileNumber: mobileNumber},
success: function(result){
if(result){
$("#enter-otp").modal('show');
}
}
});
}
return false;
});
});
I want to print var mobileNumber value in enter-otp id popup in same page
so i write
<?php echo $mobileNumber; ?>
but it is not showing
If you want to enter value in enter-otp id popup in same page. You dont want any PHP script you can do it by jquery only. (Although You can write in success of ajax). Suppose you have div tag with id of otp-div inside enter-otp. You can write following code
success: function(result){
if(result){
$("#enter-otp").modal('show');
$("#otp-div").html(mobileNumber);
//OR ifotp-div inout attribute then use `val()`
$("#otp-div").val(mobileNumber);
}
}
depending on what gives you back your "result"-variable, you can output data.
so if your "result"-variable gives you back something useful, you can take this data and put it in the html like this.
success: function(result){
if(result){
$("#enter-otp").html(result).modal('show');
}
}
regarding to your edit, this would be a simple solution:
success: function(result){
if(result){
$("#enter-otp").html(mobileNumber).modal('show');
}
}
i picked up your code and run it on localhost. and after few changes, i got it working. to try following:
test.php
<form action="" method="post">
<input id="mobileNumber" type="text" name="mobileNumber" value="" placeholder="">
<input id="submit" type="submit" name="" value="submit">
</form>
<div id="enter-otp" style="display: none; border: 1px solid red;"></div>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var mobileNumber = $("#mobileNumber").val();
if (mobileNumber == "") {
alert("Please Enter Mobile Number");
} else {
$.ajax({
type: "POST",
url: "result.php",
data: { 'mobileNumber': mobileNumber },
success: function(result) {
if(result){
$("#enter-otp").show();
$("#enter-otp").html(result);
} else {
alert("no data received");
}
}
});
}
return false;
});
});
</script>
result.php
<?php
if( isset($_REQUEST['mobileNumber'] )){
echo $mobileNumber = $_REQUEST['mobileNumber'];
} else {
echo "no data";
}
?>
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
I want to pass the jquery value "selected" to fetchdata.php without reloading the page.
How can I do this?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.min.js" type="text/javascript">
</script>
<script>
$(document).ready(function() {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass() {
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if (selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" + selected, //The data your sending to some-page.php
success: function()
{
console.log("AJAX request was successfull");
},
error: function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
} else
{
alert("Please at least one of the checkbox");
}
}
</script>
</head>
<body>
<div id="checkboxlist">
<div><input type="checkbox" value="1" class="chk"> Value 1</div>
<div><input type="checkbox" value="2" class="chk"> Value 2</div>
<div><input type="checkbox" value="3" class="chk"> Value 3</div>
<div><input type="checkbox" value="4" class="chk"> Value 4</div>
<div><input type="checkbox" value="5" class="chk"> Value 5</div>
<div>
<input type="button" value="Get Value Using Class" id="buttonClass">
</div>
</html>
fetchdata.php
<?php
foreach($_GET['val'] as $r)
{
print_r($r);
}
?>
I am using the GET method to receive the data and the for-each loop to print the array, but I am not getting any values in the PHP file.
change the ajax function like below and make sure about the fectdata.php in the same folder or give the correct path.
$.ajax({
url: 'fetchdata.php',
type:'GET',
data: {val:selected},
success: function(data) {
console.log("AJAX request was successfull");
}
});
Check if the path to your script is correct:
url: 'fetchdata.php',
Is this script in your doc root?
change the following in your code,
in fetchdata.php
<?php
$valArray = explode('#',$_GET['val']);
foreach($valArray as $val){
echo $val."<br/>";
}
?>
In html File,
$(document).ready(function () {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass(){
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if(selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" +selected.toString(), //The data your sending to some-page.php
success: function(data1) {
$("#resultDiv").html(data1);
console.log("AJAX request was successfull");
},
error:function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
}else
{
alert("Please at least one of the checkbox");
}
}
include the div after a button like
<div id="resultDiv"></div>
I am confused a little bit and I have no clues what am I looking for.
Although I will post here important parts so you may figureout and help me.
A part of PHP file:
if (empty($vid) || empty($entry)) {
$broken = TRUE;
}
if(!$broken) {
$video = parseVideoEntry($entry);
echo "
<div class=\"video_wrap\">
<div class=\"video_thumbnail\">
<a href=\"{$video->watchURL}\">
<img src=\"$video->thumbnailURL\">
</a>
</div>
</div>
<!-- More of structure parts here -->
";
}
A part of HTML structure:
<form action="" method="GET" style="margin: 5% 0;" id="youtube_fetch">
<input type="text" name="id" value="https://www.youtube.com/watch?v=VIDEO_ID_HERE" id="videoID_input" />
<input type="submit" id="fetch_submit" />
</form>
A part of jQuery / Ajax call:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else
console.log(state);
}
});
e.preventDefault();
});
Ok so when I put valid youtube ID into the input field, it will return the else from ajax call (echo the html structure in console log).
The part that I don't know how to deal with is: "How to get that echoed HTML content/structure and append it into the <div id="youtube_content"></div> for example or directly to the body.
Use the .html() method:
$('#youtube_content').html(state);
References:
.html() - jQuery API Documentation
If I understand your question correctly:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else {
$('<div />', {
id: 'youtube_content'
}).appendTo('body');
$('#youtube_content').html(state);
}
}
});
e.preventDefault();
});
I am deleting records using jQuery and Ajax. The code I wrote deletes a record but the HTML table is loaded again, which means the page refreshes which I want to avoid.
Here is my code:
comment.php
<script type="text/javascript">
$(document).ready(function(){
function loadList(){
$.ajax({
url: "load_list.php",
cache: false,
success : function(html){
$(".name_list").html(html);
}
});
}
loadList();
$("#Submit").click(function() {
if($(":text").val().length==0)
{
// $(this).next().html("Field needs filling");
$(":text").after('<span class="errorkeyup">Field cannot be empty</span>');
//return false;
success = false;
}
else
{
var name=$("#name").val();
var message=$("#message").val();
$.ajax({
type:"post",
url:"save_list.php",
data:"name="+name+"&message="+message,
success:function(data){
loadList();
}
});
return false;
}
});
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var id = $(this).attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(){
loadList();
}
});
// }
return false;
});
});
</script>
</head>
<body>
<div id="form">
<form method="post" name="form" action="">
<div id="content">
Name : <input type="text" name="name" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
</div>
<input type="button" value="Submit" id="Submit">
</form>
</div>
<div class="name_list"></div>
</body>
loadlist.php
<?php
include('connection.php');
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<table border="1">';
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td>
<a id='".$row['id']."' href=delete.php?id=".$row['id']."&type=Delete class=delete_button>Delete</a></td>";
echo"<td>
<a id='".$row['id']."' href=comment.php?id=".$row['id']."&type=edit class=edit_button>Edit</a></td>";
echo '</tr>';
$i++;
}
echo'</table>';
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
When you do the $.ajax() call for $('.delete_button'), you shouldn't call your loadList() function there because that is what reloads the table, instead you should just remove the one entry that's deleted from the table.
Perhaps you can remove it with something similar to this, placed inside the delete button success callback:
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function()
{
$(this).parent().parent().remove();
}
});
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
in this code remove line
header("location: comment.php");
Final code would be,
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
echo '1';
} else {
echo '0';
}
exit;
?>
In delete function, after executing delete query, you need to echo '1' or '0'. Lets say echo '1'; when deleted successfully and echo '0' when delete not succeed. So based on 1 or 0 you can remove those deleted row from table by ,
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var obj = $(this);
var id = obj.attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(response){
if(response == '1') {
obj.parent.remove();
}
}
});
// }
return false;
});