php code
<?php
if(isset($_POST['data'])) {
$file_handle = fopen('my_file.json', 'w');
fwrite($file_handle, json_encode($_POST['data']));
fclose($file_handle);
}
?>
html
<h1 id="title" class="text-lg-center text-md-center text-sm-left mb-4">test
title</h1>
<p class="lead text-lg-center text-md-center text-sm-left mb-4">test
content</p>
<button id="test" type="button" class="btn btn-lg btn-block btn-outline-
success">Publish List</button>
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="selectfont">
</select>
</div>
javascript
$(function () {
var font = 0;
var font_names = ["Montez","Lobster","Josefin Sans"];
$.each(font_names , function (index , value) {
$('<option />' , {
'value' : index,
'text' : value
})
.css({'font-family' : font_names[index]})
.appendTo("#selectfont");
});
$("#selectfont").change(function () {
var font = $(this).val();
$("p").css('font-family' , font_names[font]);
});
var htmldata = {
'content_font_type': font_names[font],
'content_font_size': parseFloat($("title").css('font-size'))
};
$("#test").click( function(){
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});
});
so what i want to ask is why in my_file.json the content_font_type and content_font_size not changing, but when i use alert() function in $("#selectfont").change it show correctly. Also, success always return empty when i use console.log and alert()
You have two problems:
When #selectfont changes, you're setting a local variable font, not the global variable, because you re-declare it with var font. Get rid of the var keyword.
You're setting htmldata when the page first loads. You need to set it when the user clicks on the button, so you get the updated values.
You don't really need the font variable at all. You can get the value of #selectfont when you're setting htmldata.
$("#test").click( function(){
var htmldata = {
'content_font_type': font_names[$("#selectfont").val()],
'content_font_size': parseFloat($("title").css('font-size'))
};
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});
Related
How can I clear the input tag with javascript in this code?
I've tested many ways but could not.
<div id="center">
<p id="alert">FILL FIELDS</p>
<input id="name"/>
<input id="family"/><br />
<button onclick="SaveData()" type="submit">INSERT</button>
</div>
<script>
function SaveData() {
var name = $('#name').val();
var family = $('#family').val();
$.ajax({
type: "POST",
url: "server.php?p=add",
data: "fn="+name+"&ln="+family,
success: function(msg){
document.getElementById('alert').innerHTML = "SUCCESS SAVE";
}
});
}
</script>
To clear the name input, you can use jquery .val() function to reset to empty string:
$('#name').val('');
Yes, do it in your success function:
success: function(msg){
document.getElementById('alert').innerHTML = "SUCCESS SAVE";
$('#name').val(''); // set the value to blank with empty quotes
$('#family').val('');
}
I have some results in div's ,each result has one checkbox associated with it, when a user click on single checkbox user, Current checked box's value is passed to another page using an ajax call and data is fetched and displayed in a hidden div box.
Now problem is, when user uncheck the checkbox it should remove the data associated with the checkbox.
My code is :
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(".compare").change(function() {
if(this.checked) {
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').append(data);
}
});
}
});
});
Use something like this to empty the contents of the DIV
$('#compare_box').empty()
better way is to keep the reference map, something like this
$(document).ready(function() {
var boxes = {};
$(".compare").change(function() {
var check = $(this).val();
var data = $(this).closest('.box').clone();
if (this.checked) {
boxes[check] = data;
$('#comparebox').append(boxes[check]);
} else if (!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
});
});
EDIT - should be working (not tested)
var check = $(this).val();
if (this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'JSON',
data: {
value: check
},
success: function(data) {
boxes[check] = $(data);
$('#compare_box').append(boxes[check]);
}
});
} else if(!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
DEMO
Submit button onclick calling a function.( onClick="mandatoryNotes()" ).
Its taking a bit time to loading. So added a preloader script. Now the pre loader is working but not calling the function.
Requesting help.
Thank you
function mandatoryNotes()
{
document.getElementById("formsubmitbutton").style.display = "none"; // to undisplay
document.getElementById("buttonreplacement").style.display = ""; // to display
return true;
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
//code for calling page
{
var formvalue="invoiceAttributesDetailsFORM";
validateInput(document.invoiceAttributesDetailsFORM);
var queryString;
if(checkValidation=="true"){
//added by Nilanjana for 184932g
//alert("entered");
submitSpecialBidDetails(document.invoiceAttributesDetailsFORM);
queryString = "&EUAM_SELECTED_FORM=" + formvalue;
var legendURL = "/EUAM/ADRGateway?jadeAction=MANDATORY_NOTES_ACTION_HANDLER";
var winData = 'scrollbars=yes,resizable=yes,status=yes,width=500,height=500';
window.open("MandatoryNotes.jsp", "ADDVIEWNOTES",winData);
window.close();
}
}
<div class="em" id="formsubmitbutton">
<input type="button" name="Submit" value="Submit" class="buttonEm" onClick="mandatoryNotes()">
</div>
<div id="buttonreplacement" style="margin-left:30px; padding-top:15px; display:none;">
<img src="loadingSubmit.gif"alt="loading...">
</div>
Aren't you using any asynchronous technique like AJAX with XHR request to post the form. As your request would take time to run the pre-loader should be shown until the result appears .
I would recommend you to see JQuery ajax
You can write your submission code and start preloader before sending the request and stop it after the response is received.
$(document).ready(function(){
$('#submitbutton').on('click',function(){
var mydata = [];
var jqxhr = $.ajax({
url: '',
type: 'POST',
data: mydata ,
dataType: 'json',
contentType: 'application/json',
beforeSend: mandatoryNotes()
})
.done(function (ajax_data) {
RestoreSubmitButton();
})
.fail(function (jqXHR, textStatus) {
RestoreSubmitButton();
});
return false;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="em" id="formsubmitbutton">
<input type="button" name="Submit" value="Submit" id='submitbutton' class="buttonEm" onClick="mandatoryNotes()">
</div>
<div id="buttonreplacement" style="margin-left:30px; padding-top:15px; display:none;">
<img src="loadingSubmit.gif"alt="loading...">
</div>
I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?
Video:
My code:
This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.
<div class="form-group">
<label for="select"> Partner: </label>
<select id="select" name="select" class="searchselect searchselectstyle">
#foreach($partners as $i => $partner)
<option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
#endforeach
</select>
</div>
Here Is the second select box, with the error.
<div class="form-group" >
<label for="select2"> Hoofdgebruiker: </label>
<select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url = '/json/getusers';
var $post = {};
$post.id = $("select").val();
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: $post,
cache: false
}).done(function(data){
$('#select2')
.find('option')
.remove()
.end();
$.each(data, function(i, value) {
console.log(data);
$('#select2').append($('<option>').text(value.text).attr('value', value.id));
});
}
);
});
-
public function getusers(){
if(!isset($_POST['term'])){
$users = User::where('partner_id', $_POST['id'])->get();
}else{
$wildcard = '%'.$_POST['term'].'%';
$users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get();
}
$array = array();
foreach($users as $i => $user){
$array[$i] = array("id" => $user->id, "text" => $user->email);
}
return response()->json($array);
}
Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".
{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}
not like that
{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
I found a solution, which is the following:
<script type="text/javascript">
$(document).ready(function() {
$(".searchselect").select2();
search();
$("#select").change(function(){
search();
});
});
function search(){
var $post = {};
$post.id = $("#select").val();
$("#select2").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var query = {
term: params.term,
id: $post.id
};
return query;
},
url: '/json/getusers',
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
}
</script>
Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!
<script>
function autocomplet1() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#select01').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'barcode.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#barcode01').show();
$('#barcode01').html(data);
}
});
} else {
$('#barcode01').hide();
}
}
function set_item(item2) {
$('#select01').val(item2);
var customer = $("#customer").val();
$.post("sales/add", {"data[Sales][item]": item2 ,"data[Sales][customer_phone]": customer }, function (data) {
$('#details3').html(data);
$("#select01").val('');
});
// hide proposition list
$('#barcode01').hide();
}
</script>
<script>
// autocomplet : this function will be executed every time we change the text
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#customer').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'abc.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
}
function set_item(item1) {
$('#customer').val(item1);
$.post("sales/add", {"data[Sales][customer]": item1 }, function (data) {
$('#details').html(data);
});
// hide proposition list
$('#country_list_id').hide();
}
</script>
<div class="input_container">
<input type="text" id='customer' onkeyup="autocomplet()" name="data[Sales][customer]" class="input-small focused">
<ul id="country_list_id" style='height: 500px;'></ul></div></div>
<div class="content">
<div class="input_container">
<input type="text" id='select01' onkeyup="autocomplet1()" name="data[Sales][item]" class="input-small focused">
<ul id="barcode01" style='height: 500px;'></ul></div></div>
Above is an autocomplete script. Both script having same function set_time . If i changed function name as set_time1, then autocomplete is not working . How to resolve this issue? . I need to use two autocomplete in a single page.
Okay, since this is hard to explain in the tiny comments, I'll write it here.
Take that script :
function set_item(){
alert("Hello!");
}
function set_item(){
alert("Goodbye!");
}
set_item();
What do you think will happen? What will be alerted?
Answer : "Goodbye!", because the second function definition overrode the first one. You will never see the "Hello!" alert.
This is what happens when two functions have the same name. And you have two functions with the same name. Placing them in different <script> tags won't change anything, it's still the same scope.