MsgBox in Jquery, pass info to PHP and retrieve results - php

As you can see i am noob at jquery / javascript, i need to pass variable to GET or POST written in form and the result from php need to be passed to jquery, i started to write smthing as below, but it doesnt work.
anyone help me out please
// id and settings for msg box
$("#registerin").click(function() {
$.msgbox("<p>In order to process your request you must provide the following:</p>", {
type : "prompt",
inputs : [
{type: "text",label: "Insert your Name:", value: "George", required: true},
],
buttons : [
{type: "submit", value: "OK"},
{type: "cancel", value: "Exit"}
]
}, // id and settings for msg box - end
function(name) {
// checking if name field has been set
if(name) {
// pass from field to php $_GET['name_php'] variable
$.get("form.php", {name_php: name },
**// rewriten**
function(data) {
if (data){
// inline the data creation/insertion
$.msgbox($('#textbox').html(data), {type: "info"});
} // if data end
}); // function data end
**// rewriten**
} // if name end
}); // function name end
}); // registerin click

$.get is an asynchronous function call, so that means that code below it is not garunteed to be run AFTER it has been proccessed. your callback function inside the $.get call should look like this:
function(data) {
if (data){
// inline the data creation/insertion
$.msgbox($('#textbox').html(data), {type: "info"});
}
}

Related

Updating Chart.js Datasets - Array not re-initializing (Jquery / PHP)

I am using Chart.js (v 3.3.2) to display a bar graph (myChart) with a dropdown filter. I have an event listener for my dropdown to update the PHP/SQL query to fetch the correct data - this works perfectly.
But my graph still displays the old data after the update (With disabling cache). The ajax function is POST'ing correctly. Following the chart.js docs on updating the datasets :: Updating Charts
I declare chart, label, data in my ajax: success function's params.
In my success function:
success: function (chart, label, data) {
myChart.data.labels.push(label); //Push the labels for chart
myChart.data.datasets.forEach((dataset) => { //Push data for each dataset
dataset.data.push(data); });
console.log(myChart.data.labels); // Log new labels
console.log(myChart.data.datasets);// Log new array
myChart.update(); // Update my chart
}
I look at the response from my PHP fetch file, and the correct data can be seen in the the inspector. But when looking at the data in my console log, I am still seeing the old data.
So I approached this all wrong. The select.on.change() should have been called outside the function, and when executing, call the showSuccessRate() function.
Here is the working code:
$(document).ready(function(){
$('#selectTop')
.on('change', // When the user changed the select option, run this
function () {
$('#clisuccessrate-chart').remove(); //Remove the chart canvas (because it would have loaded when document ready)
$('div#clisuccessrate-container').append('<canvas id="clisuccessrate-chart" height="200"></canvas>'); // Add the canvas back into the html
showSuccessRate(); // Call the function to draw the chart
})// end onchange event
showSuccessRate(); // Make the Bar Chart when document is ready
function showSuccessRate(){ // Build Bar Graph
{var selectedOption = $('#selectTop').children('option:selected').val(); // Get the value of the option, use this value to set limit in PHP SQL Query
$.ajax("database/cliSuccessFail-filter.php", {data: {topSelect: selectedOption} ,method:'POST', success: function (data) {
console.log('The selected option value is: ' + selectedOption); // Log the value to check response
var mx_cli = [];
var mx_success = [];
var mx_failure = [];
var mx_attempts = [];
// ^ Declare empty array
for (var i in data) {
mx_cli.push(data[i].mx_cli);
mx_success.push(data[i].mx_success);
mx_failure.push(data[i].mx_failure);
mx_attempts.push(data[i].mx_attempts);
};
// ^ Populate the arrays
var csf_datasets = {
labels: mx_cli, // Assign label
datasets: [{
backgroundColor: '#007bff',
borderColor: '#007bff',
data: mx_success,
label: 'Successful'
},
{
backgroundColor: '#ced4da',
borderColor: '#ced4da',
data: mx_failure,
label: 'Unsuccessful'
}
]
};
var csf_options = {
maintainAspectRatio: false,
};
var csf_config = {
type: 'bar',
data: csf_datasets, // Bind dataset
options: csf_options, // Bind options
}
var $cliSuccessRateChart = $('#clisuccessrate-chart'); // Get the canvas ID
var myChart = new Chart($cliSuccessRateChart, csf_config); // Draw the chart
} }) // END POST
}
}// END FUNCTION showSuccessRate
}); //End document.ready()

Twitter Typeahead: Suggestion list goes away when ajax fetching result for new keyword

I am using Twitter Typeahead (v0.11.1). I have configured an ajax call to get suggestion list upon typing each letter in textbox.
On entering every character an ajax call gets send and it brings results. If typed continuously in textbox then previous ajax calls are aborted and new ajax call is sent on pause of last character entered.
So, while this process if found some results after two characters and paused then it showing suggestion list. Now, if continue to type then exiting list goes away.
I would like to retain suggestion list for each ajax call till user not selected an item from it.
Below is the code used:
var typeahead_pre_written_xhr = null;
var helper_typeahead = $( "#input-box" ).typeahead({
highlight: true,
minLength: 0
},
{
name: "Search Suggestions",
display: ["title"],
templates: {
empty: function () {
return '<div class="tt-suggestion tt-selectable">No matching helper comment found</div>';
}
},
source: function (query, processSync, processAsync) {
if( typeahead_pre_written_xhr != null ) {
typeahead_pre_written_xhr.abort();
typeahead_pre_written_xhr = null;
}
action_url = "suggestion_list";
return typeahead_pre_written_xhr = $.ajax({ cache: false
, url: action_url + query
, type: 'POST'
, data: { 'search': query }
, dataType: 'json'
, success: function (data)
{
return processAsync(data.res);
}
});
}
}).bind("typeahead:selected", function(evt, item) {
// do some stuff
});

select2 on success retrieve newly created tag id

In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_tags').on("change", function(e) {
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag " + e.added.id + "?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.

Form submission using ajax and page view moderation after the submission

At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.

load a post into a div

In effect, I want to say this:
$('#results1').html($.post("videoloaderurl.php", { id: byName } ));
Obviously, the code above doesn't work.
where results1 is a div and videoloaderurl.php returns html.
You should provide success callback function for post function, which could add retrived data to the div.
$.post("videoloaderurl.php", { id: byName }, function(data) {
$('#results1').html(data);
});
$.post() is an AJAX method - meaning it is Asynchronous. You have to wait for the data to be returned and do something in the callback rather than the function returning the value.
$.post("videoloaderurl.php", { id: byName }, function(d){
$('#results1').html(d)
});

Categories