I have a php script that fetches items from database and allows users to vote for them, I give each one of those fetched items a (html form) with one (input text field) and a (submit button) to submit an entered score when clicked, and I have a jQuery script in the very same page that inserts the score via that form to the database without refreshing the page, everything seems to be working just fine except the script has one.
This script allows only the very first (html form) in the loop to submit and this first (html form) affects item that does not follow it in the loop, how to make every form attributed to its item?
Alongside this I also want the script to return a notification for the user who submits the score to inform them whether the data is successfully inserted or failed and when success I want to the score that the user submitted to appear for them after the submission
Any help is appreciated, here is my code:
<body>
<div id="items-wrapper">
<?php //function where i fetch items/records from database $items=g et_items_function($page_id); if(!$items){ echo 'There are no items in this page yet!'; }else{ ?>
<div id="item">
<?php //looping the fetched items/records foreach($items as $item){ $_itemid=$ item[ 'item_id']; $_name=$ item[ 'item_name']; $item_file='path/to/items/name-' .$_name. '-id-'.$_itemid. '.jpg'; ?>
<ul id="responds">
<!--i want to append data here-->
</ul>
<img src="<?php echo $item_file; ?>" />
<form action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
<input type="text" name="content_txt" id="contentText" placeholder="Enter score" />
<button id="FormSubmit">Add Score</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</form>
<?php } ?>
</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
//Ajax request to setItemScore.php
$("#FormSubmit").click(function(e) {
e.preventDefault();
if ($("#contentText").val() === '') {
alert("Please enter some text!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var myData = 'score_value=' + $("#contentText").val();
jQuery.ajax({
type: "POST",
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
dataType: "text",
data: myData,
success: function(response) {
$("#responds").append(response);
$("#contentText").val('');
$("#FormSubmit").show();
$("#LoadingImage").hide();
},
error: function(xhr, ajaxOptions, thrownError) {
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});
});
</script>
</body>
Issue #1
You should always use the .submit() method when a form is being submitted rather than the submit button onclick() for two reasons. 1) When using inputs you can hit enter and submit the form bypassing the entire method. 2) .submit() uses the form allowing you to get children items for that form.
With that in mind I would add a class name to the forms that you know are being submitted through ajax like:
<form class="ajax-form" action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
...
</form>
Then instead of using .onclick() you can use:
$('.ajax-form').submit(function(e){
...
});
Issue #2
In your AJAX request you are using the following line:
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
This is always going to set $_itemid to the last iteration from your above foreach() loop instead of the action from the form.
If you use the method mentioned above in issue #1 then you could simply use the forms action property:
url: $(this).prop('action')
Whereas $(this) is the form.
Related
I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="ZmieĆ" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.
I'm trying to reload a select with jquery and ajax, this select must be reload after I submit a new entry, right now I reach this point.
$("form").on("submit", function (e) {
e.preventDefault();
var form_id = $(this).attr('id');
var form_details = $('#' + form_id);
$.ajax({
type: "POST",
url: 'Users.php',
data: form_details.serialize(),
success: function (data) {
$('#check_data').html(data);
$('#div_to_update').load('my_page.php #div_to_update');
}
}
});
The div to be reloaded has a html select generate by a php code, the other fields are just plain html:
This is the first form, that must be reloaded with the values I enter in the form2:
<div id="div_to_update">
<form id="form1">
<?php Helper::combo_users(); ?>
/*
...
*/
</form>
</div>
This is the form 2:
<form id="form2" method="post">
<input type="text" id="user_reg" name="user_reg"/>
<input type="text" id="user_name" name="user_name"/>
<input type="submit" value="Add"/>
</form>
The odd thing is, this code will run the first time ok(I enter the values in the form2 and send, the form1 will reload with the new value), but the second time it does not work(when I click submit on the form2 nothing seems to happen) and the third time it will work again (click the submit button again and the value is send and the form 1 is reloaded) and so on.
Simply you are not working for second time since you are serializing a form which is dynamically updated within ajax.
jQuery won't serialize when you load a form elements such as inputs dynamically.
You're solution can be loading your new values with JSON object, and put in a foreach to display new content.
Hi I have been at this for days now and I just cant figure out why this isn't working, please could someone take a look.
index.php
<form id = "update_status" method = "POST">
<textarea id="shadow" name ="user_status" placeholder = "Share what is on your mind!" cols="97" rows="1" title="Share what's on your mind"></textarea>
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="button" value="Add Post" title="Your posts will be made public"></input></form>
swift.php
$(document).ready(function(){
$("#btnStatus_update").click(function(e) {
e.preventDefault();
//alert("Confirming function works");
$.ajax({
cache: false,
type: 'POST',
url: './datacenter.php',
data: $("#user_status"),
success: function(d) {
$("#successMesg").html(d);
}
});
});
});
datacenter.php
if (isset($_POST['user_status'])) {
var_dump($_POST['user_status']);
foreach ($_POST as $ak => $av) {
if (empty(trim($_POST['user_status']))) {
echo 'Say what is on your mind'.' ';
} else {
$userstatus = $_POST['user_status'];
add_user_status($user_data['id'], $userstatus);
}
}
}
using var_dump for testing I was hoping it did return the data, but instead i get NULL, i need the data so i can pass it into the add_user_status function to be added to the database, but it seems there is something missing or off about the code denying me my satisfaction. Please help
There are a few things that appear to be missing:
Index.php:
You need to add an action="something" attribute to the form tag, this tells the form what to do when you submit it. (unless you are manually handling this is JS somewhere else?)
<form id = "update_status" action ="data.php" method = "POST">
Also, unless you are using JavaScript on the index page to handle the actual submitting of the form, your <input> should include a type="submit" attribute. (this will also make it a button) and when clicked it will automatically submit the form to the action location above.
Swift.php:
the code posted is JS, and does what the first line of the previous paragraph mentioned (handles the submit button). Do you include this file inside the index.php? if the index.php cannot see it, then it wont run. It must also be in the html somewhere in a proper <script> block.
I believe the correct way to send form data using ajax is to serialize the data:
$('#update_status').serialize() instead of just sending the one input field.
You will also be required to reference the jQuery libraries, preferably in the index, but could also go in swift.php. I am also assuming that the code posted appears in the necessary <script> block.
Data.php:
should this be datacenter.php? your Swift.php is sending the ajax request to ./datacenter.php
On a side note, if you need it to use Ajax then you actually don't need the action ="data.php" method = "POST" in the form (Ajax does all that for you)
The way it could be done would be something like this:
Index.php:
// HTML beginning stuff
<head>
// Either reference the script in its own JS file or:
// Need to also include jquery library
<script type="text/javascript">
$(document).ready(function(){
$("#btnStatus_update").click(function(e) {
e.preventDefault();
//alert("Confirming function works");
$.ajax({
cache: false,
type: 'POST',
url: './datacenter.php',
data: $('#update_status').serialize(),
success: function(d) {
$("#successMesg").html(d);
}
});
});
});
</script>
</head>
<body>
<form id = "update_status">
<textarea id="shadow" name ="user_status" placeholder = "Share what is on your mind!" cols="97" rows="1" title="Share what's on your mind"></textarea>
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="button" value="Add Post" title="Your posts will be made public"></input>
</form>
</body>
datacenter.php:
<?php
var UserStatus = user_status
if (!empty(UserStatus)) {
var_dump($_POST['user_status']);
// process as necessary
}
?>
But, including the
<form id = "update_status" action ="datacenter.php" method = "POST">
and changing the button to
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="submit" value="Add Post" title="Your posts will be made public">
will allow users to still post information if they have JavaScript disabled.
the selector for the textarea is incorrect, the id is not "user_status", its "shadow"
data: $("#user_status"),
should really be:
data: $("textarea[name=user_status]")
or
data: $("#shadow")
<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/
I've got a basic html/php form, with jquery validation. I want the user to be able to click a link that says "preview", have fancybox load up, and then I'll present a preview of the data, which means combining elements. For instance, the user can choose the background of the iframe. Here is the basics of my form -
<form action="loggedin.php" enctype="multipart/form-data" id="message_form" method="post">
<h4>Who would you like to send a message to?</h4>
<input type="text" size="35" id="recipient" name="recipient" value="Enter Name">
<h4>Choose A Background: </h4>
<input type="radio" value="plain" class="stationery_radio" name="stationery_radio" checked />
<label for="plain">Plain</label>
.....
And this is the info I want in my fancybox:
<a class="fancybox" href="#preview_message">Click Here To Preview Your Form</a>
<div id="preview_message" style="display:none;">
<h2>To: <?php echo ($message_form['recipient']) ?></h2>
.....
But I can't use the POST, as I haven't really submitted the form yet. How can I sent the data to my fancybox where the user can look at it, and either submit the form or return to edit? Thanks for any help.
What I would do is to create another .php file (e.g. preview.php) where you can (pre)submit the form via ajax. This file would basically echo the POST values of your form fields like $_POST['recipient'], etc.
Additionally, within the same file (preview.php) you may have some links to either submit the actual form or close fancybox.
Here is an example of the preview.php file
<?php
function check_input($data){
// sanitize your inputs here
}
$field_01 = check_input($_POST['field_01']);
$field_02 = check_input($_POST['field_02']);
$field_03 = check_input($_POST['field_03']);
// ... etc
?>
<div style="width: 340px;">
<h3>This is the preview of the form</h3><br />
<p>Field 01 : <?php echo $field_01;?></p>
<p>Field 02 : <?php echo $field_02;?></p>
<p>Field 03 : <?php echo $field_03;?></p>
<a class="submit" href="javascript:;">submit</a>
<a class="closeFB" href="javascript:;">back to edit</a>
</div>
notice style="width: 340px;" so fancybox will know what size of box to display (height would be auto)
Then in your main page, add the preview button
<a class="preview" data-fancybox-type="ajax" href="preview.php">Preview</a>
notice the data-fancybox-type="ajax" attribute, which tells fancybox the type of content.
Then the script to submit (preview) the form via ajax :
jQuery(document).ready(function ($) {
$('.preview').on("click", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: this.href, // our preview file (preview.php)
data: $("#message_form").serializeArray(), // all the fields in your form (use the form's ID)
success: function (data) {
// show in fancybox the returned data
$.fancybox(data,{
modal : true, // optional (no close button, etc. see docs.)
afterShow: function(){
// bind click to "submit" and "close" buttons inside preview.php
$(".submit, .closeFB").on("click", function(event){
if( $(event.target).is(".submit") ){
$("#message_form").submit(); // submit the actual form
}
$.fancybox.close(); //close fancybox in any case
}); // on click
} // afterShow
}); // fancybox
} // success
}); // ajax
}); // on click
}); // ready
Of course, the DEMO at http://www.picssel.com/playground/jquery/postPreview_05Jun13.html.
NOTES:
this is for fancybox v2.1.4+
.on() requires jQuery v1.7+
You can use Jquery, to get the values, and put them into the fancy box...
A little like this...not quite, but you get the idea...
$('#preview_button').click(function(){
var msg = $('#recipient').val();
var bg = $('input:radio[name=stationary_radio]:checked').val();
$('h2#recipient').html(msg);
//and whatever you wanna do with the value of the bg
//probably apply some CSS on the fly to change the preview background?
$('#fancybox').show();
});
The fancybox show() is likely wrong, never used fancybox, so I dont know, but Im just using a generic, 'hidden div' show. I assume fancybox has its own API that is different, so just substitute...