AJAX Button disappering - javascript

I have a web app in laravel and I have a simple textarea with a form that allows users to enter some basic markdown text and I need it to output the data in both HTML tags and then normal formatting, my main problem, is my button disappears after submitting the first time and I can only seem to have it print out the HTML formatting or the text values but not both at the same time. I'm a little new to AJAX so any help would be awesome. Here is my AJAX code and part of my form.
<form action="{{action('MarkDownController#process')}}" method="post" name="markdownform" id="markdownform">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
<input type="button" id="ctaPrimary" value="Parse"/>
</form>
<script>
$(function () {
$('#ctaPrimary').click(function(e) {
e.preventDefault();
$.ajaxSetup({headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}});
$.ajax({
type: 'post',
url: 'process',
crossDomain:'true',
data: $('#markdownform').serialize(),
success: function (data) {
$("#markdownform").html(data);
}
});
});
});
</script>
So I was able to fix my problem overall, by changing
data: $('#markdownform').serialize(),
success: function (data) {
$("#markdownform-html").html(data);
$("#markdownform-text").text(data);
}
And just adding:
<div id="markdownform-html"></div>
<div id="markdownform-text"></div>
I guess my final question is, with $("#markdownform-text").text(data); I would like the data to show on a new line if there is a space between the elements not how it is showing below, in just one long block:
<h1>Header one</h1> <p>Hello</p> <p>more text <br />What's going on?</p> <h2>Another Header</h2> <p>something hear, eh?</p>

You are replacing the content that is in the <form> tags, you need to put it into a separate <div> to ensure it does no change the HTML within it.
<form action="{{action('MarkDownController#process')}}" method="post" name="markdownform" id="markdownform">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
<input type="button" id="ctaPrimary" value="Parse"/>
</form>
<div id="markDownContent"></div>
<script>
$(function () {
$('#ctaPrimary').click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type: 'post',
url: 'process',
crossDomain:'true',
data: $('#markdownform').serialize(),
success: function (data) {
$("#markDownContent").html(data);
}
});
});
});
</script>

Related

'undefined' data submited when using ajax

I'm using HTML form to send data to google sheet, it work great. But when i add ajax code, the data send to google sheet always is "undefined", remove the code it'll work but it show the code really ugly after that, so i want using ajax.
$(document).ready(function() {
var submit = $("button[type='submit']");
submit.click(function() {
var data = $('form#test-form').serialize();
$.ajax({
type: 'GET',
url: 'https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec',
dataType: 'json',
crossDomain: true,
data: data,
success: function(data) {
if (data == 'false') {
alert('Oopps! Đã có lỗi. Quý khách hãy thử lại hoặc liên hệ trực tiếp qua hotline nhé.');
} else {
alert('Đã tiếp nhận thành công! Cát Tiên sẽ liên hệ lại trong thời gian sớm nhất. Cám ơn quý khách');
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec" method="GET">
<input type="text" name="SDT" id="ip2" placeholder=" SĐT hoặc Email">
<button type="submit" id="submit-form" class="button">Nhận</button>
</form>
<script type="text/javascript">
</script>
I don't know about code, all i using tutorial in web. Many thanks for your help.
You forgot to add an ID to your form.
Your script is trying to serialize the form with the id test-form with this function:
var data = $('form#test-form').serialize();
The form isn't found, because you forgot to add the id to the form.
Just replace your form's HTML with the following:
<form
id="test-form"
action="https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec" method="GET">
<input type="text" name="SDT" id="ip2" placeholder=" SĐT hoặc Email">
<button type="submit"id="submit-form" class="button">Nhận</button>
</form>

Iterating over form to submit dynamic data to flask via jQuery/AJAX

I'm trying to create a web app with flask that has rows of data obtained from API calls. Currently I have a column called 'Ticket Number' that contains a set of numbers. My desired functionality is for the user to click on a number and have a modal present more specific information (via a separate python API call). I'm using AJAX to send the data to my flask app to prevent a page refresh on click. The only problem is that no matter which button I click, it thinks I am clicking the first button listed and gives me the results for the first number. Below I've posted the Python, jQuery, and html. Any and all help is greatly appreciated, thanks for your time.
jQuery:
$().ready(function(){
$('button').click(function() {
$.ajax({
url: '/ticket',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
});
Flask:
#app.route('/ticket', methods=['POST', 'GET'])
def ticket_drill():
ticket_number = request.form['ticketNumber']
header = {
'authorization': "super_secret_key",
'content-type': "application/json",
'cache-control': "no-cache"
}
s = requests.get("https://my_site/v4_6_release/apis/3.0/service/tickets/" +
str(ticket_number), headers=header)
ticket_details = json.loads(s.text)
ticket_id = ticket_details['id']
return json.dumps({'status':'OK','Ticket Number:':ticket_id});
HTML:
{% for ticket_number in service_board %}
<tr>
<td>
<form class="form-signin" action="/serviceboard" method="post" role="form">
<button class="btn btn-lg btn-primary btn-block" type="button">{{ticket_number}}
<input type="hidden" name="ticketNumber" value="{{ticket_number}}" />
</button>
</form>
</td>
</tr>
{% endfor %}
I would give your button an id and call that with the jquery like so:
$().ready(function(){
$('button#ticketNumberButton').on('click',function() {
var ticketNumberVar = $(this).parent().find(' form ').find('#ticketNumber');
$.ajax({
url: '/ticket',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
obj = JSON.parse(response);
ticketNumberVar.val(obj.Ticket_Number);
},
error: function(error) {
console.log(error);
}
});
});
});
Maybe this is just me, but I would get rid of the space and ";" in your view as well.
return json.dumps({'status':'OK','Ticket_Number:':ticket_id})
HTML:
{% for ticket_number in service_board %}
<tr>
<td>
<form class="form-signin" action="/serviceboard" method="post" role="form">
<input type="hidden" id="ticketNumber" name="ticketNumber" value="{{ticket_number}}" />
</form>
<button id="ticketNumberButton" class="btn btn-lg btn-primary btn-block" type="button">{{ticket_number}}</button>
</td>
</tr>
{% endfor %}
Hopefully that helps, good luck!

how to upload an image using ajax

I want to upload an image without refreshing the page,But my page still refresh when i hit submit button to upload image. what is wrong with my ajax code. This works when am submitting form with plain text but not with image file.
test.php
<div class="preview_d_p" id="preview_d_p">
<div class="preview">
<div class="p_preview">
<div id="p_p_image"><div id="myimage"></div></div>
</div>
<div id="lab"> <label for="photo_upload">upload</label></div>
<form enctype="multipart/form-data">
<input type="file" id="photo_upload" name="image_upload">
<input type="submit" value="save" id="insert_img" onclick="return loadimage()">
</form>
</div></div>
<script>
function loadimage(){
var image = documentElement('photo_upload').value;
$.ajax({
type:'post',
url:'profile.php',
data:{
image:image
},
cache:false,
success: function(html){
}
});
return false;
}
</script>
my advice is changing the input to a button (type="button") - I prefer buttons to inputs as they're more easily stylable.
But you can do something like this to govern submitting data without page refresh:
HTML EXAMPLE (NOT A COPY OF YOUR HTML):
<div id="container">
<form action="" method="post" id="myForm">
<input type="text" value="hello world!" />
</form>
<!-- what's great about buttons, is that you don't have to place inside the form tags -->
<button type="button" id="submitBtn">
JS To match
$(document).ready(function()
{
$('#submitBtn').on('click', function()
{
//ajaxy stuff
//will show the success callback function though:
success: function(res)
{
$('#container').html(res);
}
})
});
if your post script returns html then this should work. Let me know if otherwise :)
I solved this problem using formdata to send my image file to server
$(document).on("submit","form",function(e){
e.preventDefault();
var file = $("#product-file-i").val();
var p = $("#product-upload-f").children("input[name=name]").val();
$.ajax({
type:"post",
url:"profile.php",
data:new FormData(this),
contentType:false,
processData:false,
cache:false,
success: function(feedback){
alert(feedback);
},
error: function(){
}
});
});

Reload a single DIV on a page using onClick

In my page there are several DIVs, which are supposed to show different news items depending on the user selection and a press of a submit button.
Am I able to refresh only a single DIV when the relevant submit button is clicked?
I tried <input type ="button"> instead of <input type="submit"> but that didn't work as expected. My code is below:
<div class="dloader"></div>
<div class="search">
<form action="" method="post">
Furniture:
<input type="text" name="val1" id="val1" value="<?=$_POST['val1']?>" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php
if( isset($_POST['submit']) ){
$postItemHeader = htmlentities($_POST['val1']);
}?>
<script>
$(window).load(function() {
$(".dloader").fadeOut("slow");
})
</script>
Take One Button For Post Event
<input type="submit" id="add" name="add" />
If You want to pass the Text Data, so a text value from the Text to fetch the particular data
<div id="result">Result should appear here</div>
Use Javascript To POst The Text Data To Back End
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#add').val,
success: function(data, status) {
$("#result").html(data)
}
});
});
});
What you need is AJAX. (read the documentation). A simple example is here.
The HTML
<div id="target_div"></div> <!-- Here is where you gonna place your new content -->
<input type='button' id='trigger' onClick="get_new_data()" value="Get new Content"> <!-- When this button is pressed get new content -->
The Javascript
function get_new_data()
{
$.ajax(
{
type: POST,
url: "you-url-here.php",
dataType:"HTML", // May be HTML or JSON as your wish
success: function(data)
{
$('div#target_div').html(data) // The server's response is now placed inside your target div
},
error: function()
{
alert("Failed to get data.");
}
}); // Ajax close
return false; // So the button click does not refresh the page
} // Function end

Complete Javascript Ajax php confusion

Hi all I am developing a site in Codeigniter and I have a form that I am posting using PHP and this is absolutely fine. However I have a small dropdown on the side of my page which I am using to jump between pages - in order to do this I am simply using a href and passing variables within the URL.
I need to POST some data however when they click on the link. I don't wish to use a button and was wondering whether this could be acheived using an ajax onclick() event?? - the data I need to post however is within the form. The code structure is roughly:
<form action="main/postback" method="post">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<div>
<ul>
<li><a href = 'http:localhost/landing'>click me</a></li>
</ul>
</div>
When someone clicks on the link I want to send an Ajax Post request, but In the php file that I am posting the data I want to be able to retrieve data from within the form. Is this possible? if so could someone please provide an example AJAX request and how to retrieve the data in PHP as I am majorly confused. I tried the following:
<li><a onclick='myFunction()'>click me</a></li>
<script type="text/javascript">
function myFunction()
{
var "test";
$.ajax({
type: "POST",
url: "http://localhost/ciproject/assessment/test",
dataType: String,
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
Any ideas would be much appreciated, many thanks
You will probably run into problems using complete urls (with the domain name) due to CORS so I would recommend removing that, but you can easily do what you want using something like:
<li><a class="postFormLink">click me</a></li>
<script type="text/javascript">
$('.postFormLink').on('click', function() {
$.ajax({
type: "POST",
url: "/ciproject/assessment/test",
data: $('form').serialize(),
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
If you have more than one form on your page, you should add an ID or a class to target it instead of using $('form').
Note that I have also removed the inline event handler.
Try the following:
<form action="main/postback" method="post" id="form1">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<li><a id="clickme">click me</a></li>
<script type="text/javascript">
$(function () {
$("#clickme").click(function () {
var form_data = $('#form1').serialize();
$.ajax({
type: "POST",
dataType: "text",
url: "ciproject/assessment/test",
data: form_data,
success: function(response){
alert('Job well done');
}
})
})
})
</script>
The following should work, if you put it into your ajax options. You will need to identify your form, the easiest way is to use an id.
data: $("#theFormId").serialize()

Categories