JQuery Page Refreshes - php

I working on a page with some JQuery and Kendo UI. This is my first JQuery project and I getting things along. However, my page refreshes for some reason. This is what I am trying to do: I have a text field where I can enter a search term and when I press a button, the query is sent to a php file and some json info will pop up. So far, I can get it to return something, but the page refreshs and all the data is gone.
code:
*<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<link href="styles/kendo.common.min.css" rel="stylesheet" />
<link href="styles/kendo.default.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<script src="js/kendo.web.min.js"></script>
</head>
<body>
<div id="example">
<form id="search">
<label for="search">Search For:</label>
<input type="text" id="txtSearch" name="q">
<button type="submit" id="submit">Find</button>
</form>
<div id="grid">
</div>
</div>
<script>
$(function() {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "include/showsearch.php"
},
schema: {
data: "data"
}
},
columns: [{field: "id"},{field: "name"},{field: "season"}]
});
$("#submit").click(function(){
var textVal = $("#txtSearch").val();
var dynamicURL = "include/showsearch.php?show_name=" + textVal;
var grid = $("#grid").data("kendoGrid");
alert("sdf123");
grid.dataSource.transport.options.read.url = dynamicURL;
grid.dataSource.read();
alert("sdf");
});
});
</script>
</body>
</html>*
NOTE:
I used the alert functions to stop and see how the page reacts. How do I get the page from refreshing?

The reason this is happening is that the default action for your submit button is still occurring; submitting the form.
It's probably best to catch the form submission event rather than the button click as hitting Enter in a text field may also submit the form.
You will also need to prevent the default event action.
Change this
$("#submit").click(function(){
to this
$('#search').on('submit', function(e) {
e.preventDefault();
// and the rest of your code here

Related

Submiting a form with jquery/AJAX isn't working when clicking the submit button

I am trying to submit a form with jquery/AJAX but my function is never called when I am clicking on the submit button.
My website looks like that:
CarMenu.php
<html lang="en">
<html>
<head>
<meta charset="ISO-8859-1">
<title>ArsenalAutoBrokers - Backend - add car</title>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.min.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.theme.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.structure.css" type="text/css"/>
<link rel="stylesheet" href="../css/carForm.css" type="text/css"/>
<script charset="UTF8" src="../js/jquery/jquery-1.11.3.js"></script>
<script charset="UTF8" src="../js/jquery-ui- 1.11.4/external/jquery/jquery.js"></script>
<script charset="UTF8" src="../js/jquery-ui-1.11.4/jquery-ui.js"></script>
<script charset="UTF8" src="../js/app/carForm.js"></script>
<script charset="UTF8" src="../js/app/addCar.js"></script>
</head>
<body>
<div id="container">
<div id="leftMenuContainer">
<ul id="menu">
<li id="addCarItem">Add car</li>
<li id="saveCarItem">Edit cars</li>
</ul>
</div>
<div id="rightMainContent">
</div>
<div class="clear"></div>
</div>
</body>
</html>
On that page, I am using jquery menu and I am loading the data into the div with the id 'rightMainContent'.
The javascript code to do this looks like: carForm.js
$(document).ready(function () {
$( "#menu" ).menu({
select: function(event, ui) {
if (ui.item.attr('id') === 'addCarItem') {
$("#rightMainContent").load(
'/CarDealer/CarForm/CreateCar/AddCar.php');
}
}
});
});
If you are clicking on the 'addCar' menu item parts of the site will load from this php site:
<script type="text/javascript">
$('input[type=submit]').button();
//$('#activeCheck').button();
$("#activeCheck").attr('checked','checked');
$('#saveButton').hide();
$('#tabs').tabs();
$('#accordion' ).accordion({heightStyle: "content"});
$('#tabs').tabs({
activate: function (event, ui) {
var act = $("#tabs").tabs("option", "active");
if (act == 0 || act == 1) {
$('#saveButton').hide();
} else {
$('#saveButton').show();
}
}
});
$('#fileToUpload').on('change', function(){
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
if (files.length > 10) {
$('.info').html('The file upload is limited to <font color="red"><b>10 pictures per car</b></font>.<br>Only the 1st ten pictures will be stored.');
$('.info').show();
} else {
$('.info').html('');
$('.info').hide();
}
});
</script>
<form id="carSaveForm"
action="/CarDealer/CarForm/CreateCar/CarCreation.php" method="POST"
enctype="multipart/form-data">
<div id="tabs">
<ul>
<li>General Car Information</li>
<li>Car Descriptions</li>
<li>Picture Upload</li>
</ul>
<div id="tabsGen">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carGeneralData.php"); ?>
</div>
<div id="tabsDescr">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carDescriptions.php"); ?>
</div>
<div id="tabsPics">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/PictureUpload.php"); ?>
</div>
</div>
<br> <input id="saveButton" type="submit" name="submit" value="save" />
</form>
This site is containg only form elements like input buttons, file pickers, etc.
Well, so far so good. Everything is displaying properly but if I am clicking the submit button this function isn't getting called: addCar.js
$('#carSaveForm').on('submit', function(event){
event.preventDefault();
var formData = new FormData();
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
formData.append('carBrand' , $('input[name=carBrand]').val());
formData.append('carModelYear' , $('input[name="carModelYear"]').val());
formData.append('carModel' , $('input[name=carModel]').val());
formData.append('carTrim' , $('input[name="carTrim"]').val());
formData.append('carDriveTrain' , $('input[name="carDriveTrain"]').val());
formData.append('carCondition' , $('input[name="carCondition"]').val());
formData.append('carType' , $('input[name="carType"]').val());
formData.append('carFuelType' , $('input[name="carFuelType"]').val());
formData.append('carTransmission' , $('input[name="carTransmission"]').val());
formData.append('carEngine' , $('input[name="carEngine"]').val());
formData.append('carCylinder' , $('input[name="carCylinder"]').val());
formData.append('carMileage' , $('input[name="carMileage"]').val());
formData.append('carExteriorColor' , $('input[name="carExteriorColor"]').val());
formData.append('carInteriorColor' , $('input[name="carInteriorColor"]').val());
formData.append('carLocation' , $('input[name="carLocation"]').val());
formData.append('carVin' , $('input[name="carVin"]').val());
formData.append('carStock' , $('input[name="carStock"]').val());
formData.append('carPrice' , $('input[name="carPrice"]').val());
formData.append('carPriceDetails' , $('input[name="carPriceDetails"]').val());
formData.append('carTax' , $('input[name="carTax"]').val());
formData.append('carTaxDetails' , $('input[name="carTaxDetails"]').val());
formData.append('carCurrency' , $('input[name="carCurrency"]').val());
formData.append('carOnline' , $('input[name="carOnline"]').val());
formData.append('carDescr' , $('input[name="carDescr"]').val());
formData.append('carBodyDescr' , $('input[name="carBodyDescr"]').val());
formData.append('carDriveTrainDescr' , $('input[name="carDriveTrainDescr"]').val());
formData.append('carExteriorDescr' , $('input[name="carExteriorDescr"]').val());
formData.append('carElectronicsDescr' , $('input[name="carElectronicsDescr"]').val());
formData.append('carSaftyFeaturesDescr' , $('input[name="carSaftyFeaturesDescr"]').val());
formData.append('carSpecialFeaturesDescr', $('input[name="carSpecialFeaturesDescr"]').val());
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
formData.append('files[]', file, file.name);
}
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '/CarDealer/CarForm/createCar/carCreation.php', // the url where we want to POST
data : formData, // our data object
contentType: false,
processData: false,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
},
error: function (data) {
$('.success').fadeIn(200).hide();
$('.error').fadeOut(200).show();
}
});
return false;
});
I have no clue why this function is never getting called, I have tried everything, I have googled a lot but I am not getting it. I am searching for the error the whole day but I can't see it.
Please help me.
Your help is apreciated.
Thanks in advance.
jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.
For instance, this button has been added to the DOM via AJAX:
<input id="saveButton" type="submit" name="submit" value="save" />
In order to properly handle this (if it is the only form with this id added to the page) is to delegate the click or submit event:
$(document).on('click', '#saveButton', function(event) {...
In addition, if you continue to add forms as you show here, you will have duplicate id's in your page and id's must be unique. Failure to make them unique will result in a number of problems.
Make sure to watch the AJAX request / response in the browser's console as outlined here to find and correct errors that you may be having.
change $('#carSaveForm').on('submit', function(event) to $('#carSaveForm').on('click','#saveButton', function(event)
Cut (ctrl+x) this line from CarMenu.php
<script charset="UTF8" src="../js/app/addCar.js"></script>
And paste (ctrl+v) the script in AddCar.php

Ajax call not saving form information

I have tried using the code below to save and display information using ajax. But it doesn't work.
Here's the code.
<?php session_start();?>
<html>
<head>
<script src="style/jquery-ui.js" type="text/javascript" charset="utf-8"></script>
<script src="style/jquery-1.11.1.min.js"></script>
<script>
$(function() {
$("#ajaxquery").live( "submit" , function(){
// Intercept the form submission
var formdata = $(this).serialize(); // Serialize all form data
// Post data to your PHP processing script
$.post( "show.php", formdata, function( data ) {
// Act upon the data returned, setting it to #success <div>
$("#success").html ( data );
});
return false; // Prevent the form from actually submitting
})
});
</script>
</head>
<form id="ajaxquery" method="post" action="">
<label for="field">Type Something:</label>
<input type="text" name="field" id="field" value="" />
<input type="submit" value="Send to AJAX" />
</form>
<div id="success"> </div>
</html>
AND MY show.php which displays data in id="success"
<?php
// Process form data
echo '<strong>You submitted to me:</strong><br/>';
print_r( $_REQUEST );
?>
Please help...
at first you have to load jquery ui after jquery
<script src="style/jquery-1.11.1.min.js"></script>
<script src="style/jquery-ui.js" type="text/javascript" charset="utf-8"></script>
then in this case you don't need to use live you can simply do this
$("#ajaxquery").submit(function(){
// your code
})
"live" function ( or for now "on" ) used when you going to create or load html code after you set events.

How to get Text Typed on CkEditor

I´m trying to get typed text on ckeditor (textarea), but I have some trouble:
Here is my code:
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#editor').ckeditor();
var editor = $('#editor').ckeditorGet();
var data = $('#editor').val();
window.alert(data);
window.alert(CKEDITOR.instances['editor'].getData());
});
</script>
<body>
<form method="post">
<textarea name="editor" id="editor"></textarea>
<input type="submit" value="Submit">
</form>
The results on two alerts are empty. What i´m doing wrong?
That's because you are calling the alerts when the page loads. At that time, there is nothing yet on the textarea.
Bind the event to something that will happen after the textbox has something to show, for example, when you click the submit button:
$(document).ready(function(){
$('#editor').ckeditor();
$('input[type=submit]').on('click', function() {
window.alert($('#editor').val());
});
});
Also, you may want to bind the click event to the document instead, so it will happen even if you add new submits programatically. For that to happen, bind the event like this:
$(document).on('click', 'input[type=submit]', function() {
window.alert($('#editor').val());
});

jquery is resetting my div content

I'm trying to change the content of div using jquery. but the content flashes and resets the div. i cannot use return false; because there is another button for post text field value. i want to keep the changes of div. here is my code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div>
<form id="form" method="POST">
<input type="text" name="gname" id="gname"/></br>
<button id="btn">Set</button>
<button id="nbtn">View</button>
</form>
</div>
<div id="outp">
</div>
</body>
<script>
$("#btn").click(function(event) {
$.post("send.php", {
named: $("#gname").val()}, function(data) {
alert(data);
});
});
</script>
<script>
$("#nbtn").click(function(e) {
$("#outp").html("<?php include './view.php'; ?>");
});
</script>
It's not jQuery; it's that your form is being posted. So your change is made, but then the form is posted and the page is refreshed from the server.
The default type of button elements is "submit". To make one or both of those buttons just a button, use type="button".
Alternately, if you want to allow the form to be used when JavaScript is disabled (e.g., allow it to be posted normally), leave the buttons as submit buttons but prevent form submission using JavaScript. E.g.:
$("#form").submit(false); // Prevents the form being submitted in the normal way.
Any buttons inside a form are considered submit buttons.
So you need to add event.preventDefault() to your .click code.
Also, why are your scripts outside body section?
You can try with ajax and catch success and error:
$("#btn").click(function() {
var named: $("#gname").val();
$.ajax({
url: 'send.php',
type: 'POST',
data: {param1: 'value1'},
})
.done(function(data) {
console.log("Post success"+data);
})
.fail(function() {
console.log("Post error"+data);
});
});

Jquery Confirmation Does Not Appear

I want to begin by saying I am extremely new to Jquery / client side scripting. I was kinda blind sided when my bosses wanted some way for customers to acknowledge form submission.
This is my jquery / header :
<head>
<title>Access Point</title>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
<link rel="stylesheet" href="<?php echo base_url();?>css/mainstyle.css" type="text/css" />
<link rel="stylesheet" href="<?php echo base_url();?>css/secondarystyles.css" type="text/css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$("#signinform").submit( function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait."))
{
e.preventDefault();
return;
}
});
</script>
</head>
And this is my form :
<?php echo form_open('staff_controller/agree', 'id="signinform"') ?>
<input type="checkbox" id="agree" name="options" value="agree"<?php echo form_checkbox('options','agree') ?>I have read and understood the above <br /> <font color="#ff0000" size="3">(Please click on the box)</font></input>
<br />
<br />
<br />
<?php
echo form_submit('submit', 'Submit');
echo anchor('staff_controller/studentlogin', 'Cancel');
echo form_close();
?>
My php script checks if the checkbox is checked (to agree to our requirements) and also checks if submit is clicked. If it is clicked then submit the values into a database. To my understand I can continue to use this style to handle my data I just want jquery in the middle to allow users to know they are submitting. I found this code out in the internet and I have no idea how to debug this. I also do plan to a jquery confirm to check if you want to "Cancel" form submission
Edit 1 :
looking at source code it "should" work :
form
action="https://www.finaidtest.com/index.php/staff_controller/agree"
id="signinform" method="post" accept-charset="utf-8"
and then my updated confirmation :
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
<script>
$(document).on('submit', "#signinform", function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait"))
{
e.preventDefault();
return;
}
});
</script>
Edit 2
Thanks to Musa it all works fine now! Thanks!!
Code :
<script src="<?php echo base_url();?>javascript/js/jquery.js" type="text/javascript"></script>
<script>
$(document).on('submit', "#signinform", function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait"))
{
e.preventDefault();
return;
}
});
</script>
You have to wait for the element to be created before you can bind an event handler to it. Use $(document).ready to ensure your element is created before you set the handler.
$(document).ready(function(){
$("#signinform").submit( function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait."))
{
e.preventDefault();
return;
}
});
});
You could also use delegation to attach the event so you don't have to wait for the dom to be loaded
$(document).on('submit', "#signinform", function(e){
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait."))
{
e.preventDefault();
return;
}
});

Categories