jQuery, JavaScript - Network Error? - javascript

I am working on building a Javascript/jQuery and AJAX website. However, while testing I am encountering the following error:
Timestamp: 6/11/2016 10:13:45 AM
Error: NetworkError: A network error occurred.
To me, the most obvious culprit would be the AJAX call made in my script; however, I tried commenting it out and still received the same error. When the website is first loaded it displays three alert boxes (selection=category&detail=test, and so on), but then the error appears and changing the selection does not trigger the alert.
Here is my main page:
<?php
include('header.php');
?>
<div id='mainContent'>
<?php /* if(!$_SESSION['admin']) {
echo "<p>You do not have permission to view this page!</p>";
} else { */
echo "<form method='post' action='addItem.php'>
<div class='form-group'>
<label>Category</label>
<select id='categorySelection' name='categorySelection'>
<option value=1>Playstation</option>
<option value=2>Wii</option>
<option value=3>Gamecube</option>
<option value=4>N64</option>
<option value=5>Other Console</option>
<option value=6>DS</option>
<option value=7>Game Boy</option>
<option value=8>Other Handheld</option>
<option value=9>DVD</option>
</select>
</div>
<div class='form-group'>
<label>Item</label>
<select id='itemSelection' name='itemSelection'>
</select>
</div>
<div class='form-group'>
<label>Condition:</label>
<select id='conditionSelection' name='conditionSelection'>
<option value=1>Acceptable</option>
<option value=2>Good</option>
<option value=3>Very Good</option>
<option value=4>New</option>
</select>
</div>
<div class='form-group'>
<label>Price: </label>
<input id='itemPrice' type='text' name='itemPrice' />
</div>
<div class='form-group'>
<label>Description: </label>
<textarea id='itemDescription' name='itemDescription'></textarea>
</div>
</form>";
// }
?>
</div>
<script>
function selectionHandler(selectedAction, selectedValue) {
var gameData = "selection=" + selectedAction + "&detail=" + selectedValue;
alert(gameData);
$.ajax({
type: 'POST',
url: 'filter.php',
data: gameData,
success: function(returnData) {
if(selectedAction == 'category') {
$('#itemSelection').html(returnData);
} if(selectedAction == 'game') {
$('#itemPrice').val(returnData)
} else {
$('itemDescription').val(returnData);
}
} // end return
}); // end ajax
} // end handler
$(document).ready(function() {
$("#categorySelection").on("change", selectionHandler('category', "test" ) ) ;
$("#itemSelection").on('change', selectionHandler('game', "test" ) );
$("#conditionSelection").on('change', selectionHandler('condition', "test" ) );
}); // end ready
</script>
<?php
include('footer.php');
?>
and my PHP
<?php
include("header.php");
$db = new pdoAccess("localhost","root","");
$selection = $_POST['selection']; // either game, category, or condition
$detail = $_POST['detail'] // either categoryID or ISBN/Item ID
if($selection == 'category') {
$products = $db->filterByCategory($detail);
$html = "";
foreach($products as $product) {
$html += "<option value={$product->upc)}>$product->title</option>";
}
return $html;
} elseif ($selection = 'game') {
return $db->getProductPrice($detail);
} else {
return $db->getCategoryDescription($detail);
}
?>
Thanks!
EDIT: It should be noted that I also tried other events such as focusout and select. Same issue.

In php string cocatinating is by dot . and use quotes also change here like this
$html .= "<option value='{$product->upc)}'>{$product->title}</option>";
Also use double == to compare here
} else if ($selection == 'game') {
Use echo in ajax instead of return

Related

calling subcategories when categories selected in codeigniter using ajax giving error

i have a simple form in codeigniter website where am trying to display sub categories when categories are selected, i did the following code:
$(document).ready(function() {
$('#country').change(function() {
var country_id = $('#country').val();
if (country_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>index.php/homecontroller/fetchstate",
method: "POST",
data: {
country_id: country_id
},
success: function(data) {
$('#state').html(data);
$('#city').html('<option value="">Select Brand</option>');
}
});
} else {
$('#state').html('<option value="">Select Category</option>');
$('#city').html('<option value="">Select Brand</option>');
}
});
});
<form action="" method="post">
<label for="inputEmail4">Category</label>
<select id="country" class="form-control" name="cname" aria-label="Default select example">
<option>Select Category</option>
<?php
foreach($listcategory as $vals){
echo '<option value="'.$vals->name.'">'.$vals->name.'</option>';
}?>
</select>
<label for="inputEmail4">Brand</label>
<select class="form-control" name="sname" id="state">
<option value="">Select Brand</option>
</select>
i have the controller and model like below:
function fetchstate()
{
if($this->input->post('country_id'))
{
echo $this->excel_import_model->fetch_state($this->input->post('country_id'));
}
}
function fetch_state($country_id)
{
$this->db->where('inventorycategory', $country_id);
$this->db->order_by('name', 'ASC');
$query = $this->db->get('inventorybrand');
$output = '<option value="">Select Brand</option><option value="None">None</option>';
foreach($query->result() as $row)
{
$output .= '<option value="'.$row->name.'">'.$row->name.'</option>';
}
return $output;
}
now here the issue is when i select the category it doesnt display sub category, i get the following error:
POST http://localhost/letsship/index.php/homecontroller/fetchstate 500 (Internal Server Error)
can anyone please tell me what is wrong in here, thanks in advance

How to keep jQuery auto populated dropdown result selected?

I have this dynamic dropdown which fetches result on selection of one select menu, but the challenge I am facing after it auto populates the results on the second dropdown on submit of form the value of second select disappears. How to make it not disappear even after submit?
Here is my HTML & PHP
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="job_category">Select Job Category</label>
<select name="job_category" id="category" class='form-control'>
<option value='' selected='selected' disabled='disabled'>Select Job Category</option>
<?php
$sql="select * from job_category ";
foreach ($db->query($sql) as $row) {
?>
<option value='<?php echo $row[cat_id]; ?>' <?php if($job_category == ''.$row[cat_id].'') echo 'selected="selected"'; ?>><?php echo $row[cat_name]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class='row form-group'>
<div class='col-md-12'>
<label class='sr-only' for='job_subcategory'>Select Job Industry</label>
<select name='job_subcategory' id='sub-category' class='form-control'>
<option value='' selected='selected' disabled='disabled'>Select Job Industry</option>
</select>
</div>
</div>
Here is my JQ
$(document).ready(function() {
$('#category').change(function(){
var cat_id=$('#category').val();
$('#sub-category').empty();
$.get('fetchCategories.php',{'cat_id':cat_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#sub-category").append("<option value='" + value.subcat_id +"'>"+value.subcat_name+"</option>");
});
}, "json");
});
});
And my fetchCategories.php
#$cat_id=$_GET['cat_id'];
//$cat_id=2;
/// Preventing injection attack ////
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
}
/// end of checking injection attack ////
require "includes/config.php";
$sql="select subcat_name,subcat_id from job_subcategory where cat_id='$cat_id'";
$row=$db->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
$main = array('data'=>$result);
echo json_encode($main);
You can use localStorage to store the current value which is selected by user on change of select-box and then when your page gets reload just fetch the stored data from localStorage and then call your ajax to retrieve required data.
Your jquery code will somewhat look like below (Sorry for any syntax error) :
$(document).ready(function() {
//check if there is any value in localStorage
if (localStorage.getItem("save") != null) {
//get that value
var value = localStorage.getItem("save");
console.log(value);
//set value in selected box
$("#sub-category").val(value);
}
//onchange of subcategory
$('#sub-category').change(function() {
var values = $(this).val();
localStorage.clear(); //clear previous data
localStorage.setItem("save", values); //add data to storage
});
$('#category').change(function() {
var cat_id = $('#category').val();
$('#sub-category').empty();
$.get('fetchCategories.php', {
'cat_id': cat_id
}, function(return_data) {
$.each(return_data.data, function(key, value) {
$("#sub-category").append("<option value='" + value.subcat_id + "'>" + value.subcat_name + "</option>");
});
}, "json");
});
});

JavaScript from ajax modified file doesn't work in main page

I have a problems with a form and ajax behavior when I populate my dynamic div using JavaScript.
I have a drop box which contains different time periods and it triggers JavaScript function which modifies the container div based on provided value.
The problem is that the POST behavior of the form and all JavaScript elements doesn't work in the main file.
Here is the code. I simplified it to emphasize the problem.
this is the drop Box:
//jQuery for datePicker comes here
<select id="QSelector" method="post" onchange="populateDiv(this.value)">
<option value="0">All Values</option>
<option value="1">Sets for 1</option>
<option value="2">Sets for 2</option>
<option value="3">Sets for 3</option>
<option value="4">Sets for 4</option>
</select>
<div id="OUtputDiv" ></div>
here is the javascript function:
function populateDiv(id){
var xmlhttp;
if(window.XMLHttpRequest){//safari, chrome, opera, ffox
xmlhttp=new XMLHttpRequest();
}
else{//IE
xmlhttp=ActiveXObject("Microft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("OUtputDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../scripts/supportFile.php?ID=" + id, true);
xmlhttp.send();
}
And here is the content of the support file. don't mind the id variable it does some logic (ant it works), but I removed it because it's irrelevant to a given problem.
<?php
$Id= $_GET['ID'];
echo "<script> alert('it works'); </script>";
echo "<form name='AddForm' class='AddForm' method='post' >";
echo "<span > Date: </span> <input type='textbox' id='datepicker' name='datepicker' > ";
echo "<input type='submit' name='SubBtn' value='Save' >";
echo "</form>";
if(isset($_POST['SubBtn']))
{
echo $_POST["datepicker"];
}
?>
Nether JavaScript or JQuery does not work from the main file. And form does not post anything if I press the save button.
Can anyone suggest how can I make it responsive in the main file where I call ajax function from?
Avoid using IE5/6 support, use jQuery instead:
The problem is that you put all code in the same page, it will not work in that way, you need to make 2 files, 1 for post 1 for result
Good:
test_post.php
<?php
$Id = $_POST['id'];
if(!empty($Id)){
$result = "
<script> alert('it works'); </script>
<form name='AddForm' class='AddForm' method='post' >
<span > Date: </span> <input type='textbox' id='datepicker' name='datepicker' >
<input type='submit' name='SubBtn' value='Save' >
</form>
";
echo json_encode(array('status' => 'success', 'result' => $result));
}
?>
test.php
<select id="QSelector">
<option value="0">All Values</option>
<option value="1">Sets for 1</option>
<option value="2">Sets for 2</option>
<option value="3">Sets for 3</option>
<option value="4">Sets for 4</option>
</select>
<div id="OUtputDiv" ></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var $ =jQuery.noConflict();
$(document).ready(function(){
$(document).on( "change", '#QSelector',function(e) {
e.preventDefault();
var id = $(this).val();
$.ajax({
type: "POST",
url:"<?php echo './test_post.php'; ?>",
data: {id: id},
dataType: 'json',
success: function(data){
if(data.status == 'success'){
$('#OUtputDiv').html(data.result);
}
}
});
});
});
</script>

codeigniter dependant dropdown, there was a issue while using xmlhttp

I am using dependent drop down in my project. I have checked my code several time but still there was an error.
Data has loaded to 'Category' drop down. when Iam select item from 'Category' following message will be displayed. Not data loaded into 'Sub category'.
"There was a problem while using XMLHTTP"
please look at my code
<!-- /.Category -->
<div class="form-group">
<label>Product Category</label>
<select name="category_id" class="form-control col-sm-5" id="category" onchange="get_category(this.value)">
<option value="">Select Product Category</option>
<?php if (!empty($category)): ?>
<?php foreach ($category as $v_category) : ?>
<option value="<?php echo $v_category->category_id; ?>"
<?php
if (!empty($product_info)) {
echo $v_category->category_id == $product_category->category_id ? 'selected' : '';
}
?> >
<?php echo $v_category->category_name; ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div>
<!-- /.Sub Category -->
<div class="form-group">
<label>Subcategory<span class="required">*</span></label>
<select name="subcategory_id" class="form-control col-sm-5" id="subcategory">
<option value="">Product Subcategory</option>
<?php if (!empty($subcategory)): ?>
<?php foreach ($subcategory as $v_subcategogy) : ?>
<option value="<?php echo $v_subcategogy->subcategory_id; ?>"
<?php
if (!empty($product_info)) {
echo $v_subcategogy->subcategory_id == $product_info->subcategory_id ? 'selected' : '';
}
?> >
<?php echo $v_subcategogy->subcategory_name; ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div>
AJAX CODE (i think issue in the response (req.status == 200) part.)
//*********************************************
// Product Category to Subcategory
//*********************************************
function get_category(str) {
if (str == '') {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
} else {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
var link = getBaseURL();
var strURL = link + "admin/product/get_subcategory_by_category/" + str;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
//alert(result);
$("#subcategory").html("<option value=''>Select Subcategory</option>");
$("#subcategory").append(result);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
}
It will help you if you are looking for Dependent dropdown (library) using CodeIgniter.
Look over It: Dependent dropdown (library)

Two submit button - default submit not working because of other

I have two submit buttons in a php file take_test:-
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can display the user's username to them by reading it from the session array. Remember that because
// a username is user submitted content we must use htmlentities on it before displaying it to the user.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-AU">
<head>
<title>OSTA - Take Test</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<link href="css.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="editarea/edit_area/edit_area_full.js"></script>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1> OSTA - Take Test</h1>
</div><!-- end header -->
<div class="nav">
<ul>
<li>Hello <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF- 8'); ?></li>
<li>Assignments</li>
<li>Edit Account</li>
<li>Logout</li>
</ul>
</div><!-- end nav -->
<div class="content">
<?php
echo "<form id='code' action='take_test.php' method='post'>";
$con=mysqli_connect($host,$username,$password,$dbname);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['next']))
{
$aa = $_POST['source'];
//foreach($aa as $k) :
$query = "INSERT INTO student_test(status,user_name,aaid,qqid,answer,submit_time)
VALUES('1','{$_SESSION['user'] ['username']}','{$_POST['edit']}','{$_POST['qid']}','{$aa}',NOW())";
$rest5=mysqli_query($con,$query);
//endforeach;
//}
//if (!$rest)
//{
// die('Error: ' . mysqli_error($con));
//}
$qry="SELECT qid FROM questions where aid={$_POST['edit']}
ORDER BY qid DESC
LIMIT 1";
$restfinal=mysqli_query($con,$qry);
$rowfinal = mysqli_fetch_array($restfinal);
$qidfinal = $rowfinal['qid'];
if ($qidfinal==$_POST['qid'])
{
echo "Test Submitted Successfully.";
sleep( 3 );
header("Location: s_assignments.php");
echo "Test Submitted Successfully.";
}
}
if(isset($_POST['edit']))
{
$id2 = $_POST['edit'];
if(isset($_POST['next']))
{
$a=$_POST['a'];
if(!isset($a)){
$a=0;
}}
if(!isset($a)){
$a=0;
}
//$res=mysqli_query($con,"Select * from assignments where a_id='$id'");
$res1 = mysqli_query($con,"Select n_question from assignments where a_id='$id2'");
$row1 = mysqli_fetch_array($res1);
$n_q = $row1['n_question'];
$res8=mysqli_query($con,"Select * from questions where aid='$id2' LIMIT 1 OFFSET $a");
}
echo "<table border='0' cellspacing='1' cellpadding='1'>";
echo "<tr>
<th>Question</th>
</tr>";
while($rowt = mysqli_fetch_array($res8))
{
echo "<tr>";
echo "<td>" . $rowt['question'] . "</td>";
echo "</tr>";
echo "<td>"."<input type ='hidden' id='qid' name ='qid' value=".$rowt['qid']."></td>";
echo "<td>"."<input type ='hidden' id='aid' name ='edit' value=".$rowt['aid']."></td>";
//echo "<td>"."<input type ='hidden' id='id' name ='id' value=".$id."> </td>";
echo "<tr>";
echo "<tr>";
echo "<td>"."<hr>"."<td>";
echo "</tr>";
echo "<td>"."<label for='lang'>Select Language:</label>
<select name='lang' id='lang'>
<option value='7'>Ada (gnat-4.3.2)</option>
<option value='13'>Assembler (nasm-2.07)</option>
<option value='45'>Assembler (gcc-4.3.4)</option>
<option value='104'>AWK (gawk) (gawk-3.1.6)</option>
<option value='105'>AWK (mawk) (mawk-1.3.3)</option>
<option value='28'>Bash (bash 4.0.35)</option>
<option value='110'>bc (bc-1.06.95)</option>
<option value='12'>Brainf**k (bff-1.0.3.1)</option>
<option value='11'>C (gcc-4.3.4)</option>
<option value='27'>C# (mono-2.8)</option>
<option value='1' selected='selected'>C++ (gcc-4.3.4)</option>
<option value='44'>C++0x (gcc-4.5.1)</option>
<option value='34'>C99 strict (gcc-4.3.4)</option>
<option value='14'>CLIPS (clips 6.24)</option>
<option value='111'>Clojure (clojure 1.1.0)</option>
<option value='118'>COBOL (open-cobol-1.0)</option>
<option value='106'>COBOL 85 (tinycobol-0.65.9)</option>
<option value='32'>Common Lisp (clisp) (clisp 2.47)</option>
<option value='102'>D (dmd) (dmd-2.042)</option>
<option value='36'>Erlang (erl-5.7.3)</option>
<option value='124'>F# (fsharp-2.0.0)</option>
<option value='123'>Factor (factor-0.93)</option>
<option value='125'>Falcon (falcon-0.9.6.6)</option>
<option value='107'>Forth (gforth-0.7.0)</option>
<option value='5'>Fortran (gfortran-4.3.4)</option>
<option value='114'>Go (gc-2010-07-14)</option>
<option value='121'>Groovy (groovy-1.7)</option>
<option value='21'>Haskell (ghc-6.8.2)</option>
<option value='16'>Icon (iconc 9.4.3)</option>
<option value='9'>Intercal (c-intercal 28.0-r1)</option>
<option value='10'>Java (sun-jdk-1.6.0.17)</option>
<option value='35'>JavaScript (rhino) (rhino-1.6.5)</option>
<option value='112'>JavaScript (spidermonkey) (spidermonkey-1.7)</option>
<option value='26'>Lua (luac 5.1.4)</option>
<option value='30'>Nemerle (ncc 0.9.3)</option>
<option value='25'>Nice (nicec 0.9.6)</option>
<option value='122'>Nimrod (nimrod-0.8.8)</option>
<option value='43'>Objective-C (gcc-4.5.1)</option>
<option value='8'>Ocaml (ocamlopt 3.10.2)</option>
<option value='119'>Oz (mozart-1.4.0)</option>
<option value='22'>Pascal (fpc) (fpc 2.2.0)</option>
<option value='2'>Pascal (gpc) (gpc 20070904)</option>
<option value='3'>Perl (perl 5.12.1)</option>
<option value='54'>Perl 6 (rakudo-2010.08)</option>
<option value='29'>PHP (php 5.2.11)</option>
<option value='19'>Pike (pike 7.6.86)</option>
<option value='108'>Prolog (gnu) (gprolog-1.3.1)</option>
<option value='15'>Prolog (swi) (swipl 5.6.64)</option>
<option value='4'>Python (python 2.6.4)</option>
<option value='116'>Python 3 (python-3.1.2)</option>
<option value='117'>R (R-2.11.1)</option>
<option value='17'>Ruby (ruby-1.9.2)</option>
<option value='39'>Scala (scala-2.8.0.final)</option>
<option value='33'>Scheme (guile) (guile 1.8.5)</option>
<option value='23'>Smalltalk (gst 3.1)</option>
<option value='40'>SQL (sqlite3-3.7.3)</option>
<option value='38'>Tcl (tclsh 8.5.7)</option>
<option value='62'>Text (text 6.10)</option>
<option value='115'>Unlambda (unlambda-2.0.0)</option>
<option value='101'>Visual Basic .NET (mono-2.4.2.3)</option>
<option value='6'>Whitespace (wspace 0.3)</option>
</select>". "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"."<label for='source'>Source Code:</label>"."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"."<textarea cols='80' rows='12' name='source' id ='source'> </textarea>"."</td>";
echo "</tr>";
}
echo "<tr>";//echo "<br />";
echo "<td>"."<label for='input'>Input: <span class='description'>(Data that will be given to the program on the stdin.)</span></label>";
//echo "<br />";
echo "</tr>";
echo "<tr>";
echo "<td>"."<textarea cols='40' rows='3' name='input' id='input'></textarea>". " </td>";
echo "</tr>";
$a=$a+1;
echo "<input type='hidden' value='$a' name='a'>";
// echo "<td>"."<a href='take_test.php'> "
//echo "<td>"."<input type ='submit' name ='compile' value='Compile Code'>"."</td>";
echo "<td>"."<input type='submit' name='compile' id='compile' value='Compile Code'>"."</td>";
echo "<td>"."<input type ='submit' name ='next' value='Next Question'>"."</td>";
echo "</table>";
echo"</form>";
?>
<div id="response">
<div class="meta"></div>
<div class="output"></div>
</div>
</div><!-- end content -->
<div class="footer">
<p>designed by | © </p>
</div><!-- end footer -->
</div><!-- end wrapper -->
<script language="javascript" type="text/javascript">
editAreaLoader.init({
id : "source" // textarea id
,syntax: "css" // syntax to be uses for highgliting
,start_highlight: true // to display with highlight mode on start-up
});
</script>
<script type="text/javascript" src="jquery.min.js"></script>
<script src="script.js"></script>
<!-- <script src="../jquery/jquery-1.4.1.min.js"></script> -->
</body>
</html>
One submit name=next i am detecting through
if(isset($_POST['next']))
and the other through
Here is the code for script.js
jQuery(document).ready(function($) {
//$('input[name=compile]').on('click',function(){
// $(this).closest("#code")[0].submit();})
//$('#compile').on('click', function() {
$('#code').submit( function(){
var data = $(this).serialize();
var source = $('textarea#source').val();
if( source == '' ) {
alert( 'No source code provided');
return false;
}
$(this).append('<div class="loading">Processing...</div>');
$.ajax({
type: 'post',
url: 'process.php',
dataType: 'json',
data: data + '&process=1',
cache: false,
success: function(response){
$('.loading').remove();
$('.cmpinfo').remove();
$('#response').show();
//alert(response);
console.log(response.raw);
if( response.status == 'success' ) {
$('.meta').text( response.meta );
$('.output').html('<strong>Output</strong>: <br><br><pre>' + response.output + '</pre>');
if( response.cmpinfo ) {
$('.cmpinfo').remove();
$('.meta').after('<div class="cmpinfo"></div>');
$('.cmpinfo').html('<strong>Compiler Info: </strong> <br><br>' + response.cmpinfo );
}
} else {
//$('.output').html('<pre>' + response + '</pre>');
alert( response.output );
}
//alert( response.msg );
}
});
return false;
});
});
The problem is whenever I click on either compile button or next button it considers compile button only. If i remove script file the next button runs perfectly.
Please give any suggestion.
I have tried a lot of solutions but nothing is working.
The $('#code').submit function in the JS file seems to be the problem. Since both buttons in your PHP are submit buttons, clicking on either of those two buttons will trigger the form submit action and it in-turn is triggering the AJAX request for process.php.
If the script file is commented out, then the default action page mentioned in your form tag is called and that is the reason why your next button works when the script is commented out.
You should add a control within the JS file to check which of those submit buttons was actually clicked by the user and then do the appropriate action. The below is a very basic sample for your reference:
HTML
<form id="code" action="aa.php" method="post">
<input type="submit" class="button" name="compile" value="compile"/>
<input type="submit" class="button" name="next" value="next"/>
</form>
JS (to be executed on DOM ready)
var buttonpressed;
$('.button').click(function() {
buttonpressed = $(this).attr('name');
}); //This will set the name of the button that was clicked to the buttonpressed variable whenever a button is clicked
$('#code').submit(function() {
//The below lines check for the button's name upon form submit and then process accordingly
if(buttonpressed=="next") alert("Add code to next");
else alert("Add code to compile");
buttonpressed='';
return false;
});

Categories

Resources