here is my first view
<form id="bussearch">
<input class="form-control" id="value1" name="start" type="text" />
<input class="form-control" id="value2" name="value2" type="text" />
<input class="form-control" id="value2" name="value3" type="text" />
<button class="btn" type="submit">Search for Bus</button>
</form>
here is the script
$("#bussearch").submit(function(e) {
$.ajax({
type: "POST",
url: "http://siteurl/controller/test",
data: $("#bussearch").serialize(),
success: function(data)
{
$("#div_result").html(data);
//alert(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
Here is my controller
function test()
{
$response = $this->load->view('welcome_message',TRUE);
echo $response;
}
here is the view welcome_message
<div id="div_result"></div>
I need to load a view after ajax sucess function, but view welcome_message is not loading
I do something similar to this to load data into modals.
In my controller I just call for the view:
public function update_user_modal()
{
$this->load->view('modals/update_user_modal');
}
The ajax is like this:
$.ajax({
url: "<?php echo base_url('admin/get_user_details'); ?>",
type: "POST",
data: { id: id }
}).done(function(msg) {
console.log(msg); // this will have the content of the view
}.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus + " - Please try again.")
})
I presume it is a typo in the ajax url you have provided as you are calling function test() within the controller but you are providing the function bus_test() in your controller.
Hope this helps.
Related
I'm wondering if there is a simple and safe way to insert values from an input field into a wordpress database without form tags. As I have it, I used the following:
<input id="amountSlider" type="range" min="100000" value="200000" max="1000000" required="required" step="1000" />
<input type="text" id="emailText"/>
<button id="inputSubmit" onClick="checkSubmit()">Submit</button>
and
function checkSubmit() {
var userInfo = {
'Amount': document.getElementById('amountSlider').value,
'emailOf': document.getElementById('emailText').value
};
jQuery.ajax({
url: "wp-admin/submitInfo.php",
type: "POST",
data: userInfo,
success: function (html) {
if (html==1) {
alert('ok.');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
}
Is it possible without a form tag?
form tag meaning:
<form>
Yes. Its possible.
<input id="amountSlider" type="range" min="100000" value="200000" max="1000000" required="required" step="1000" />
<input type="text" id="emailText"/>
<button id="inputSubmit">Submit</button>
jQuery('#inputSubmit').on('click', function () {
var userInfo = {
amount: jQuery('#amountSlider').val(),
emailOf: jQuery('#emailText').val()
};
jQuery.ajax({
url: "wp-admin/submitInfo.php",
type: "POST",
data: userInfo,
success: function (html) {
if (html == 1) {
alert('ok.');
} else {
alert('Sorry, unexpected error. Please try again later.');
}
}
});
});
But place your file in wp-admin/ catalog - is bad idea. Use wp_ajax_{action} hooks for this.
I have a form with
<form id=myform onsubmit=return validate();>
<input type=text id=name name=name>
</form>
In my javascript file I have
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (data.exists){
return false;
}
}
});
return true;
}
This Ajax code check if the returned data has value especially the data.exists. I would like to prevent submit form based on the value of exists.
This
if (data.exists){
return false;
}
does not really work.
Your problem occurs because of async ajax function call, it returns true before ajax data returns.
I haven't checked it, But you can try something like this:
function validate(){
var self = this;
self.preventDefault();
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
self.submit();
}
}
});
return false;
}
$('#myform').submit(function() {
return false;
});
This should do the trick, now the form won't reload the page on pressing enter or a button.
EDIT:
Your form is also missing double-quotes
<form id="myform" onsubmit="return validate();">
<input type="text" id="name" name="name">
</form>
Solution:
I have changed my HTML and I have added onclick event than onsubmit
<form id="myform">
<input type="text" id="name" name="name">
<button type="submit" id="button" onclick="validate();">
</form>
Also in Javascript
I prevent the submit here
$("#button").on("click",function(event){
event.preventDefault();
});
Here is my function to check if not exists data so then submit form
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
$('#myform').submit();
}
}
});
I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});
I'm using a form within a fancybox window post (Ajax) data to a php page.
If I run the form outside of the Fancybox it works perfectly. Insert - Check. Response - Check. That said, if I run the same page through the Fancybox I get a loading wheel (which persists after I close the overlay).
Form (form_test.php):
<form id="form" method="post" action="">
<input type="text" id="name" name="name" value="Test Name" />
<input type="text" id="email" name="email" value="email#test.com" />
<input type="submit" value="Login" />
</form>
<script type"text/javascript">
$("#form").bind("submit", function () {
$.fancybox.showLoading(); // it was $.fancybox.showActivity(); for v1.3.4
$.ajax({
type: "POST",
cache: false,
url: "test.php", // make sure your path is correct
data: $(this).serializeArray(), // your were using $(form).serialize(),
success: function (data) {
$.fancybox(data);
}
});
return false;
}); // bind
</script>
PHP (test.php):
$name=$_POST['name'];
$email=$_POST['email'];
$query=mysql_query("INSERT INTO members (firstName,email) VALUES('$name','$email')");
if($query){
echo "Data for $name inserted successfully!";
}
else{
echo "An error occurred!";
}
Ideas?
Try
$("#form").bind("submit", function () {
$.fancybox.showLoading(); // it was $.fancybox.showActivity(); for v1.3.4
$.ajax({
type: "POST",
cache: false,
url: "test.php", // make sure your path is correct
data: $(this).serializeArray(), // your were using $(form).serialize(),
success: function (data) {
$.fancybox(data);
}
});
return false;
}); // bind
Now, $.fancybox(data); will return (inside fancybox) whatever you sent from the text.php file so you could return the <div id="message"> from within that file like :
if($query){
echo "<div id='message'>Data for $name inserted successfully!</div>";
} else {
echo "<div id='message'>An error occurred!</div>";
}
I've been trying to figure this out, but it seems to be harder than i first thought. However, what I'm trying to do is make an ajax post request, but the POST seems to be empty when I'm sending it.
My HTML File
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm', 'name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
My Javascript
$('#statusUpdateForm').submit(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
My PHP (Some of my medhod in the controller)
// Check if the input is a ajax request
if($this->input->is_ajax_request()) {
echo $_POST['profileUpdate'];
}
Notice, when i put echo "Hello World" etc in the controller, i do get "Hello World" in the alert box from the javascript.
I've also tried a var_dump on $_POST and it returns array(0){} When I'm trying to output the specific $_POST['profileUpdate'] variable i get an error like this,
I've also done a alert from the seralize function i JS, this is what i got,
Is there anyone who know how i can fix this problem?
Try changing method to type.
I'm guessing the script is performing a GET request, which is the default setting when using ajax(), instead of a POST request. Like this:
$.ajax({ // Starter Ajax Call
// "method" isn't an option of $.ajax
// method: "POST",
type: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
Try The following Code
In View add the following form
<?php echo form_open('welcome/CreateStudentsAjax'); ?>
<label for="roll">Student Roll Number</label>
<input type="text" id="txtRoll" value="" name="roll"/>
<label for="Name">Students Name</label>
<input type="text" id="txtName" value="" name="name"/>
<label for="Phone">Phone Number</label>
<input type="text" id="txtPhone" value="" name="phone"/>
<input type="submit" name="submit" value="Insert New Students" />
<?php echo '</form>'; ?>
The JQuery Part is below
$(document).ready(function(){
$('form').submit(function(){
//alert('ok');
$.ajax({
url:this.action,
**type:this.method,**
data:$(this).serialize(),
success:function(data){
var obj = $.parseJSON(data);
if(obj['roll']!=null)
{
$('#message').text("");
$('#message').html(obj['roll']);
$('#message').append(obj['name']);
$('#message').append(obj['phone']);
}
else
{
$('#message').text("");
$('#message').html(obj);
}
},
erro:function(){
alert("Please Try Again");
}
});
return false;
});
});
</script>