Validation Script not getting called while using AJax - javascript

I am using below code on my main page ,where other pages are loaded using ajax with the help of TWO RADIO BUTTONS
<script>
function loadXMLDoc(str)
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
if(str=="Candidate")
{
xmlhttp.open("GET","creg.php",true);
}
else if(str=="Employer")
{
xmlhttp.open("GET","Empyr.php",true);
}
xmlhttp.send();
}
</script>
below script is written for FORM VALIDATION (written at end of main page),this script works only when main page loaded first time ,but when forms are getting loaded second time using ajax than this script is not working
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
As i know script is getting read at the time of page load ,but now Where should I write this script so that it works when I load forms using ajax,where i am going wrong?

Are you using validation engine? I will not prefere doing ajax call with pure javascript it looks messy.
jQuery(document).ready(function($) {
$('#registration').validate({
rules:{
email: {
email: true
},
password : {
minlength : 6
},
repassword : {
minlength : 6,
equalTo : "#password"
}
},
submitHandler: function(form) {
// do other things for a valid form
var post = {};
form_data = $(form).serialize();
//console.log(form_data);
//console.log(book_form);
if(post)
{
$.post(site_url+'/members/register',form_data,
function(response){
var res1 = $.parseJSON(response);
console.log(res1);
if(res1.success == true )
{
$('.success_message').html('You are successfully registered ').show();
window.location.href = site_url+'/pages/registerstep';
clear_form(form);
}
else
{
$('.error_message').html(res1.success).show();
//clear_form(form);
}
}
);
}
}
});
});
Use something like this. This will work. Reason why your code is not working after first load is because your validation is not triggering while form submit

You need to run the code again to bind the event handler, after the new element is inserted into the DOM. It is better to use cross platform javascript framework like jQuery, Prototypejs etc
You need to call the bellow javascript again from ajax response
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
Check here

Related

Ajax trying to execute PHP page brings me to a new page

I am trying to get a live chat working using PHP and mysql and AJAX. It is almost completely functioning, except I cant seem to figure out how to submit the chat message without reloading a page. I have a page, sendchat.php, that takes input from the previous page and enters the data into a database. I am trying to use a text input field and when the user clicks the enter key, it would execute the PHP page with the details needed to send to sendchat.php without actually loading or refreshing the page. This is what I have so far:
<form id="send-message-area">
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeydown="onChatEnter(this);"></textarea>
</form>
</div>
</td></tr></table>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
function onChatEnter(str) {
if(event.key === 'Enter') {
$.ajax({
type: "GET",
url: "sendchat.php?msg=" + str ,
success : function() {
// here is the code that will run on client side after running clear.php on server
}
});
}
</script>
All it does is try to load the url, but its not trying to find sendchat.php or send the data. Instead it just tries to load a blank page. Where am I going wrong here? Everything seems spelled correctly and case sensitive. I check if the user pressed enter when they press a key. If they did, I am loading an AJAX function to execute a PHP page. Yet, it is not doing that. Just for FYI, I do not want a button there to be clicked.
EDIT:
I tried the suggestions below and still nothing. I decided to try a different approach now. Still doesn't work.
<script>
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","sendchat.php?msg="+str,true);
xmlhttp.send();
}
}
</script>
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeypress="updatechat(this.value);"></input>
Try this:
$("#send-message-area").submit(function(e) {
e.preventDefault();
e.stopPropagation();
});
I am not sure how.. But I fixed it.. I think it had to do with giving the input a name along with the ID. See below:
<script language="javascript" type="text/javascript">
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
var planetloc = document.getElementById("loc").value;
chaturl = "sendchat.php?msg="+str+"&loc="+planetloc;
sendie.value="";
xmlhttp.open("GET",chaturl,true);
xmlhttp.send();
}
}
//-->
</script>
This was the code I used for the html:
<p>Your message: </p>
<input type='text' id='sendie' name='sendie' maxlength = '100' onkeypress='updatechat(this.value);'></input>
<input type='hidden' id='loc' name='loc' value='$chatroom'></input>";
I also added chaturl to combine the ajax page I needed along with the parameters passed to it. It seemed by creating a variable for that it solved other issues too.

How to pass ajax variable value to controller in codeigniter

Here i want to pass the 'q' value from ajax to controller function in codeigniter.
ajax code:
function getdata(str)
{
if (str == "") {
document.getElementById("yer").innerHTML = "";
return;
} else {
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) {
document.getElementById("bus").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo site_url('money_c/taxcalculator1'); ?>?q="+str,true);
xmlhttp.send();
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
}
}
controller:
function taxcalculator1()
{
$bt=$_GET['q'];
echo $bt;
}
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
As soon as you have started the Ajax request sending with this:
xmlhttp.send();
You leave the page with this:
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
… which aborts the Ajax request, removes the place you are trying to edit with innerHTML and destroys the JavaScript that would be trying to do that anyway.
If you want to use Ajax then:
Put the data you want to show to the user the response from taxcalculator1
Use onreadystatechange to show it to the user
Don't leave the page before that happens (remove the window.location line).
If you want to load an entirely new page:
Don't use Ajax
Just submit a form to a URL
Display the data you want the user to see (in the form of an HTML document) in the response to that request

JavaScript form submit to database using Ajax and Laravel route

I'm making a quiz website using Laravel, Javascript and Ajax and I made an add form function with JavaScript like this:
But I want to send the form data (to create a new quiz question) into my Laravel QuizController route using Ajax, after the focus on the form is lost or after an enter..
But I can't figure out how to do it.
My JavaScript/Ajax:
var limit = 1;
var count = 0;
var myButton = document.getElementById('myButton');
var container = document.getElementById('container');
function createQuestion() {
if(count < limit) {
var input = document.createElement("input");
input.type = 'text';
input.id = '';
input.setAttribute('class', 'form-control')
container.appendChild(input);
count++;
}
else {
alert ('Enter this question first before you can add another question!');
}
}
function storeQuestion() {
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)
{
//
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
My Laravel.blade:
<div class="form-group">
<div id="container"></div>
</div>
{!! Form::button('Add Quiz', array('onclick' => 'createQuiz()', 'class' => 'btn btn-default', 'id' => 'myButton', 'value' => 'Add question')) !!}
My QuestionController:
public function store(Quiz $quiz)
{
$input = Input::all();
$input['quiz_id'] = $quiz->id;
Question::create($input);
return Redirect::route('quizzes.show', $quiz->slug)->with('message', 'Question created.');
}
I hope someone can help me because I'm pretty stuck up with this problem for some time..
To use AJAX instead of standard HTTP POST you should catch enter and blur events.
How to catch enter is explained in first answer to input type text and onKeyDown not working under IE but in test for enter you should run storeQuestion
to add blur add :
<input type="text" name="item_code" onkeydown="test(event)" onblur="storeQuestion()">
Your store function should not return a Redirect::route but some status code or JSON string. If you use laravel 4 http://laravel.com/api/4.1/Illuminate/Http/JsonResponse.html that would just say "OK" or true or error
You should modify storeQuestion to add the new answer/edit/delete buttons to the list also. ( // )
A simpler way would be to not use AJAX but just submit the form with javascript after focus is lost by attaching an onblur event handler to the textbox.
var req = new XMLHttpRequest();
queryString = "access_token=" + access_token + "&data=" + data;
req3.open('GET', '/path/of/laravel/route?' + queryString, true);
req3.send(queryString)

Replacing content using AJAX when clicking a link

I want to use AJAX to replace the contents of a div. Although the application is fairly complex, I have tried to dumb it down in isolation so that I can get the basic concept working first.
For now, I just want to replace a div as per the PHP file...
<?php
$id = $_GET['id'];
if ($id = 1)
{
$text = 'This is some text';
}
elseif ($id = 2) {
{
$text = 'This is a lot more text than the first text!';
}
elseif ($id = 3) {
{
$text = 'This is a lot more text than the first text, and a load more than the third as well!!';
}
echo $text;
?>
Fairly simple stuff really. So here's my HTML file...
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">I want this content replacing</div>
ID: 1<br>
ID: 2<br>
ID: 3
</body>
</html>
I realise what is there will never work as I've modified some stuff I found online, but basically I'm looking to pass a variable such as the ID in the link to the AJAX script to replace the contents of the div.
How do I get this working? Is there a better alternative to using <a> tags?
Using jQuery
Your HTML
ID: 1
Javascript
// Delegate click event
$(document).on('click', 'a.ajax', function(){
var el = $(this);
$.ajax({
url: 'ajax.php',
data: {id: el.data('id')},
}).done(function(response){
$('#myDiv').html(response);
});
return false;
});
I'll answer your question using Vanilla JavaScript rather than using the jQuery AJAX Helper. Although it's very good - but learning the Vanilla way will give you a good idea of what the libraries do to aid you.
Firstly, you are making an Ajax call but albeit, an Empty one.
"Query" parameters is what $_GET is based on, are formated like:
?Key=Value&KeyTwo=SomeOtherValue
Which in PHP, Translates too:
Array
(
[Key] => Value
[KeyTwo] => SomeOtherValue
)
This'll need to be passed along with the xmlhttp.send() for it to make an successful ajax call, with Data.
But to collect this data in the first place, you must collect it with your HTML:
<!-- Notice how the <a> tags now have attributes attached, the id="" -->
ID: 1<br />
ID: 2
<script>
function loadXMLDoc( Id ) {
/**
* Id is the <a href="#" id="3" collected
* when onclick="loadXMLDoc()" is pressed
**/
var xmlhttp,
DataId = Id.attributes.id.value;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
/**
* Notice the ?id="+ dataId +"
* It's passing through the ID Collected
**/
xmlhttp.open("GET","ajax.php?id="+ dataId +"",true);
xmlhttp.send();
}
</script>
Although this code above is very inefficient, you would be much better in JavaScript & Programming in general to keep things generic. By modifying your code to:
ID: 1<br />
ID: 2
<script>
function getId() {
alert( this.attributes.id.value );
//Click on id="2", alerts '2'
}
/**
* We find all the HTML tags with the
* attribute that has 'class="idlistener"
* attached, we 'bind' it to a function called
* getId()
**/
var IdListener = document.getElementsByClassName('idlistener');
for( var x = 0; x < IdListener.length; x++ ) {
IdListener[x].addEventListener( 'click', getId, false );
}
</script>
Demo: Fiddle
Lastly, It does look to me you've discovered this AJAX Code from W3Schools.com. I think you'll find every StackOverflow Web Developer that would agree with me - Don't learn from this Site!
General format for replacing html content with the response from an ajax call:
$.ajax({
url: yourUrl,
method: 'get', // or 'post'
success: function (response) {
$('#myDiv').html(response);
}
// other ajax options here if you need them
});
You dont need to use ajax for that. Just use the following in the condition. Dont forget to call the jquery js file on the header. Otherwise jquery wont work:
echo '<script>$("#myDiv").html("This is some text")</script>';

Call Javascript method from .ashx file

From my previous question(Create json using JavaScriptSerializer), In .ashx file I am printing the json object using:
context.Response.ContentType = "application/json";
context.Response.Write(json);
I am calling this .ashx file from default.aspx which has some javascript function inside its <head> tag.
My question is :
How will I be able to call the javascript function from .ashx file after context.Response.Write(json);?
UPDATE:
My ultimate goal is to achieve Server Side Processing for DataTable.In that i want to bind the rows with context menu using javascript function.
For that I am using following code to call .ashx file:
$('#example').dataTable({
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '/data.ashx'
});
Are you using ajax requests? In that case, you can use the success method that is available in javascript, as in the following example from w3schools:
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
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)
{
// You can call your custom method here...
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.asp?q="+str,true);
xmlhttp.send();
}
Or if you are using jquery:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
// You can call your custom method here...
$(this).addClass("done");
});
UPDATE
Check out: http://datatables.net/usage/callbacks The method you can use is: fnInitComplete
e.g.
$('#example').dataTable({
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '/data.ashx',
'fnInitComplete' : function() {
alert('Your menu population code here!');
}
});
You could use
eval
to evaluate the response as javascript on client-side. But I doubt you really need or want this, it might not be a very elegant solution. So what you want to archieve?

Categories