Send Form Data to Controller (Codeigniter) - javascript

I have a pop up menu and inside that I have a form and a text box. I want to retrieve that value and submit it to my controller. Once submitted I want my pop up to close and go back to the other page. I tried with AJAX but I might be doing something wrong.
<form onsubmit="return(testing());" method="POST">
<input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
<input type="submit" name="Redeem" value="Redeem">
</form>
Now My Javascript
function testing() {
$test = document.getElementById("vip").value;
var url = base_url + '/index.php/home/redeeming_form_value';
$.ajax({
type : 'POST',
url : url,
data : {'myvalue':test},
success: function(data){
alert(data);
}
});
};
In my controller
function redeeming_form_value() {
$amount = $this->input->post('myvalue');
return $amount;
In the AJAQ I have a success, and want to alert my data(the value) to make sure it even works but it does nothing. When i click submit my pop up view just goes away.

Try adding dataType: "json", to your Ajax
dataType: "json",
Then in your controller use json_encode to return your data
$arr = array('amount' => $amount);
return json_encode($arr);
Test the response in success
console.log(data.amount);

Try it..
HTML
<form action="" method="POST">
<input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
<input type="submit" name="Redeem" id="submit" value="Redeem">
</form>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var test = $("#vip").val();
var base_url= 'http://localhost/shop';
var url = base_url + '/index.php/home/redeeming_form_value';
$.ajax({
type : 'POST',
dataType: 'json',
url : url,
data :'myvalue='+test,
success: function(data){
msg= eval(data);
amount= msg.amount;
alert(amount);
}
});
});
});
</script>
At your Controller
function redeeming_form_value()
{
$amount = $this->input->post('myvalue');
echo json_encode(array('amount'=>$amount));
}

Related

how to clear form after submit the form and pass the data to php file without reloading page

how to clear form after submit the form and pass the data to php file without reloading page...the form data is pass the php file and it stored the data base.but i was unable to clear the form data after submit the form.if i reset the form using javascrip but data not pass the data base.if i pass the data to php the form is not clear.is there a way for me achive both target?thank you..
here my snipt code...
<iframe name="votar" style="display:none;"></iframe>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
Using AJAX you can do this.
$('#submitBtn').click(function () {
$.ajax({
url: 'confirm.php',
data: $('#sfm').serialize(),
type: "post",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
you can try this
in index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'ajax.php',
data: $('form').serialize(),
success: function (data) {
$('#name').val('');
alert('data');
//your return value in data
}
});
});
});
</script>
</head>
<body>
<form action="ajax.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" id="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
</body>
</html>
and in ajax.php
<?php
$name = $_GET['name'];
//do what you want to do using name
echo "what you need to return";
Have you thought about to use Ajax to handle the form submit?
Form submit with AJAX passing form data to PHP without page refresh
try making $_POST array empty after submitting and saving the form
$_POST='';
After getting success response you can clear form input
$('#sfm').submit(function () {
var form = $(this);
$.ajax({
url: 'phpfile.php',
data: form.serialize(),
type: "POST",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
You can do like this, first get form inputs value and then reset
You can also able to reset after success response
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var that = $(this);
var params = that.serialize();
that.get(0).reset();
console.log(params);
$.ajax({
type: 'GET',
url: 'submit.php',
data: params,
success: function (data) {
console.log(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
SERVER SIDE
<?php
$name = $_GET['name'];
echo 'success';
exit();
?>

How to display specific record after clicked on anchor tag using php?

I have two links, Delete and View. Delete is working perfectly. I am getting the issue on view link. I have to display specific records after clicked on view link.If you notice that delete anchor tag I wrote href='delete.php?function=delete&del_id=$id'. It's calling the delete.php file and deleting a specific record. I want to know about how to write in view anchor tag to display records? Please check below image.I want to clicked on view and display the records in text fields.PHP file added. Please check my ajax code. It is also not working. Ajax code is not working here. I have to display the output in the text field.If i write directly $id=2 then it is display records in alert. Hope you guys can understand now.Would you help me in this?
//delete.php
function view($conn) {
$id=$_GET['view_id'];
$admin_view="SELECT * from view_table WHERE Id=$id";
$result = $conn->query($admin_view);
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$parent_name=$row['Name'];
$parent_email=$row['Email'];
$admin_mobile=$row['Mobile_no'];
}
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href='delete.php?function=delete&del_id=$id' >Delete</a>
<a href='#Popup' onClick='a_onClick(<?php $id?>)' class='btn-view'>View</a>
<form action="#" method="post">
<input type="text" name="Name" placeholder="username" value="<?php echo $parent_name;?>" >
<input type="email" name="email" placeholder="email" value="<?php echo $parent_email;?>" >
<input type="text" name="Mobile_no" placeholder="Mobile no" value="<?php echo $admin_mobile;?>" >
Cancel <span class="close"></div>
</form>
<script>
function a_onClick(id) {
var id = id;
var Name=$('#name').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "delete.php?function=view&view_id=id",
data:'Name='+Name,
dataType: "html", //expect html to be returned
success: function(response) {
// $("#responsecontainer").html(response);
alert(response);
}
});
}
</script>
you need to change some changes
<a href='#Popup' onClick='a_onClick(<?= $id ?>)' class='btn-view'>View</a>
<script>
function a_onClick(id) {
var id = id;
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "delete.php?function=view&view_id=id",
data:'Name='+Name,
dataType: "html", //expect html to be returned
success: function(response) {
// $("#responsecontainer").html(response);
alert(response);
}
});
}
</script>
hope its help you

How to pass on a form through Ajax, and PHP

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>

Pass variable from Ajax to PHP does not work

I have such code
<form>
<input type="text" value="" name="someval">
<button id="ajax-button">ajaxButton</button>
</form>
<script>
$(document).ready(function(){
$('#ajax-button').click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "action.php",
data: { text : $('input[name=someval]').val() },
dataType: "text",
success: function (data){
alert(data);
}
});
});
});
</script>
Now I try to echo the Ajax returned value in php.
I try
echo json_encode($text);
echo $text;
echo $_GET['text'];
Al are wrong.
How to get it in PHP.
Thanks
Set attributes for the form to get semantic correct html
<form action="action.php" id="someForm" method="POST">
<input type="text" value="" name="someval">
<select id="someSelect">
<option value="some_1">some 1</option>
<option value="some_2">some 2</option>
<option value="some_3">some 3</option>
</select>
<button id="ajax-button">Send</button>
</form>
Your script
<script>
$(function(){
var form = $("#someForm"),
select = $("#someSelect"),
url, formData;
form.submit(function(event){
event.preventDefault();
url = form.attr("action");
formData = form.serializeArray();
$.post(url, data, function(response){
console.log($.parseJSON(response));
});
});
select.change(function(){
url = form.attr("action");
formData = form.serializeArray();
$.post(url, data, function(response){
console.log($.parseJSON(response));
});
});
});
</script>
Your php file(path to file set in action attribute of the form).
<?php
var_dump($_POST);
?>
Use data: 'text=' + $('input[name=someval]').val() , instead. And in PHP you can directly access it using echo $_GET['text']; only without the need of json encoding it.
Otherwise the syntax of json is data: { "text" : $('input[name=someval]').val() },.

jQuery ajax form doesn't work

I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped

Categories

Resources