response from php script disappears after jquery button click event - javascript

Here I posted one variable to PHP script. Response from php script I am writing to some div. But after button click, instantly the response disappears:
When I do alert(arabic); it displays but as I close prompt, it disappears.
Why does it reload the page after response from php script?
$( "#submit" ).click(function() {
var cat = $("#cats option:selected").html();
// alert(test);
var arabic = document.getElementById("arabic").value;
//alert (arabic)
dataInsert(arabic);
});
function dataInsert(arabic)
{
var xmlhttp;
//alert("hi");
show.innerHTML = '';
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
//document.getElementById("old-records").innerHTML = "";
if (xmlhttp.readyState == 4 && xmlhttp.status==200)
{
var div2 = document.getElementById("show");
div2.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","koove_insertpost_db.php");
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('arabic=' + arabic ) ;
//alert(arabic);
}

It looks like your button is trying to submit something, thus overlapping your callback function. You might want to use the parameter event to stop it's propagation.
Check this code:
$( "#submit" ).click(function(event) {
event.stopPropagation();
var cat = $("#cats option:selected").html();
//alert("test");
var arabic = document.getElementById("arabic").value;
//alert (arabic)
dataInsert(arabic);
return false;
});
}
You should also return false at the end of the callback function, in order to completely stop processing the event after your instructions. This is the key to perform your dataInsert() function without interruption.

Are you using jQuery? looks like it with the $( "#submit" ).click(function() {});
why not make life easy and just use
$( "#submit" ).click(function() {
var arabic = $("#arabic").value();
$.post("koove_insertpost_db.php",{"arabic" : arabic}, function( data ) {
$('#show').html(data);
});
});
http://api.jquery.com/jquery.post/
you can also check the success status etc for data validation from the server.
I cant comment yet so i believe #feijones has the answer! ( especially return false; )
p.s. Alert works because it halts the execution of the JavaScript until you close the dialog, which then submits the form and reloads the page.

Related

e.preventDefault & e.stopImmediatePropagation not working

I got a problem where preventDefault() are not working properly.
This ajax request is working and I get the php page to show in the selected div, but the preventDefault is not working. For the map area that have a link I got redirected to the page, and for the ones that have no link, the address bar got an added "#" to the url. (in this last case, the ajax calls get correctly appended to the div, but still, preventDefault not doing its job).
After doing some digging I found out something : stopImmediatePropagation()
I was really hyped by this for a few seconds before seeing that it had absolutely no effect on my side too. I must be missing something but I can't find it.
More infos: The website is on joomla 3x, on localhost and showing K2 itemview categories on this ajax request.
Any help really really welcomed.
window.addEventListener('DOMContentLoaded', (event) => {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
let links = document.querySelectorAll('map area')
console.log(links)
for (let i = 0 ; i < links.length ; i++) {
let link = links[i]
link.addEventListener('click', function (e) {
e.preventDefault
e.stopImmediatePropagation()
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('maploc-loc').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", '../index.php?option=com_k2&view=itemlist&layout=category&task=category&id=1&id=Itemid=1',true);
xmlhttp.send();
})
}
});

how to change ckeditor value by javascript

my textarea is:
<textarea class="content" name="content" id="content" rows="10" cols="80"></textarea>
and initializing it as:
<script>
$(document).ready(function(){
///CKeditor
CKEDITOR.replace( 'content', {
height: 320,
} );
});
</script>
now i am getting data in an array and then changing the values of different elements according to it. the array that i am getting is:
[{"id":"5","subject_Id":"1","topic_id":"1","question_type_id":"4","exam_id":"1","difficulty_id":"1","year_id":"1","essay":"","right_marks":"2","negative_marks":"3","question":"question 2","options":"Ans CC~Ans BB~Ans AA~","correct_answer":"Ans BB~"}]
[{"id":"6","subject_Id":"1","topic_id":"1","question_type_id":"4","exam_id":"1","difficulty_id":"1","year_id":"1","essay":"","right_marks":"2","negative_marks":"3","question":"question 1","options":"<img alt=\"\" src=\"\/corePhp\/examinationsystem\/assets\/ckeditor\/kcfinder\/upload\/images\/profile-icon-9(1).png\" style=\"height:512px; width:512px\" \/>~Ans BB~Ans AA~","correct_answer":"Ans BB~"}]
[{"id":"18","subject_Id":"1","topic_id":"1","question_type_id":"1","exam_id":"1","difficulty_id":"1","year_id":"2","essay":"Essay 5","right_marks":"2","negative_marks":"3","question":"Brass gets discoloured in air because of the presence of which of the following gases in air?","options":"Oxygen~Hydrogen sulphide~Carbon dioxide~Nitrogen","correct_answer":"\"Hydrogen sulphide\""}]
then in my javascript
<script type="text/javascript">
function dbDataQuestion(quesId) {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var convert=JSON.parse(xmlhttp.responseText);
//console.log(convert[0].subject_Id);
document.getElementById("selectSubject").value=convert[0].subject_Id;
document.getElementById("selectTopic").value=convert[0].topic_id;
document.getElementById("selectQuestionType").value=convert[0].question_type_id;
document.getElementById("selectExam").value=convert[0].exam_id;
document.getElementById("selectYear").value=convert[0].year_id;
document.getElementById("selectDiffLvl").value=convert[0].difficulty_id;
document.getElementById("txtRightMarks").value=convert[0].right_marks;
document.getElementById("txtNegMarks").value=convert[0].negative_marks;
console.log(convert[0].question_type_id);
console.log(convert[0].question);
CKEDITOR.on("instanceReady", function(event)
{
//CKEDITOR.instances.content.insertHtml(convert[0].question);
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
if(convert[0].essay){
document.getElementById("txtEssayName").value=convert[0].essay;
document.getElementById("radioEssayYes").checked = true;
}
else{
document.getElementById("txtEssayName").value=convert[0].essay;
document.getElementById("radioEssayNo").checked = true;
}
}
}
xmlhttp.open("POST","process/questions/quesDetails.php?quesId="+quesId, false);
xmlhttp.send();
}
</script>
as you can see i am consoling console.log(convert[0].question); in which i am getting correct data, but when i am writing CKEDITOR.instances.content.setData(convert[0].question); its not updating ck editor's value.
actually the function "dbDataQuestion(quesId)" is being called once at the time of page load at that time its working fine the CKEditor is showing question 2 which you can see is in the first array, after that I have a button on which I am getting the next array and so on. on clicking this button array is getting displayed in the console as well as other element are changing its values but CKEditor is showing the same old value that is question 1 and not question 2 on consoling console.log(convert[0].question); I am getting "question 2" which is correct.
Note: function dbDataQuestion(quesId) is where from where i am getting above mentioned array and on xmlhttp.readyState === 4 && xmlhttp.status === 200 of the function i am changing the values of the elements which includes ck editor. its once called at the time of page load and then its being called on a button click:
<button type="button" class="btn btn-xs btn-success" onclick="fetchQuestionDetails('next')">Next</button>
I am calling all my scripts at the bottom of the page.
thanks in advance.
Update:
I noticed that instanceReady event is not getting triggered by calling the function when the button is pressed. I altered my code to check
console.log(convert[0].question);
CKEDITOR.on("instanceReady", function(event)
{
console.log(convert[0].question);
console.log("sss");
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
only console.log(convert[0].question); is getting triggered and none of the other console statements. What am I doing wrong?
first thanks a lot #Muhammad Omer Aslam for responding, so quickly. i have not tried your answer but i ll try it and comment if it solved the problem or not but i found a way to make it work i removed instanceReady event and wrote
setTimeout(function(){
CKEDITOR.instances.content.setData(convert[0].question);
}, 1000);
and its working fine. but again thanks #Muhammad Omer Aslam
try it the following way by moving the initialization inside the ajax response section.
$(document).ready(function () {
dbDataQuestion(quesId);
});
Your function will look like this.
function dbDataQuestion(quesId) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var convert = JSON.parse(xmlhttp.responseText);
//console.log(convert[0].subject_Id);
document.getElementById("selectSubject").value = convert[0].subject_Id;
document.getElementById("selectTopic").value = convert[0].topic_id;
document.getElementById("selectQuestionType").value = convert[0].question_type_id;
document.getElementById("selectExam").value = convert[0].exam_id;
document.getElementById("selectYear").value = convert[0].year_id;
document.getElementById("selectDiffLvl").value = convert[0].difficulty_id;
document.getElementById("txtRightMarks").value = convert[0].right_marks;
document.getElementById("txtNegMarks").value = convert[0].negative_marks;
console.log(convert[0].question_type_id);
console.log(convert[0].question);
///CKeditor
CKEDITOR.replace('content', {
height: 320,
});
CKEDITOR.on("instanceReady", function (event) {
//CKEDITOR.instances.content.insertHtml(convert[0].question);
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
if (convert[0].essay) {
document.getElementById("txtEssayName").value = convert[0].essay;
document.getElementById("radioEssayYes").checked = true;
} else {
document.getElementById("txtEssayName").value = convert[0].essay;
document.getElementById("radioEssayNo").checked = true;
}
}
}
xmlhttp.open("POST", "process/questions/quesDetails.php?quesId=" + quesId, false);
xmlhttp.send();
}

execute javascript onload rather than onchange

I have am HTML form in a PHP page. The form has various inputs. One of the inputs has an onchange event:
<input size=10 type=number id=sku1 name=sku1 onchange="showUser(1, this.value);showWhse(1, this.value)">
This calls the following function:
<script type="text/javascript">
function showUser(userNumber, str)
{
if (str=="")
{
document.getElementById("txtHint" + userNumber).innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("txtHint" + userNumber).innerHTML=xmlhttp.responseText;
var responseText = xmlhttp.responseText;
var description = responseText.substring(12, responseText.indexOf(",Warehouse:"));
var warehouse = responseText.substring(responseText.indexOf(",Warehouse:")+11, responseText.indexOf(",SellingUnits:"));
var sellingUnits = responseText.substring(responseText.indexOf(",SellingUnits:")+14);
document.getElementById("whse" + userNumber).innerHTML = warehouse;
document.getElementById("txtHint" + userNumber).innerHTML = description;
document.getElementById("su" + userNumber).innerHTML = sellingUnits;
}
}
xmlhttp.open("GET","getdata1.php?q="+str,true);
xmlhttp.send();
}
</script>
This works 100%. if however, the input is populated by a session variable, and the page is refreshed, how can I get the script to execute again onload, without an onchange event?
so when the page is first visited, id the input has a value, execute the script?
Just execute the function onload?
window.onload = function init() {
showUser(1, document.getElementById("sku1").value);
}
You may also use the onload attribute of your document's body, or add the init function as an event handler to DOMContentLoaded. But I'm sure you already have some functions which are executed onDOMready.
you can also use the ready function from the jquery
$(document).ready(function() {
showUser(1, $("#sku1").val());
});
Well, you can use the onload event. You may also want to consider using Jquery's document.ready functionality. The difference can be found here. Also, Jquery provides a much more concise syntax for accessing your form elements
In either case, you would probably simply need function that does something like checking the field has a value.
<script type="text/javascript">
function showUserOnLoad()
{
var inputValue = $('#sku1').val();
if(inputValue != '' && inputValue != null)
showUser(1, inputValue);
}
function showUser(userNumber, str)
{
...
}
</script>

How do I use ajax to auto refresh a section of page without manually invoking a function within javascript?

var xmlhttp;
//Set up ajax first so he knows which guy to play with
function loadXMLDoc(url,cfunc)
{
//Code to catch modern browsers
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//Code to catch crap browsers
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//Set up
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
//Set a function to deploy when something calls myFunction()
function myFunction()
{
loadXMLDoc("../../../support/ajaxTest.txt",function()
{
//Fires off when button pressed
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText;
setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 );
}
});
}
I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines.
function autoRefresh()
{
var url = "../../../support/ajaxTest.txt";
var target = document.getElementById("statusRefresh");
var doRefresh = function()
{
loadXMLDoc(url, function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
target.innerHTML=xmlhttp.responseText;
}
}
});
setInterval( doRefresh, 5000 );
}
and
document.onload = autoRefresh;
more information is needed such as what is your goal, what do you currently have......what are you trying to do......If its a script thats triggered by something from example a user viewing your page or click a button then use that button to triiger the function to auto refresh
Another way is to use a crob job

How make ajax update every (n) number of seconds with out using jquery but using javascript?

I'm trying to hava a javascript poll the server every (n) number of seconds how would I do this with javascript?
Assuming you are using jQuery:
var seconds = 5;
setInterval(function(){
$.ajax({
url: 'something.something',
data: 'something'
});
}, seconds * 1000)
Without jQuery:
var seconds = 5;
setInterval(function(){
some_ajax_function();
}, seconds * 1000)
Or as #Felix suggests below:
var seconds = 5;
some_ajax_function(seconds);
function some_ajax_function(seconds){
..ajax
onsuccess: setTimeout(function(){some_ajax_function(seconds);},
seconds * 1000)
}
It is simple with the following function
window.setInterval("yourfunctionWithAjaxRequestETC", time_in_ms);});
Enjoy :)
first, we need to make our ajax request object. We need to take different browsers into account.
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
Now, we'll write our function to send a request
function askData(){
xmlhttp.open("GET","myinfosource.php",true); // opens a Get request to the url myinfosource.php, and sets the request to asynchronuous.
xmlhttp.send(); //sends the request
}
Now, let's write an event handler that changes the HTML when the info comes back.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) //if we reveived data (readystate 4 means that information was received. status 200 is the status of the HTTP request, where 200 means 'ok'.
{
//insert data into the div you want.
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And finally, we set an interval on the first function we wrote to make it run every x seconds.
setInterval('askData',10000);
this will refresh your data.
I hope you see now why most people use a framework such as jquery to use AJAX. One of the major advantages of js frameworks is that they work around browser incompatibilities so that you, as the developer can concentrate on the task at hand.
I assume that there is a servlet with URL Pattern /UpdateCount is configured in web.xml to provide dynamic data/content and there is a div element countStatDiv in the jsp page.
The following code refreshes/updates the content of countStatDiv at every 30 seconds using GET method and variable seconds value can be changed according to the need:
<script>
var request;
var seconds=30;
function getRequestObject(){
setInterval(function() {sendRequest();},seconds*1000);
if (window.ActiveXObject){
return (new ActiveXObject("Microsoft.XMLHTTP"));
} else if (window.XMLHttpRequest){
return(new XMLHttpRequest());
} else {
return (null);
}
}
function sendRequest(){
request = getRequestObject();
request.onreadystatechange = handleResponse;
request.open("GET", "../UpdateCount", true);
request.send(null);
}
function handleResponse(){
if((request.readyState == 4)&&(request.status == 200)){
var serverResponse = request.responseText;
var statCtrl=document.getElementById("countStatDiv");
statCtrl.innerHTML=serverResponse;
}
}
</script>

Categories