Showing data after being submitted with ajax - javascript

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;
});

Related

How to pass javascript variable in .html() to php

I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;

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.
}
});
});

How do I toggle content between tabs through ajax/php?

I have divided my content in two tabs and switching between two tabs with javascript.
<div class='tab-container'>
<div class='tab-1'>
<?php
$sql="SELECT * FROM posts WHERE status='tab1'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
<div class='tab-2'>
<?php
$sql="SELECT * FROM posts WHERE status='tab2'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
</div>
Php code divides content between tabs through WHERE clause select * from posts where status='tab1'; so to remove post from one tab ajax request given below triggers php code which updates status of content from tab1 to tab2.
<script type="text/javascript">
$(function() {
$(".restore").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Restore?"))
{
$.ajax({
type: "GET",
url: "restore.php",
data: info,
success: function(){
}
});
$(this).parents(".db").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
So that post is removed from tab1. Idea here is to move post from one tab to another through ajax. javascript works good on removing post from one tab however for making that post appear in another tab I have to reload page as I haven't used ajax for that. So problem is I don't get how to add that post dynamically to another tab through ajax without refreshing page.
To get content from ajax call, you have to echo it in server side.
May be something like this
echo "hi, this is new content";
Now in ajax success
success: function(data){
alert(data); this will alert what was echoed in php(hi, this is new content)
}
If you want to add the content to some div in view,
$("class or id for the div").html(data);
In restore.php, you should get the selected post and then then update the status of that post to tab2. And append that result in main php page. You can append the same via restore.php.
Try this
HTML
<div class="tabs" id="d-tab1"></div>
<div class="tabs" id="d-tab2"></div>
<a href="#" class="restore" id="tab1">
<a href="#" class="restore" id="tab2">
JS
$('.restore').click(function(e){
e.preventDefault();
var $tab = $(this);
$.post('restore.php',{id: $tab.attr('id')},function(html){
$('.tabs').hide();
$('#d-'+$tab.attr('id')).html(html).show();
})
})
Or use Jquery tabs https://jqueryui.com/tabs/
Agree with #Niranjan N Raju. But want to add some addition.
Use console.log(data) instead alert(data) as last don't shows object info.

How do i send parameter in ajax function call in jquery

I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});

Ajax post works once then works again but not asynchronously

What i'm trying to do is simply post the forum asynchronously to a php page and return what it echos to a particular id.
When I first submit, everything works as expected. The text gets sent to the append.php and returns the new list of items promptly without refreshing the page.
The second time I submit text, it seems like it's ignoring the ajax stuff. Instead, it takes me to append.php and displays just the list. Though it still submits the form and adds to the array. This makes me suspect that my problem lies within the script.
So my question is, what do I need to do for my form to continuously work using AJAX more than once?
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>For Testing Ajax</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
// Bind to the submit event
$(".ajax").submit(function(event){
// Get local variables
var form = $(this);
// Get inputs of this form
var inputs = form.find("input, select, button, textarea");
// Get the data to post
var serializedData = form.serialize();
// prevent additional requests during the duration of this one
inputs.prop("disabled", true);
// Make the request to the form's ACTION property
var request = $.ajax({
url: form.prop("action"),
type: "post",
data: serializedData
}).done(function (response, textStatus, jqXHR){
// Success
console.log("Hooray, it worked!");
// Return response to the ID according to the form's NAME property
$("#"+form.prop("name")).html(response);
}).fail(function (jqXHR, textStatus, errorThrown){
// Failure
console.error(
"The following error occured: "+
textStatus, errorThrown
);
}).always(function () {
inputs.prop("disabled", false);
form.unbind('submit');
});
event.preventDefault();
return false;
});
});
</script>
</head>
<body>
<h1>You're on the main page.</h1>
<div id="list">
<form class="ajax" method="POST" name="list" action="append.php">
<input type="text" name="text">
<input type="submit" value="Append">
</form>
<?
$list = json_decode(file_get_contents('list.json'),true);
echo '<ul>';
foreach($list as $item){
echo '<li>'.$item.'</li>';
}
echo '</ul>';
?>
</div>
</body>
</html>
append.php
<?
// Get the POST stuff
$text = $_POST['text'];
Check if anything was indeed submitted
if (isset($_POST['text'])) {
// Get current array
$list = json_decode(file_get_contents('list.json'),true);
// Add to the array
$list[] = $text;
// Save changes to the file
file_put_contents('list.json',json_encode($list));
// Return the forum and the array in an unorganized list
echo '
<form class="ajax" method="POST" name="list" action="append.php">
<input type="text" name="text">
<input type="submit" value="Append">
</form>
<ul>';
foreach($list as $item){
echo '<li>'.$item.'</li>';
}
echo '</ul>';
}
?>
Thank you for your time!
PS: I am using jQuery v2.0.2
The problem is form.unbind('submit'); it is unbinding your event handler so it doesn't execute the next time.
Lets see, you have a form inside a DIV
<div id="list">
<form class="ajax" method="POST" name="list" action="append.php">
and in the success callback you do
$("#"+form.prop("name")).html(response);
As the name of the form is list, you're effectively replacing everything inside the DIV with the id #list with whatever the ajax call returns, and the element you inititally bound the event handler to is gone!
To solve it, use a delegated event handler that works with the new form you put in there as well
$(document).on("submit", ".ajax", function(event){
// your code here
});
You're also unbinding the event in the always handler, but that doesn't really matter as the form is no longer there after the ajax call is successful.

Categories