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.
Related
So i'm a completely rookie at AJAX so I was wondering if someone could help.
I'd like to get this, SQL command to be activated onkeyup:
SELECT * FROM commands WHERE tag=$_POST['search_input']
This is the current code I have for the form:
<form method="post">
<input class="search_input" type="text" name="search_input" placeholder="Search..." onkeyup="suggest()" autocomplete="off" />
</form>
Current jQuery:
$(document).ready(function() {
$('.search_input').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
function handleKeyPress(e,form){
var key=e.keyCode || e.which;
if (key==13){
form.submit();
return false;
}
}
});
the function suggest() is what I'd like your guy's help on. To send the command above on a keypress.
Use $.post(). You have here examples http://api.jquery.com/jquery.post/
The basic structure is
$.post(url(string), data(object), function(response){ /* do something */ });
A delay between inputs would be really good so it won't continuously send requests to the server. You may also want to use keyup instead of keypress, test it and you'll see why.
I would recommend to use...
HTML
<form method="post">
<input class="search_input" type="text" name="search_input" placeholder="Search..." autocomplete="off"/>
</form>
JS
// shorthand for document ready
$(function(){
var $input = $('.search_input');
// using on-function (see jQuery Docs)
// bind event instead of using on-attribute (nicer)
// bind input event instead of keyup, because it will fire on paste too
$input.on('input', function(evt){
$.ajax({
// maybe use GET?
type: 'POST',
url: '/yourQueryPath',
// assign the input value to the needed query parameter
data: {'search_string': $input.val()},
success: function(response){
// whatever you want to to with your response
}
)};
});
});
Additionally a hint: Never use unfiltered user input like your SQL does (MySQL-Injection)!
E.g. if you are with PHP please use filter_input() and mysql_real_escape_string() or simliar.
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
I'm using JQuery Form Plugin for AJAX file uploader.
The (html) form is created dynamically, and looks like this:
<form id="formUpload" action="fileReceiver.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" multiple>
<input type="submit" value="Upload File to Server">
</form>
Because, the form is created dynamically, I'm using jquery on(). I also need to send a few variables, I'm using data options from the plugin.
The Javascript looks like this:
$(document).on("submit", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
I think the form is binded correctly, I could call/alert something from the ajaxForm (jquery form plugin) function through beforeSend or Success options.
Now, the problem is the PHP couldn't get the data I posted in the Javascript.
My PHP is simple like this:
<?php
echo $_POST["someVariable"];
?>
It gives me error "Notice: Undefined index: someVariable blah blah blah"
Any advice? Thx :)
Try adding some variables in hidden input inside form
<input type="hidden" name="someVariable" value="someValue">
and remove $(document).on("submit",... event
You can try
var input = $("<input>").attr("type", "hidden").attr("name", "someVariable").val("someValue");
$('#formUpload').append($(input));
this links may help you
http://www.malsup.com/jquery/form/progress2.html
http://www.malsup.com/jquery/form/file-echo2.php.txt
Well, in case your form is being added dynamically then you'd have to use DOMNodeInserted event instead of submit. That way, whenever there's some addition in DOM your form will be attached to form plugin.
You can replace your function with following --
$(document).on("DOMNodeInserted", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
// do something
}
});
});
But remember, using DOMNodeInserted event will fire that method whenever there's addition of any kind into DOM. So just put what is essential ( in this case form plugin init for #formUpload ) .
Try to locate if you already added the jQuery Form Plugin...
<script src="jquery.form.js"></script>
Your syntax is definitely correct according to http://malsup.com/jquery/form/#options-object
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
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.