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>
Related
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.
I have a form that is posting data to a php api file. I got the api working and it creates an account but want to use AJAX to send the data so I can make the UX better. Here is what the PHP sending script is expecting:
<form id="modal-signup" action="/crowdhub_api_v2/api_user_create.php" method="post">
<div class="modal-half">
<input type="text" placeholder="First Name" name="user_firstname"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Last Name" name="user_lastname"></input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="male" name="user_gender">Male</input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="female" name="user_gender">Female</input>
</div>
<div class="modal-half">
<input type="date" placeholder="DOB" name="user_dateofbirth"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Zip Code" name="user_zip"></input>
</div>
<input class="end" type="email" placeholder="Email" name="user_email"></input>
<input type="password" placeholder="Password" name="user_password"></input>
<input type="submit"></input>
</form>
PHP
$user_firstname = $_REQUEST['user_firstname'];
$user_lastname = $_REQUEST['user_lastname'];
$user_email = $_REQUEST['user_email'];
$user_password = $_REQUEST['user_password'];
$user_zip = $_REQUEST['user_zip'];
$user_dateofbirth = $_REQUEST['user_dateofbirth'];
$user_gender = $_REQUEST['user_gender'];
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
How would I send this via ajax? I found this script that says it worked, but it did not create a user. I imagine its sending the data not the right way.
Ajax
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/api_v2/api_user_create.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
First, let's get ajax in order:
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
//same url as the form
url: '/crowdhub_api_v2/api_user_create.php',
data: $('form').serialize(),
//we need a variable here to see what happened with PHP
success: function (msg) {
//output to the page
$('#output').html(msg);
//or to the console
//console.log('return from ajax: ', msg);
}
});
});
});
Somewhere on the form page, add a div with id output:
<div id="output></div>
Finally, in api_user_create.php, there is an error:
$user_gender = $_REQUEST['user_gender'];
//these last two do not exist on the form
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
I'd recommend some error-checking on the PHP side, like this
if(!empty($_REQUEST)){
//For developing, you may want to just print the incoming data to see what came through
//This data returns into the msg variable of the ajax function
print_r($_POST);
//once that's good, process data
if(isset($_REQUEST['user_gender'])){
$user_gender = $_REQUEST['user_gender'];
}
//etc... as before
} else {
echo 'no data received';
}
Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});
I'm trying to post some form data and return results but I am having trouble getting this to work:
The javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#sendthis").click(function () {
$.ajax({
type: "POST",
data: $('#theform').serialize(),
cache: false,
url: "form.php",
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
The HTML:
<form id="theform">
<input type="text" class="sized" name="name" id="name"><br />
<input type="text" class="sized" name="email" id="email">
</form>
Submit
The page to post to (form.php):
<?php
if (isset($_POST['name'])){
$result = $_POST['name'];
}
echo $result;
?>
Now, it is my understanding that when the form is submitted, it would post to form.php, and the input value of "name" would be returned in an alert box. However, I can't seem to get the form data posting (or maybe returning) correctly.
Is it a problem with $('#theform').serialize()? Maybe something else?
Any help is much appreciated.
Try this and see if it works
<form id="theform" action="/form.php">
<input type="text" class="sized" name="name" id="name"/><br />
<input type="text" class="sized" name="email" id="email" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
The jquery
$("#theform").on('submit', function () {
$.post($(this).attr('action'), $(this).serialize(), function(data) {
alert(data);
});
return false;
});
I would add an error callback to your ajax request to catch if there are issues being encountered during the post. Do you have a debugger like firebug that can show you what data is being posted (and where)?
I have got this html/php in my index.php
if (isset($_POST['UploadMSub'])) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)) {
if ($fileP_error===0) {
if ($fileP_size<=2097152) {
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
$_SESSION['fileP']=$fileP;
$_SESSION['fileP_name']=$fileP_name;
$_SESSION['fileP_tmp']=$fileP_tmp;
$_SESSION['fileP_size']=$fileP_size;
$_SESSION['fileP_error']=$fileP_error;
$_SESSION['fileP_extension']=$fileP_extension;
$_SESSION['fileP_new_name']=$fileP_new_name;
}
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
And this ajax
$(".UploadMSub").click(function() {
var text=$(".Text").val();
var file=$("#Nameupload").val();
$.ajax({
type: "GET",
url: '../connect.php',
data: "Text=" + text+"&&file="+file,
success: function(data)
{
alert(data);
}
});
return false;
});
connect.php
if (isset($_GET['Text'])) {
$Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
$file=htmlspecialchars($_GET['file'],ENT_QUOTES);
echo $Text." ".$_SESSION['fileP_new_name'];
}
But when i submit form it returns(alerts)
"Undefine index ''fileP_new_name'"
Is there any other way of getting all information about file in my connect.php?
The problem is,
When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,
Undefine index: fileP_new_name
From your question,
Is there any other way of getting all information about file in my connect.php?
So the solution is as follows. You have to change few things in your code, such as:
Add a name attribute in your <textarea> element, like this:
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:
$(".UploadMSub").click(function(event){
event.preventDefault();
// your code
});
If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.
So your code should be like this:
HTML:
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
jQuery/AJAX:
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('form')[0]);
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data){
alert(data);
}
});
});
And on connect.php, process your form data like this:
<?php
if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
// both file and text input is submitted
$new_post = $_POST['new_post'];
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
// your code
//echo $fileP_new_name;
}
?>