Sending javascript variable from view to controller in Codeigniter [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get JavaScript function data into a PHP variable
i have a javascript variable in order.php view and i want to send that variable to a controller and then to the model to write it in to the database.
ex: var myOrderString = "something" to order.php controller.
how to do this?

To build on rayan.gigs and antyrat's answers, below is a fix to rayan.gigs answer and how you would receive that information on the controller side:
rayan.gigs fixed answer (modified to match controller example below):
// your html
<script>
var myOrderString = "something";
$.ajax({
type: "POST",
url: <?= site_url('OrderController/receiveJavascriptVar'); ?>
data: {"myOrderString": myOrderString}, // fix: need to append your data to the call
success: function (data) {
}
});
</script>
The jQuery AJAX docs explain the different functions and parameters available to the AJAX function and I recommend reading it if you are not familiar with jQuery's AJAX functionality. Even if you don't need a success callback, you may still want to implement error so that you can retry the AJAX call, log the error, or notify the user if appropriate.
antyrat (modified to fit controller example below):
<form action="<?= site_url('OrderController/receiveJavascriptVar'); ?>" method="POST" id="myForm">
<input type="hidden" name="myOrderString" id="myOrderString">
</form>
<script>
var myOrderString = "something";
document.getElementById('myOrderString').value = myOrderString;
document.getElementById('myForm');
</script>
The controller could look like this for both of the above cases:
<?php
class OrderController extends CI_Controller
{
public function receiveJavascriptVar()
{
$myJSVar = $this->input->post('myOrderString');
// push to model
}
}
?>
I would recommend rayan.gigs method instead of abusing forms. However, if you are trying to submit user information or submit information along side an existing form submission, you could use antyrat's method and just insert a hidden that you fill either on render, or via javascript.

You want to send var from view to anther controller ..... it's mean new request
It's easy to do using Ajax request
In View
// your html
<script>
var X = "bla bla ";
$.ajax
({
type: "POST",
url: // ur controller,
success: function (html)
{
}
});
</script>

You can create simple html <form> with hidden field. Assign your JS variable to that field and submit the form.
Simple example:
<form action="order.php" id="myForm">
<input type="hidden" name="myOrderString" id="myOrderString">
</form>
<script>
var myOrderString = "something";
document.getElementById('myOrderString').value = myOrderString;
document.getElementById('myForm');
</script>
Now in order.php You will have _GET value of myOrderString.
Also you can do it simply using AJAX.

Related

how to submit form data using formdata object from one form to another form using jquery ajax

How to submit 1st form data to another remote form data using formdata object and jquery ajax, finally get result from remote form?
Well, is a bit undefined question but I'll try my best.
First of all you need an HTML or PHP where you will recieve data from AJAX form, like:
<div id="ajaxform">
<button id="ajaxform" class="button"></button>
</div>
Then, in your javascript:
$(document).ready(init);
function init() {
$('#ajaxform').click(sendAJAX);
}
function sendAJAX(){
$.ajax({
type: "POST",
url: "yourPHP.php",
dataType: "json",
data: {//data to send using JSON
},
success: function (respJSON) {
var X= respJSON.X;
var Y= respJSON.Y;
}
}
Now, you have to edit your PHP, as:
<?php
//your data from HTML as:
$varZ = $_POST['varZ'];
//Code where edit data, etc
echo ($respJSON);
?>
Hope it helps, if you improve your question I can edit my answer to make it less general.

PHP + AJAX - Pass Current $_GET Variables So Far

I have a page where users fill out $_GET data for some options. I'd like to pass these $_GET variables using AJAX to a .php script. But my issue is how do I pass those $_GET variables they filled out so far, without refreshing the page?
Here is my code so far.
$.ajax({
type: "GET",
url: "serverside script to process on data",
data:{name:youwant}, // Here is where I want to take what the user has filled out so
// far, and place it here all without refreshing the page
success: function(data){
alert("return here if success")
}
})
First of all, drop this task into small ones:
1) Get/process variables in JavaScript
2) Send them to PHP
3) Parse/handle the ones
4) Depending on result send respond back to JavaScript
5) Handle that respond and display a message to user
Take a look at this example,
Let's assume that jquery.js is loaded.
Assume that we want to send the values of the inputs we have - email and password.
<script type="text/javascript">
$("#Send").click(function(){
$.ajax({
type : "GET",
//Look carefully:
data : {
// it'll be PHP vars // This is JS vars
email : $("#email").val(),
password : $("#password").val()
},
success : function(respondFromPHP){
alert(respondFromPHP);
}
});
});
</script>
<input type="text" id="email" />
<input type="password" id="password" />
<br />
<button id="Send">Send to php</button>
In your php script, just handle vars you get, like this:
<?php
print_r($_GET); // will print smth like Array("email" => "foo", "password" => "bar")
// Then create function so that you can simplify handling of the vars.
// Like this:
function validate_password($password){}
function validate_email($email){}
I don't know your code, but you can have a form, but instead of submit it, you put a onsubmit method to a javascript function. In that function you gather all variables and pass it through ajax.
Example: <form name="form1" method="get" onSubmit="return send()">
<script>
function send() {
$.ajax(...);
return false;
}
</script>
You can use seralize function to send in $.ajax data field

What does jquery .ajaxsubmit pass?

I am trying to use jquery's form plugin from http://www.malsup.com/jquery/form/#ajaxSubmit and .ajaxsubmit to submit my data in a form however I am not really sure what .ajaxsubmit is passing and how I can read this in my php file.
I have a validate function
function validate(formData, jqForm, options) {
alert('About to submit: \n\n' + queryString);
return true;
}
that shows queryString which is
first=testfirstname&last=testlastname&age=90
when I use .ajaxsubmit, nothing happens as listed in my script below.
$(document).ready(function() {
var options = {
target: '#output1',
beforeSubmit: validate,
success: showResponse
};
//submission
$('#myForm').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
My form is
<form action="comment.php" method="post" id="myForm">
I was wondering what format is the data being sent, would I do something with
$_REQUEST['first'];
and also how would I also pass in an addition value from the $_SESSION?
Thanks
As far as I know, the jQuery plugin actually sends the plugin data as POST-data to PHP (similar to setting method="post" on your <form> tag). You can access it like this:
$_POST['name_of_field_in_form'];
The name_of_field_in_form is just the name of a field, for example if you have this code <input name="email" type="text" />, you could access it via $_POST['email'];.
About your second query, not sure what you mean, but you can use session_start(); to create a session and after that $_SESSION acts like a 'normal' array.

Send $.post from JQuery to controller in code igniter and load the result

I want to send a post from HTML that contains info about a certain form to a controller in code igniter. The I want the controller to process the info and loads a certain page inside a div. Here is my code. I think I'm supposed to use something like .html or something? I'm not quite sure, I dont understand it
The controller
function search_friend(){
//this function gets text from text field and searches for a user and returns all users similar to this dude
// $this->input->post($searchFriendForm);
// $this->input->post($searchFriendText);
$this->load->model('userProfile_m');
$people = $this->userProfile_m->get_user_by_name($this->input->post($searchFriendText));
$this->load->view('addFriendSearchResult',$people);
}
the form in html
<form method="post" action="" name="searchFriendForm" id="add-friend-search">
<input type="text"/ name="searchFriendText">
<input type="button" class="small green button" id="add-friend-button" />
</form>
the jquery function
$("#add-friend-button").click(function(){ //start click
$.post("<?php echo site_url('userProfile/search_friend'); ?>", $("#add-friend-search").serialize());
$("#insert-activity").load("<?php echo base_url().''?>system/application/views/addFriendSearchResult.php");
$("#add-friend-search").slideUp("slow",function(){});
}); //end click
Firstly, in your controller change this line like this (u need to pass the string name of the field here):
$people = $this->userProfile_m->get_user_by_name($this->input->post('searchFriendText'));
Next, change your jQuery to be like this:
$("#add-friend-button").click(function(){ //start click
$.post("<?php echo site_url('userProfile/search_friend'); ?>",
$("#add-friend-search").serialize(),
function(data){
$("#insert-activity").html(data);
});
$("#add-friend-search").slideUp("slow",function(){});
}); //end click
You cant call your view directly, and you don't need to. The post should return the data, which you can write out to your #insert-activity element.

jQuery, Ajax & PHP submit multiple forms dilemma

This is a very simple form that I have found on the web (as I am a jQuery beginner).
<!-- this is my jquery -->
<script>
$(document).ready(function(){
$("form#submit_wall").submit(function() {
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
</script>
<!-- this is my HTML+PHP -->
some PHP ...
while($row_pilt = mysql_fetch_assoc($select_pilt)){
print
<form id="submit_wall">
<label for="message_wall">Share your message on the Wall</label>
<input type="text" id="message_wall" />
<input type="hidden" id="id" value="'.(int)$row_pilt['id'].'">
<button type="submit">Post to wall</button>
</form>
and down below is my PHP script that
writes to mySQL.
It is a pretty straight forward script. However, it is getting little complicated when I submit it. Since I have more than one form on my page (per WHILE PHP LOOP), thus when I submit - only the FIRST form gets submitted. Furthermore, any other subsequent forms that I submit - data is being copied from the first form.
Is there any jQuery functions that clear the data? - or is there a better solution.
Thanks,
Nick
It's because you're giving each form the same id, and thus it is submitting the first element it finds with that id, i.e. the first form. What you should do is assign a unique id to each form, and then give each form an AJAX submit function that submits the form-specific data. You can use jQuery's $.each() function to loop through all the forms and $(this).attr('id') within the submit function to retrieve the form-specific id.
UPDATE: As revealed by the comment on this answer, you actually don't need the each() function because jQuery applies it to every form element anyway.
Here would be an example script:
$(document).ready(function(){
$("form").submit(function() {
var message_wall = $(this).children('input[type="text"]').attr('value');
var id = $(this).children('input[type="hidden"]').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
Because we can't see all of your forms, I'm not entirely sure, but given your question I'm going to assume that the other forms all share the same id (form#submit_wall), which is invalid an id must be unique within the document.
Given that you're going to change the id of the other forms (I'd suggest using a class name of, probably, 'submit_wall', but the specifics are up to you), the jQuery needs to be changed, too. From:
$("form#submit_wall").submit(function() {
To:
$("form.submit_wall").submit(function() { // using the class-name instead of the id.
Now, of course, you run into the same problems of duplicate ids.
So I'd suggest, again, changing the id to a class and changing:
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
to:
var message_wall = $(this).find('.#message_wall').attr('value');
var id = $(this).find('.id').attr('value');
Given the mess that you've posted, above, I find it hard to believe that this is all you need. It would definitely be worth posting the full page (or a demo at JS Fiddle or JS Bin) that fully reproduces your code.

Categories