Span Value Changed Back to Old Value After Successful AJAX call - javascript

So I have this one weird situation which I am really confused now. I can't see any solution on the Net yet for this weird issue. I have one AJAX call that will populate the data which generated on the page also by using AJAX (dynamic). Here is my code:
My jQuery Code:
$(document).delegate('.edit_tr', 'click', function(){
var the_id = $(this).attr('id');
}).delegate('.edit_tr', 'keypress', function(e){
if(e.which == 13) {
var input_name = $("#input_name_" + the_id ).val();
if(input_name.length > 0){
//if I reset the span text and do return false here, the text showed properly on the page
$.ajax({
type: "POST",
url: "ajax_update.php",
data: data_string,
success: function(html){
//do the reset of span text
$('#name_'+the_id+'').html(input_name);
alert('Examining'); //while alert is popped up,text of span is expected as changed
//after 'OK' is clicked on the alert, the span text go back to its previous text
},
error: function(err){
//do something
}
});
}
}
});
Code in another PHP page which gets called via AJAX. This page displays the data on the page before being manipulated by above code for edit in place.
$returned_msg .= '<form id="form1">';
if( $contact_details->exists() ){
$lists = $contact_details->data();
foreach( $lists as $list ){
$returned_msg .= '<tr id = "'.$list->cont_detail_id.'" class="edit_tr">
<td style="text-align:center" class="edit_td">
<input type="hidden" value="'.$list->cont_detail_id.'" id="cont_detail_id_'.$list->cont_detail_id.'" />
<span id="name_'.$list->cont_detail_id.'" class="text_span">'.$list->det_name.'</span>
<input type="text" value="'.$list->det_name.'" style="width:120px;height:6px;" class="editbox" id="input_name_'.$list->cont_detail_id.'" />
<input type="hidden" value="'.$list->det_name.'" class="editbox" id="hidden_name_'.$list->cont_detail_id.'" />
</td>
</tr>';
}
$returned_msg .= '</form>';
}
class editbox is not displayed till the tr is clicked. I am now totally baffled. Looking forward to get some thought on what could probably causing this. Thank you.

Related

Adding single hidden input value to each form input in ajax call

I have a form with a button that can add dynamic input fields, and it's creating an ajax issue. My ajax post is giving me 500 errors
But My console log for data right now is this:
but I need to insert these as
insert into ticker_content (ticker_id, content)
values (1, 'one'), (1, 'two');
If that makes sense.
So basically, the problem is i have multiple inputs at any given time (containing text values) and a hidden input in the form that gives me my correct ticker ID.
However, I need to make my array contain elements that each have the input text value and the ticker ID. So for every input that's created and filled, I need to assign the value of that form's hidden input to it as well so I can sent them as pairs to my foreach loop and insert.
Here's my addticker.php that's being called for the insert:
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO ticker_content (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
So basically for every Items[] value, I need to insert with the same hidden field.
Here's my form and JS code for reference. The first JS block is mainly for the functionality of dynamically adding inputs, but the last JS block is the ajax using serializeArray();
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/> <!--form starts with one input-->
<button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->
<input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
<input type="submit" name="saveTickerItems" value="Save Ticker Items"> <!--submit button-->
</form>
<?php endforeach;?>
<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: $("#Items").serializeArray(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
Firstly, you are missing a semicolon in your code (which is likely causing your 500 error).
Secondly, if you want to bundle all the fields from the form as a single query, the following will build out a query similar to what you noted earlier in your question as:
INSERT INTO ticker_content (ticker_id, content) VALUES(1, 'one'), (1, 'two'), ...
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
$addTicker = "INSERT INTO ticker_content (tickerID, content) values";
foreach ($items as $item){
$addTicker .= "('$tickerID', '$item'),";
}
$addTicker = substr($addTicker, 0, -1); // Eat that last comma
$mysqlConn->query($addTicker);
Your HTML also needs some work because the id attribute should be unique on the page. Since you are duplicating the form, you should do something like the following:
<form id="Items<?php echo $ticker['ticker']?>" class="tickerform" method="post">
And then update your javascript:
// Using $(this) in Jquery allows you to access the
// element that is making the method call (in this case, the form)
$(".tickerform").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: data, // Don't need to serialize again, 'var data' is still in scope.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});

Unsolved PHP page refreshing without Ajax

Please, can somebody publish a mistakes corrected and tested code for my problem?
Program does - 22.php has the form. When the user enter and click Submit button, the result should be taken from 23.php and displayed in div on 22.php
I already tried solutions below and none of them solve my problem;
1) I changed to: $("#testform").submit(function(event){
2) I included "return false;" at the end to prevent it to actually submit the form and reload the page.
3) clear my browser cache
I can see what happen the program with my computer;
1) I do not get error message after I click submit.
2) I can see the tab of the page reloads quickly and the entered text fields are cleared.
3) No error message or result shows.
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').val(data);
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
you don't need to change your php code
try submit form with submit event ...
$("#testform").submit(function(event){
use `dataType:json`; in your ajax ..
yourData =$(this).serialize();
Your php
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
$data['name']= 'welcome '.$name;
$data ['age']= 'you are '.$age;
print_r(json_encode($data));exit;
}
?>
Now In Your Success function
var message = data.name + ' ' + data.age;
$('#result').html(message );
You are sending myname and checking name(isset($_POST['name']) in php.
don't use .value() use .html() for data rendering. and console log the data and see whats request and response using firebug.
Can you try this one?
To be changed
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
and
$('#result').html(data); // here html()
the code becomes
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
alert('Submitted');
}else{
return false;
}
}
});
});
});
Try formatting your post data like this inside your ajax function.
$.ajax({
type:'POST',
data : {
myname: myname
myage: myage
}
...
}
EDIT
Try removing the ; in
return false;
}
};
to
return false;
}
}
You can change at both end ajax and php:
#PHP:
You can check for correct posted data which is myname and myage not name and age.
<?php
if ( isset($_POST['myname'])) { // was the form submitted?
echo "Welcome ". $_POST["myname"] . "<br>";
echo "You are ". $_POST["myage"] . "years old<br>";
}
?>
or #Ajax:
yourData ='name='+myname+'&age='+myage;
//--------^^^^^^----------^^^^----change these to work without changing php
Just noticed the #result is an div element. So, you can't use .val() but use .html(), .append() etc:
$('#result').html(data);

Jquery won't POST if preventdefault is placed

I want to make a form where you write a number send it with Jquery and is shown by PHP without refreshing the page ,by far i have this code but if preventDefault() is placed it will post but the content is not shown,also if i remove it, the content is shown but the page will pe refreshed.
Javascript:
$('#testut').unbind('submit').bind('submit',function(ev) {
ev.preventDefault();
$.ajax({
type: 'post',
url: 'incerc.php',
data: $('form').serialize(),
success: function () {
$('.success').fadeIn(500);
}
});
});
}
HTML:
Test
<br />
<?php
if(isset($_POST['test'])) {
$test = $_POST['test'];
$numar = $_POST['numar'];
echo 'Order name:'.$test.'<br />Number:'.$numar.'<br />';
} else {
echo 'No <br />';
}
?>
<div id='testut'>
<form id='test' method='post'>
<input type='text' name='numar'><br />
<input type='submit' name='test' onclick ='check()' value='Place'><br />
<span class='success' style='display:none'>Order was successfully placed.</span>
</form>
</div>
If I understand you correctly, you're making a dynamic ajax request and expecting your if(isset($_POST['test'])) to run on success. That won't work. That PHP code is static and will only be run to build the page. What you'll need to do is dynamically build the results after receiving a response from the POST operation.
The form response should return JSON, i.e.: { orderName: 'test name', numar: 1321321 }
Then your success function would look like (roughly):
function( data ){
$('.success')
.html( 'Order name:' + data.orderName + '<br />Number:' + data.numar + '<br />' )
.fadeIn(500);
}
Don't use unbind submit and bind submit, eventually it is of no use, 'cause the default action (form submitting on submit button click) is not been prevented in this way.
If you really trying to get data from another php file (incerc.php) to your page, you need to prevent your page from been reloaded by preventDefault() method inside your event handler:
$('#test').on('submit', function(ev){
ev.preventDefault();
var form = $(this);
$.post('incerc.php', form.serialize())
.done(function(data){
$("#form_result").html('Number:' + data + '<br />');
})
.fail(function(){
$("#form_result").html('No <br />');
});
$('.success').fadeIn(500);
});
And without page reload you can only insert response from $.post ajax call to some DOM element (#form_result in my example) of your page, to show it. Here is the HTML for my example:
<div id="form_result"></div>
<div id='testut'>
<form id='test' method='post'>
<input type='text' name='numar'><br />
<input type='submit' name='test' value='Place'><br />
<span class='success' style='display:none'>Order was successfully placed.</span>
</form>
</div>
Then you don't need to pass $_POST['test'] - value of your submit button - in ajax call to the incerc.php, 'cause it can be simply found in the DOM.
However, if you are trying to get data from the same page of yours, you will need the right PHP implementation of ajax response in the beginning:
if(isset($_POST['test']))
{
$test = $_POST['test'];
$numar = $_POST['numar'];
echo 'Order name:'.$test.'<br />Number:'.$numar.'<br />';
die();
}
...
I wanted to execute a query after the POST in php,the example was just for test, so i managed to do this(on example).
Javascript:
function check(){
$("#test").submit(function(e)
{ var numar = $('#numar').val();
var test = $('#testim').val();
var dataString = 'numar='+ numar + '&test=' + test;
$.ajax(
{
url : 'incerc.php',
type: "POST",
data : dataString,
success:function(data, textStatus, jqXHR)
{
$('.success').fadeIn(500);
$('body').load('incerc.php?'+dataString);
},
error: function(jqXHR, textStatus, errorThrown)
{
$('.success').html("Nu a mers");
}
});
e.preventDefault();
e.unbind();
});
}
HTML:
<?php if(isset($_GET['test'])){
$test = $_GET['numar'];
$numar = $_GET['numar'];
echo 'Order name:'.$test.'<br />Number:'.$numar.'<br />';}
else{echo 'No <br />';} ?>
<div id='testut'>
<form name='test' id='test' method='POST'>
<input type='text' id='numar' name='numar'><br />
<input type='submit' id='testim' name='test' onclick ='check()' value='Place'><br />
<span class='success' style='display:none'>Order was successfully placed.</span>
</form>
So now the body will load when the data is sent sucessfully , and will get the result correctly ,also in the adress bar it will still show 'incerc.php' not 'incerc.php?'+dataString.

Submitting form is not working properly

I'm developing a webpage that creates a form with a number of select tags dynamically by means of some javascript/jquery code. When submitting the form a php file (form_submit.php) must process the submitted form fields. Furthermore I use Netbeans 7.4 for php debugging.
My problem: when I select some values in the form and submit the form the debugger shows empty submitted values (e.g., default values "NOSELECTION" for no selection) within form_submit.php instead of the selected values. The console within the submit function in the code below does show the selected submitted values (and therefore also confirms that the built html form with the select tags is correct).
I do not assume this a is a bug in Netbeans, so where do I go wrong? I suspect there is a bug in the jquery submit function below, but I cant's see it...
Javascript code:
//main function document ready
$(document).ready(function(){
//only part of code here to build the form with a number of <select>'s
ecorp_eproductoptions = '<select id="selected_eproductid'+ff+'" class="eprodtype" name="selected_eproductid'+ff+'">';
ff++;
ecorp_eproductoptions += '<option selected="selected" value="NOSELECTION" > Koppel uw product </option>';
for(var k=0; k< Staticvars.ecorp_nrofeproducts;k++){
ecorp_eproductoptions += '<option value="'+ Staticvars.suppliername[i] +'_'+Staticvars.agreementid[i] +'_'+ supplier_eproductid +'_'+ Staticvars.ecorp_eproductid[k] +'"> '+ Staticvars.ecorp_eproductname[k] +' </option>';
}//for var k
ecorp_eproductoptions += '</select>';
form += '<td> '+ ecorp_eproductoptions +' </td></tr>';
//etc...
//FUNCTION Submit()
$("#myForm").submit(function(){
console.log('SUBMITTED FORM: '+ $( this ).serialize() ); //shows values for select tags!
$.ajax({
type: "POST",
url: "form_submit.php",
data: $("#myForm").serialize(),
dataType: "json",
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
return false;
});//$("#myForm").submit()
}); //$(document).ready
HTML code:
<form id="myForm" name="myForm" action="" method="post">
<div id="wrapper"></div> <!--anchor point for adding set of product form fields -->
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="submit" name="submitForm" value="Bevestig">
</form>
I'm new to jQuery too, but I think the problem is the fact that your $.ajax call is running asynchronously which allows the submit event handler to continue on and return false before your form sends the values...just a newbie guess. :)
Have you tried adding async: false to your $.ajax call?
i dont know why happens that, but please try this
$("#myForm").submit(function(){
var dataAjax = $( this ).serialize();
console.log('SUBMITTED FORM: '+ dataAjax ); //shows values for select tags!
$.ajax({
type: "POST",
url: "form_submit.php",
data: dataAjax,
dataType: "json",
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
return false;
});//$("#myForm").submit()

Showing data after being submitted with ajax

I am trying to display data after being submitted with ajax. The ajax works so far when submitting, but I have to refresh to see it.
Here's the jquery:
$('#submit-quote').live("submit", function(){
var formdata = $(this).serialize();
$.post("add.php", formdata, function(data) {
console.log("success");
});
return false;
});
The php in add.php:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Here's the HTML/PHP that I use to fetch the data and display it:
<?php
require("includes/connect.php");
$result = mysql_query("SELECT * FROM entries", $link);
while($row = mysql_fetch_array($result)){ ?>
<div class="quote-wrap group">
<span>Like</span>
<div class="quote">
<p>
<?php echo htmlentities($row['quote']); ?>
</p>
</div><!-- /.quote -->
</div><!-- /.quote-wrap -->
<?php } ?>
If needed, here's the form:
<form id="submit-quote" method="post" >
<h2> Submit A Quote </h2>
<textarea name="quote">
</textarea>
<input type="submit" name="submit" value="Submit!">
</form>
Ajax works when submitting, but I need to display it after being sent also, how can I do this?
The data variable in your success callback function stores the server response. So to add the server response to the DOM:
$(document).delegate("'#submit-quote'", "submit", function(){
$.post("add.php", $(this).serialize(), function(data) {
$('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + data + '</p></div></div>');
});
return false;
});
If you need to use event delegate (e.g. the form isn't always present in the DOM) then use .delegate() instead of .live() as the latter has been depreciated as of jQuery 1.7.
Also you don't really need to cache $(this).serialize() in a variable since it is only being used once (creating the variable is unnecessary overhead).
Since your PHP code is outputting echo $quotes . "Added to database";, the server response will be the quote with "Added to database` appended to the string, which will be added to your list of quotes.
UPDATE
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
$('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + quoteVal+ '</p></div></div>');
});
return false;
});
Notice that I am no longer referencing the server response (in fact I removed the data variable all together). Instead I am saving the value of the name="quote" element within the form being submitted and using it after the AJAX request comes back (this way the quote is added to the database before being added to the DOM). You could move the .append() code outside the success callback to run it right as the form is submitted (in the submit event handler).
UPDATE
If you want to create a DOM element to append rather than concocting a string:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
//create parent div and add classes to it
$('<div />').addClass('quote-wrap group').append(
//append the "like" span to the parent div
$('<span />').text('Like');
).append(
//also append the .quote div to the parent div
$('<div />').addClass('quote').append(
//then finally append the paragraph tag with the quote text to the .quote div
$('<p />').text(quoteVal)
)
//then after we're done making our DOM elements, we append them all to the .inner element
).appendTo('.inner');
});
return false;
});

Categories