PHP: trying make ajax call from foreach loop - javascript

I am looping through data form a database to a form that makes a Ajax request to add an item to a shopping basket/cart. Everything works fine except that only the first item in the array is added? I have tried using classes as apposed to id's(unique
echo "<div class='col-100 border-temp bg-orange'>";
echo "<div class='col-50 border-temp'>";
foreach ($result as $key => $result) {
$m = $result["model_no"];
$q = $result["qty_available"];
echo "<form method='post' action='/stock-clearance' class='stock_clearance bg-blue'>";
echo "<label for='model_no'><h2>Model No</h2></label>";
echo "<input id='model_no' name='model' type='text' placeholder='Paste model no... ' value='$m' />";
echo "<span id='model_error'></span>";
echo "<label for='quantity'>Quantity</label><br />";
echo "<input id='quantity' name='quantity' value='1' type='number' min='1' max='$q'>";
echo " <span id='quantity_error'></span>";
//echo "<input id='sc_add_to_cart' name='' value='$key' type='button'>";
echo "<input id='sc_add_to_cart' name='sc_add_to_cart' value='Add to Basket' type='submit'>";
echo "</form>";
} // End foreach loop
echo "</div>";
)
My JS code is as follows:
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php',
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
enter image description here

You can not have the same one ID for a different inputs. ID must be UNIQUE. Instead of ID use CLASS attribute

1- Sometimes because of caching problem it will not work so you have to add seed to your call.
seedrandom()
function seed() {
return Math.floor((Math.random() * 10000) + 1);
}
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php?sid=' + seed(),
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
Please use IDs only for one element. They must be unique. You can use CLASS instead.

Related

Retrieve Result from Ajax Process

I need a way of retrieving data from a processing script into a Request page using Ajax, PHP. The code below shows this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the JSON data
var data4=JSON.parse(data4);
Please, note that I have search but have not been able to get solution. So, I thought maybe there is a way of passing the result to the requesting page without using json_encode.
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select.partno").change(function() {
var selectedCustomer = $(".partno option:selected").val();
$.ajax({
type: "POST",
url: "process-grpid.php",
dataType: "json",
data: {
custid: selectedCustomer
}
}).done(function(data4) {
var data4 = JSON.parse(data4); //Error Area
//using php-mysql before
$("#desc").html(data4.ref);
$("#purch").html(data4.lprice);
});
});
});
</script>
<form>
<table>
<tr>
<th>Item Code/Part NO:</th>
<?php
include("db_connection.php");
$s = mysqli_query($connection,"SELECT * FROM tab_stock ORDER BY itemName ASC");?>
<td>
<select name="partno" class="partno">
<option>Select PartNo</option>
<option value="N/A">N/A</option>
<?php while($rw = mysqli_fetch_array($s)){ ?>
<option value="<?php echo $rw['itemName'];?>">
<?php echo $rw['itemName'];?>
</option>
<?php };?>
</select>
</td>
<th>Description:</th>
<td id="desc"></td>
</tr>
<tr>
<th>Last Purchase Price:</th>
<td id="purch"></td>
</tr>
</table>
</form>
process-grpid.php (Processing Script)
<?php
if (isset($_POST["custid"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$partid = $_POST["custid"];
if ($partid !== 'Select PartNo') {
$gets = "SELECT * FROM tab_stock WHERE itemName='" . $partid . "'";
$get = mysqli_query($connection, $gets);
$row = mysqli_fetch_array($get);
$desc = $row['description'];
$lprice = $row['Rate'];
if ($partid == 'N/A') {
$res["sta"] = 0;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
} else {
$res["sta"] = 1;
$res["ref"] = "<input type='text' value='$desc' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='$lprice' readonly='readonly' required='required'/>";
}
echo json_encode($res);
}
}
?>
When I run this Application, it shows an error of SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the JSON data
var data4=JSON.parse(data4)
But when checked with Firebug, in the HTML and RESPONSE TAB, it shows the expected result. Question, what alternative way of getting result from a processing script to the requesting page, withput uisng json_encode and JSON.parse(response)?
Try removing
dataType: "json"
of the call ajax
Update:
If the configuration is dataType: json, you'll get a javascript object is no longer necessary JSON.parse
Try not using the JSON.parse at all ... as you get a native JavaScript Object back, not a JSON String ...
I took your code and made some tests. Next code works for me:
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
var selectedCustomer = 1; // DATA FOR PHP.
$.ajax( { type : "POST",
url : "test.php",
data : { "custid" : selectedCustomer }, // DATA FOR PHP.
success: function ( data4 ) {
var data4 = JSON.parse( data4 );
alert( data4.custid );
alert( data4.sta );
alert( data4.ref );
alert( data4.lprice );
$("#desc").html( data4.ref ); // <TD> IN <BODY>.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<button onclick="myAjax()">echo hello</button>
<table>
<tr>
<td id="desc"></td>
</tr>
</table>
</body>
</html>
test.php
<?php
if ( isset( $_POST[ "custid" ] ) )
{ $res = array();
$res["custid"] = $_POST[ "custid" ];
$res["sta"] = 2;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
echo json_encode( $res );
}
?>
Notice I deleted the ajax line dataType : "json",, because as soon as I include it this code throws an error. Copy-paste previous codes in two files called "test.html" and "text.php", they work fine.
Instead of
echo json_encode($res);
Use:
echo json_encode(array('res' => $res));
And instead of:
var data4 = JSON.parse(data4);
Use:
var d = data4.res;
And than use "d" like an array. Here is the JS code I am trying to tell you:
$(document).ready(function() {
$("select.partno").change(function() {
var selectedCustomer = $(".partno option:selected").val();
$.ajax({
type: "POST",
url: "process-grpid.php",
dataType: "json",
data: {custid: selectedCustomer}
}).done(function(data4) {
var d = data4.res;
$("#desc").html(d['ref']);
$("#purch").html(d['lprice']);
});
});
});
If still there is an error, it is probably in the usage of "d" and you can change d['ref'] to d[1] and d['lprice'] to d[2].
I see that there is also a mistake when trying to concatenate $desc and $lprice to the input strings.
$res["ref"] = "<input type='text' value='" . $desc. "' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='" . $lprice . "' readonly='readonly' required='required'/>";
And a plus... if you use these variables only if $partid != 'N/A', why don't you move the query to inside the else statment? Doing this, you avoid to execute the query all the time.
if ($partid !== 'Select PartNo') {
if ($partid == 'N/A') {
$res["sta"] = 0;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
} else {
$gets = "SELECT * FROM tab_stock WHERE itemName='" . $partid . "'";
$get = mysqli_query($connection, $gets);
$row = mysqli_fetch_array($get);
$res["sta"] = 1;
$res["ref"] = "<input type='text' value='" . $row['description'] . "' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='" . $row['Rate'] . "' readonly='readonly' required='required'/>";
}
echo json_encode($res);
}

How to use Javascript to insert new field in PHP and perform while loop

I have a form with the option to add another row at the click of a button.
This new row will have a select list as it's input type.
The select list needs to process information from a database that was retrieved on page load.
How can I have the new select list perform a while loop on the data from the database once it is created via the add button.
Here is the code I have so far.
PHP:
echo "<div id=\"FieldGroup\">";
echo "<select name=\"add_project_service_1\" class=\"project_details_service\" value=\"\" required >";
while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}
echo "</select> ";
echo "<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_1\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"\" /> ";
echo "<label>Value: </label><input type=\"text\" name=\"add_project_value\" class=\"project_details_value\" placeholder=\"Value\" value=\"\" /><br>";
echo "</div>";
echo "<input type=\"button\" value=\"Add Button\" id=\"addField\"><input type=\"button\" value=\"Remove Button\" id=\"removeField\">";
Javascript:
<script>
$(document).ready(function() {
var counter = 2;
$("#addField").click(function () {
if(counter>50){
alert("Only 50 extra fields allowed.");
return false;
}
var newFieldDiv = $(document.createElement('div'))
.attr("id", 'FieldDiv' + counter);
newFieldDiv.after().html('<select name="add_project_service_' + counter + '" class="project_details_service" value="" required >' +
'while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}</select> ' +
'<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_' + counter + '\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"".$quantity."\" /> ' +
'<label>Value: </label><input type=\"text\" name=\"add_project_value_' + counter + '\" class=\"project_details_value\" placeholder=\"Value\" value=\"".$value."\" /><br>');
newFieldDiv.appendTo("#FieldGroup");
counter++;
});
$("#removeField").click(function () {
if(counter==2){
alert("No more fields to remove.");
return false;
}
counter--;
$("#FieldDiv" + counter).remove();
});
});
</script>
Inserting the while loop into the javascript doesn't work.
How can this be accomplished so when I add a field the options are listed and fields are populated?
javascript is exectued on client side while php interpreted on the server side.
Once you've send the page to the client, the only way to edit the page without reloading a new one is with javascript and ajax call (xmlhttprequest). The client doesn't use php neither download php page from the server.
You could do an ajax call to your page with jquery
$.ajax{
url: "mypage.php",
type: "GET",
dataType: "jsonp",
success: function( myObject ) {
console.dir( myObject );
}
}
// mypage.php
header('Content-type: application/json');
echo json_encode( $myObject );
// for you it will be
echo json_encode( $result->fetch() );

How to target the second element in JQuery

This is my PHP code and each post has a More button with the same class. I want if I click on More button of post A, only the comments under it should be displayed :
<?php
for ($i = 1; $i <= 10; $i++) {
echo "<div class='col-md-6'>";
echo "<div class = 'feeds'>"; ?>
<form method='post' class='murconform form-horizontal' name='signinform'
action =''>
<?php
echo "<p>". $post . "</p>";
echo "<div class = 'murcons btn-group'>";
echo "<span class = 'likecount'>". $likes . "</span><button class='mlike pacedown' value='".$assigned_id."' name = 'like' type='submit'><span class = 'buttons'>Like</span><span class='glyphicon glyphicon-heart'></span></button>";
//Problem 1: I want whenever the next button with the class 'mmore' is clicked, the class
'comment_data' should be displayed. It is set to "display:none" by default but
whenver I click it, all other comment are displayed.
echo "<button class='mmore pacedown' value='".$post_id."' name = 'more' type='submit'><span class = 'buttons'>More</span><span class='glyphicon glyphicon-chevron-down'></span></button>";
echo " "."<span class = 'slanted'>". $time . "</div>";
echo "</form>";
// fetch and display comment for each post...
$qry = "SELECT user_id, comment FROM comments WHERE post_id = ? ORDER BY time DESC";
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $post_id);
$q->execute();
if($commentz = $q->fetchAll()){
echo "<div class = 'comment_data'>";
foreach ($commentz as $comment){
echo "<div class = 'per_comment'>";
echo "<p>". $comment[0] ." ". $comment[1] . "</p>";
echo "</div>";
}
echo "</div>";
}?>
<form method='post' class='murconform form-horizontal' name='signinform' action ='<?php echo htmlentities($_SERVER['PHP_SELF']);?>'>
<?php
echo "<div class = 'commentdiv'>";
echo "<input type='hidden' name='post_id' value='".$post_id."'>";
echo "<textarea autocomplete = 'off' name='commentdata' maxlength='480' class='commenttext form-control' rows = '1' placeholder='Have your say...'></textarea>";
echo "<span class='counter_msg'></span>";
echo "<button class='btn btn-xs btn-primary onespacedown comment' name = 'comment' type='submit'>Comment</button>";
// Problem 2: How do I get the content of this textarea whenever the submit button is clicked via AJAX?
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
This is my jQuery code for Problem 1:
$( ".comment" ).click(function() {
var $this=$(this);
$(".murconform").submit(function(e){
return false;
});
$('.comment_data').slideToggle("slow");
});
And this is the AJAX code for Problem 2:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var $this=$(this);
var post_id = $('.post_id').val();
var comment = $(".commentdata").text();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id , comment : comment },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.comment').html( msg );
});
});
Any good solution/advice(with regards to best practice) would be deeply appreciated.
Hard to know for sure unless you post the generated HTML, not the code that generates it but it seems that what you are trying to do is target elements within a group, not those outside of that group that have the same class name.
To do this you find a common parent of those elements (for example a div that wraps those elements), in your case .feeds seems to occur once per iteration.
$('.mmore').on('click', function(){
var $commonparent=$(this).closest('.feeds');
Then you find the elements you want within $commonparent
var post_id = $commonparent.find('.post_id').val();
var comment = $commonparent.find(".commentdata").text();
This might clear up both problems. For a better answer please post the generated HTML and move your problem explanations to outside of the code.
To clarify, div.feeds can be used as the closest ancestor allowing you to find child elements by class name that only exist within that particular div.feeds
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>

My Jquery code still won't work , yet nothing is shown in firebug

I posted this code minutes 15 mins ago and I did get help for the preventDefault issue , but now I'm not getting my alerts to work , yet firebug doesn't show any error related to this code .. May i ask where I'm going wrong ,
<?php
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Expires: Sat 26 Jul 1997 05:00:00 GMT"); // Date in the past
require_once ("../_includes/functions.php");
?>
<link rel="stylesheet" title="Style CSS" href="../_reports/report_assets/cwcalendar.css" type="text/css" media="all" />
<script src="../_js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../_js/timer.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="../_reports/report_assets/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select').click(function(event){
$(':checkbox').prop("checked", true);
event.preventDefault();
});
$('#deselect').click(function(event){
$(':checkbox').prop("checked", false);
event.preventDefault();
});
$('#add').click(function() {
var field = '<input class="project_fields" type="text" size ="30" name = field_settings[] /> ';
var checkbox = '<input class ="checkbox" type ="checkbox" name ="check_field[]" /> ';
var delete_link = '<a class ="delete_link" style="text-decoration:none;" href="#"> Delete field </a> <br /><br />';
var input = field + checkbox + delete_link;
$('#input_fields').append(input);
});
$('#project_fields_submit').click(function(event) {
event.preventDefault();
var array_fields = new Array();
$('.checkbox').each(function() {
if($(this) .is(':checked')) {
array_fields.push('1');
alert('checked!!!');
}
else {
array_fields.push('0');
alert('not checked !!!')
}
});
$('#checkboxes').val(array_fields);
});
$('#edit_fields_submit').click(function(event) {
event.preventDefault();
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
});
var nextRowID = 0;
$('#add_edit').click(function() {
var id = ++nextRowID;
var new_field = '<input class ="class'+id+'" type="text" size ="40" name = edit_field_value[] value =""> ';
var new_checkbox = '<input class ="class'+id+'" type ="checkbox" name ="check_field[]" > ';
var delete_edit = '<a id ="'+id+'" class ="new_delete_edit" style="text-decoration:none;" href="#" > Delete field </a><br><br>';
var new_input = new_field + new_checkbox;
$('#new_input_fields').append(new_input);
$('#new_input_fields').append(delete_edit);
});
$('a.delete_edit').click(function(event) {
event.preventDefault();
var ID = $(this).attr('id');
var delete_field_id = 'edit_field'+ID;
var field_data = $('#'+ delete_field_id).val();
var project_id = $('#edit_project_id').val();
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/delete_field.php",
data: string,
success: function(data){
$('#'+ID).remove();
$('#'+delete_field_id).remove();
$('#new_check'+ID).remove();
}
});
});
$('.new_delete_edit').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.class'+id).hide();
$('#'+id).hide();
});
});
</script>
<?php
if (isset($_GET['pid']) && isset($_GET['user_id'])) {
$id = $_GET['user_id'];
$pid = $_GET['pid'];
$show_id = $_GET['show_id'];
"
$query_settings ="SELECT project_settings FROM projects WHERE project_id ='$pid'";
$result_settings = mysql_query($query_settings);
$row_settings = mysql_fetch_array($result_settings,MYSQL_ASSOC);
if($row_settings['project_settings'] == NULL) {
echo "<h2> Project Settings </h2>";
echo "<br><br>";
echo " <b> Add fields </b>";
echo " ";
echo "<img id ='add' src='_assets/add.png' /><br><br><br>";
echo '<form action ="" method="post">';
echo'<input type="hidden" name="pid" value="'.$pid.'">';
echo "<input id ='checkboxes' type ='hidden' name ='checkboxes' value ='' >";
echo "<div id='input_fields'> </div>";
echo '<input id ="project_fields_submit" type ="submit" name ="project_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
echo "<br><br><br><br><p></p>";
}
else {
echo "<h2> This Project Settings </h2>";
echo "<br><br><br><br>";
echo "<b> Add fields</b> <img id ='add_edit' src='_assets/add.png' /><br><br><br>";
$fields_data = unserialize($row_settings['project_settings']);
$i = 0;
echo '<form action ="" method="post">';
echo'<input id ="edit_project_id" type="hidden" name="edit_project_id" value="'.$pid.'">';
echo "<div id='new_input_fields'> </div>";
echo "<input id ='edit_checkboxes' type ='hidden' name ='edit_checkbox' value ='' >";
foreach ($fields_data as $key => $value) {
if($value =="1") {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size ='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' checked /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
} else {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
}
$i++;
}
echo '<input id ="edit_fields_submit" type ="submit" name ="edit_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
}
echo '</div>';
echo '<div id="project-setting-results"></div><div class="clear"></div>';
echo '</div><!-- end fragment-6 -->';
}
?>
I suggest changing your design. Using <form> codes and posting isn't always the best way of sending your data to another (or the same) page for PHP processing. Instead, switch over to using AJAX code to submit your form.
For one thing, this will allow you to get away from the e.preventDefault kludges. A number of things will iron themselves out if you use the AJAX approach (instead of submitting a form). I can see that you're already using AJAX in your code, but if you're still uncomfortable with it you can check out these other answers:
Form not posting correctly
Place PHP results inside HTML Page
Update data in a DIV
Change your #edit_fields_submit input field from type="submit" to type="button" and use javascript/AJAX to:
Get all the values you would normally submit as a <form>;
Use AJAX to submit them to a PHP file for processing
In the success: function of the AJAX code block, use javascript to send the user over to whatever page you want them to see next
Example:
$('#edit_fields_submit').click(function(event) {
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
var field_data = //you know how to get these values
var project_id = //etc
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/myprocessor.php",
dataType: "json",
data: string,
success: function(data){
document.location.href='yournewpage.php';
}
});
});

Problem send data using $.ajax

I made a form using radio button (for poll).
And I use $.ajax to submit the form.
but when I use $("#polling").serialize() for the data, there is nothing sent/requested...
Are there any problem with the radio button?
$(function(){ $("input[name=vote]").click(function(){
var id_polling = $("input[name=id_polling]");
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: BASE_URL + "/processes/polling.php",
data: $("#polling").serialize(),
success: function(msg){
document.getElementById("poll-content").innerHTML = msg;
}
});
});
and this is the HTML code :
<div class="poll-content" id="poll-content">
<form action="#" id="polling">
<?php
$poll = Polling::_find_by_id($id);
$view = "<h4 class=\"polling\">" . $poll->nama . "</h4>";
$options = explode(",", $poll->opsi);
foreach ($options as $i => $option) {
$view .= "<input type=\"radio\" class=\"option\" name=\"option\" value=\"" . $option . "\" />";
$view .= $option;
$view .= "<br />";
}
$view .= "<input type=\"hidden\" name=\"id_polling\" value=\"" . $poll->id_polling . "\">";
echo $view;
?>
<input type="button" name="vote" value="Vote" />
</form>
</div>
At first look it appears you are missing a closing });
$(function() {
$("input[name=vote]").click(function() {
var id_polling = $("input[name=id_polling]");
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: "/echo/html/",
data: $("#polling").serialize(),
success: function(msg) {
document.getElementById("poll-content").innerHTML = msg;
}
});
});
}); //<-Missing this to close out dom ready
Edit, after looking at your markup, doing $("div[class=poll-content]").text("Loading"); will destroy the form so your call to $("#polling").serialize() will fail.
Try to capture the form before you call .text()
$(function() {
$("input[name=vote]").click(function() {
var id_polling = $("input[name=id_polling]");
var formData = $("#polling").serialize();
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: "/echo/html/",
data: formData,
success: function(msg) {
document.getElementById("poll-content").innerHTML = msg;
}
});
});
});
Example on jsfiddle
Side note, you can use the class selector instead of the attribute selector $("div.poll-content").text("Loading");

Categories

Resources