Voting a Poll using AJAX jQuery - javascript

I've created a simple poll that would be sent to the server side using AJAX JSON jQuery and would be echoed back. It's not properly working. Please tell me where i've gone wrong. I'm new to jQuery and JSON.
JavaScript
<script>
function sendVote(){
var voteS = $("#vote").val();
$(document).ready(function(){
$("#vote").click(function(){
$.ajax({
type : "POST",
url : "poll_vote.php",
data : "vote="+voteS,
dataType: "JSON",
success : function(data){
concole.log("Data Submitted " + data);
$("#result").html(data);
},
complete :function(data){},
error : function(error, data){
console.log("Error. not Working" + error+" "+ data);
alert("Error. not Working"+ error);
$("#result").html(error+ data);
}
});
});
});
}
</script>
PHP
<?php
$vote = $_POST['vote'];
if (isset($vote)) {
$list = array('vote' => $vote);
$encode = json_encode($list);
echo $encode;
}
?>
HTML
<body>
<h3> What is your Gender? </h3>
<form>
Male :
<input type = "radio" name = "vote" value= "0" id="vote" onclick = "return sendVote()" />
<br />
Female :
<input type = "radio" name = "vote" value = "1" id="vote" onclick = "return sendVote()">
</form>
<p><div id= "result"></div></p>
</body>

You have picked ambiguous selector, having used invalid markup with non-unique id.
Change this:
var voteS = $("#vote").val();
to:
var voteS = $("input[name='vote']:checked").val();
And, as you specified by dataType: "JSON", you are expecting an json object in success section, so you only need to access this object's vote attribute here:
$("#result").html(data.vote);
Also in success you have typo: concole.log instead of console.log
And in your PHP file, you should check if $_POST['vote'] is set:
if (isset($_POST['vote'])) {
$vote = $_POST['vote'];
$list = array('vote' => $vote);
$encode = json_encode($list);
echo $encode;
}
And remove $(document).ready(function(){ from this function, it will not bind this event to that element before you actually call this function it is in.

Related

Getting updated input value for further update in jQuery

I use an Ajax form (with JQuery Validation Plugin) on my site. It works except for the following problem: if I enter something in a text field and then click on the send button, the value is updated. With each next update, however, the old value is always used. I already understand that I may have to work with .on or .keyup, but I understand how to properly integrate it into the code, after the click or outside ...
Update:
I have several fields in the form. Here is simplified code. I also noticed that after the first update of the form, no fields can be updated with newly entered values. All values remain old.
HTML:
<form id="org-684" class="org">
<input class="org-name" type="text" name="name" value="" required>
<button type="submit" class="updateOrg">Update</button>
</form>
JS:
$(document).ready(function(){
$('.updateOrg').click(function() {
var id = $(this).closest(".org").attr("id");
id = id.split('-');
id = id[1];
var org_id_attr = "#org-"+id;
var org_name = $(org_id_attr).find(".org-name").val();
$(org_id_attr).validate({
submitHandler: function() {
$.ajax({
type: "POST",
url: "update.php",
data: ({
id: id,
org_name: org_name
}),
success: function(response){
var result = jQuery.parseJSON(response);
$(org_id_attr).find(".org-name").val(result.name);
},
error: function() {
},
cache: false
});
return false;
}
});
});
})
PHP:
<?php
$orgId = $_POST['id'];
$orgName = $_POST['org_name'];
$select = "
SELECT
name
FROM
org
WHERE
id = $orgId
";
$result = $mysqli->query($select);
$row = $result->fetch_row();
$res = array(
'name' => $row[0]
);
echo json_encode($res);
I solved the problem. You just have to put the variables from the form behind the "SubmitHandler".
$(org_id_attr).validate({
submitHandler: function() {
var org_name = $(org_id_attr).find(".org-name").val();
$.ajax({
type: "POST",

parsererror SyntaxError: Unexpected end of JSON input

When I add if(isset($_POST['uplprofimg'])), I get the error:
parsererror SyntaxError: Unexpected end of JSON input
If I exclude the php if isset post function, the code works perfectly.
So, PHP:
if(isset($_POST['uplprofimg'])){ //← This if broke my code >:(
//Works if I remove the ↑
if($_FILES['imagefile']['size'] > 5242880){
$ress = "<div class='error'>Max file size is 5MB</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}else{
$imgtype = pathinfo($_FILES['imagefile']['name'],PATHINFO_EXTENSION);
if(!in_array($imgtype,array('jpg','jpeg','png','gif'))){
$ress = "<div class='error'>Only <b>jpg</b>, <b>jpeg</b>, <b>png</b> and <b>gif</b> files are allowed (".$imgtype.")</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}else{
$newimgname = "/profile_picture/".random_num($length = 8).time().random_num($length = 8).".".$imgtype;
$newimgnameserv = $_SERVER['DOCUMENT_ROOT'].$newimgname;
if(move_uploaded_file($_FILES['imagefile']['tmp_name'],$newimgnameserv)){
$upuser = $mysqli->prepare('UPDATE accinfo SET profilepic = ? WHERE username = ?');
$upuser->bind_param('ss',$newimgname,$username);
$check = $upuser->execute();
if($check == true){
echo json_encode(array('response' => true));
}else{
$ress = "<div class='error'>SQL Error</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}
}else{
$ress = "<div class='error'>Couldn't move the file. Please try again later.(".$newimgname.")</div>";
echo json_encode(array('response' => false,'ress' => $ress));
}
}
}
}
and JS:
$("#uploadimgform").on("submit",function(event){
event.preventDefault();
var formData = new FormData(this);
$("#uploadlistener").html("<img src='/images/load.gif' width='50px' />");
$.ajax({
type: 'POST',
url: "/system/requests.php",
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function(data){
if(data.response === true){
$("#bodyfader").fadeOut("slow");
$("#expandedupl").fadeOut("slow");
$("#uploadlistener").html("");
}else{
$("#uploadlistener").html(data.ress);
$('#profilepic').css('background', 'url(/images/defaultprof.png)');
$("#profilepic").css("background-size","cover");
$("#profilepic").css("background-position","center");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
If I remove the if(isset($_POST['uplprofimg'])){...}, the code works. But if I add it there, I get the json error. What is going on?
HTML Form:
<form method='POST' enctype="multipart/form-data" id='uploadimgform' style='display: none;'>
<input type='file' id='upload' name='imagefile' accept="image/x-png,image/gif,image/jpeg" />
<input type='submit' id='uploadconf' name='uplprofimg' />
</form>
This is how the form is submitted:
$("#upload").change(function(){
if(this.files[0].size > 5242880){
$("#uploadlistener").html("<div class='error'>Maximum file size is 5MB.</div>");
$("#upload").val("");
}else{
$("#uploadimgform").submit();
readURL(this);
}
});
I have no idea why, but I did this:
formData.append('uplprofimg',1);
and the code works. Someone can explain this?
I think the issue here is that you are using FormData to send the submit button value to the server.
The submit element is not added to the entries.
I have not found clear details in the submit specification or in the construction of the formData.
Indeed, when running this snippet we can see that the submit value is not appended to the FormData.
var formData = new FormData(document.querySelector('#myForm'));
for (var p of formData.entries()) {
console.log(p[0] + " " + p[1]);
}
<form id="myForm">
<input type="text" name="sometext" value="This is submitted" />
<input type="submit" name="Submit" value="someSubmitValue" />
</form>
I would suggest you to use a hidden input if you need to send some additional data that is not part of the displayed input elements.
You need to set the upload_max_filesize option in the php.ini file.
The default max size is 2M. You need to set a higher value:
upload_max_filesize = 32M

array push() jQuery got TypeError: 'stepUp'

i got
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
in this code
jQuery(document).on("click",".save",function(){
var message = "";
var many = [];
var id = jQuery("#id");
jQuery(".list .beName").each(function(e){
var row = e + 1;
var bname = jQuery.trim(jQuery(this).val());
if (bname == "") {
message += "Please input name in row "+row+"\n";
}
});
if (message != ""){
alert(message);
return false;
}else{
jQuery(".list .bename").each(function(){
var bname = jQuery.trim(jQuery(this).val());
if(bname != ""){
many.push(bname);
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ben_add.php",
data:{
"id" : id,
"beName" : many,
"save" : true
}
});
}
});
}
});
what i want is to get the value/array/data of many.push(bname); and send it into jQuery.ajax
.list is the class of <li>
.bename is the class of <input>
bename is the name of <input>
other details here is my HTML
<div id="wrap">
<ul>
<li class="list" id="<?php echo $id; ?>"><input type="text" class="beName" name="beName">x</li>
</ul>
Add Save
my html was append();
The issue lies on this line,
var id = jQuery("#id");
The error occurs when you try to pass a jQuery object in ajax call. Ajax params expect a value and not DOMElement or HTMLInputElement.
Use .val() or text() according to your need.
Just for future reference. Its really a confussing message (stepup ... HTMLInputElement.) Just check variables passed to ajax, get or post. For example, output all of them to console. Maybe one of the variables is not properly initialized,
{
action: 'find_sentences',
nonce: namespace.nonce,
find: JSON.stringify({ data: this.source_array}),
source_language: this.source_language,
target_language: this.target_language,
}

how to pass jquery date parameters in php

Please help me.. I have the following codes..
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
});
now I want to pass the firstDate and the lastDate to a php. How should I do this. and how can I retrieve the passed value in the php. I'm not very familiar with javascripts. Hope anyone can help me. Thanks in advance.
Here is my full code..
JS tags
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootstrap.datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
HTML
<div class="input-group" id="DateDemo">
<input type='text' id='weeklyDatePicker' placeholder="Select Week" class="form-control" />
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
JS
$("#weeklyDatePicker").datetimepicker({
calendarWeeks:true,
format: 'MM/DD/YYYY'
});
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
alert(firstDate);
$.post("SAMPLE1.php",{"fdate" : firstDate ,"ldate" : lastDate});
});
$('#DateDemo').on('dp.change', function (e) {
var kk = $("#weeklyDatePicker").val();
$("#output").html(
" Week Number: " + moment(kk, "MM/DD/YYYY").week() + " of " +
moment(kk, "MM/DD/YYYY").weeksInYear()
);
});
SAMPLE1 CODE
<?php
echo $_POST["fdate"]; //for firstdate
echo $_POST["ldate"]; //for lastdate
?>
You can use jquery for that. Try this code :
YOUR JS FILE CODE :
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("main.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
});
});
YOUR PHP FILE CODE (main.php)
<?php
if(isset($_POST["fdate"])) {
echo $_POST["fdate"]; //for firstdate
}
if(isset($_POST["ldate"])) {
echo $_POST["ldate"]; //for lastdate
}
?>
Make sure both the files are in same folder.
I would use $.ajax() function, which will let you handle the error status as well, because it is both a good practice to handle errors for the users and an indicator of what is going wrong with your script.
$.ajax({
url: 'test.php',
type: 'POST',
data: {fdate : firstDate ,ldate : lastDate},
dataType: 'text',
beforeSend: function(){
// initiate some spinner or loading infobox
// to inform the user about the AJAX request
},
success: function(response){
alert(response);
// you may use result like any standard argument
// and call or trigger other functions according to its value
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + ': ' + errorThrown);
// call some error handler or do nothing
},
complete: function(){
// close the spinner or loading box
}
});
In your PHP file, you get the variables as $_POST['fdate'] and $_POST['lDate']. Once you complete the query and get the results, echo a response something like that:
echo 'success';
or
echo 'failure';
according to the result of the query. You may use any string, not just success or failure. Just don't forget that is what you will handle in the success part of your $.ajax() function and not the error part of it. The error part is only for whatever goes wrong with the request (e.g. file not found or server error).
Well, here is the tricky part: If the only thing you want to return is a status, you may use dataType: 'text' in your $.ajax() function as I did in this example. However, if you want to return an object with some useful data, such as what has gone wrong with the PHP query or what has been accomplished by the PHP query, then you'd better to use dataType: 'json' and get a JSON response. In such a case, the end of your PHP script will change too.
$result = ['statusCode'=>1,'details'=>'Some details according to the query here'];
echo json_encode($result);
The success handler of your $.ajax() function will get an object as the argument (i.e. response will be an object) which you can use like this:
alert(response.statusCode); // will alert 1
Ajax is probably the easiest.
Javascript:
$.get("test.php", { firstDate: firstDate, lastDate: lastDate } );
or
$.post("test.php", { firstDate: firstDate, lastDate: lastDate } );
and in php
<?php
echo $_REQUEST['firstDate'];
echo $_REQUEST['lastDate'];
?>
Hi Kath Dee please check below code, I hope solve your problem using below code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#weeklyDatePicker').on('dp.change', function (e) {
// I am using test value, you can change var value base on id.
var firstDate = '08/02/2016';
var lastDate = '10/02/2016';
//$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("test.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
$("#weeklyDatePicker").val(data);
});
});
</script>
<input type="text" value="" id="weeklyDatePicker" />
test.php
<?php
// set your format as you want for display.
echo $_POST['fdate'].'-'.$_POST['ldate'];
?>
I hope this is working fine for you.

Variable doesn't get passed to Ajax call : undefined variable

I've edited this question from the original OP to better represent my issue.
How can I pass the variable data-uid with AJAX ?
Right now the variable doesnt get passed.
var uid = $(this).data("uid"); doesn't work = undefined
var uid = '199'; gets passed. works.
is it possible to have something like : var uid = $uid; ?
HTML
<form>
<fieldset>
<textarea id="post_form" type="text" data-uid="<?php echo $uid ?>"/></textarea>
<button type="submit" id="add" value="Update" name="submit" />OK</button>
</fieldset>
</form>
JS
$(function() {
$("#add").click(function() {
var boxval = $("#post_form").val();
var uid = $(this).data("uid"); // this needs to be changed
var dataString = 'post_form=' + boxval + '&uid=' + uid;
if (boxval == '') {
return false;
} else {
$.ajax({
type: "POST",
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
return false;
});
});
problem in your code in:
var uid = $(this).data("uid");
you're trying to wrap this into jquery object, but it is button object in this context, then you're trying to obtain something unassigned from it
you shoud use:
var uid = $('#post_form').attr('data-uid');
or, you can add <input type="hidden" name=... value=... and get id from it, this is more general way
Looks like your issue is with the data attribute that should be data-uid="somevalue" Like.
Check this fiddle to see if this solves your main problem

Categories

Resources