I'm using cakePHP 1.3 and would like to use AJAX from my search view to the search action in my controller. I was using prototype and scriptaculous and it was working fine, but need to use purely jQuery.
The search action basically looks as follows:
public function search() {
if (empty($this->data)) {
} else {
$request = $this->data;
$this->set('data', $this->Event->search($request['Event']['search']));
}
}
The view currently looks like:
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
var data = searchString;
if(searchString) {
$.ajax({
type: "POST",
url: "/events/search",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
<div id='container'>
<h1>Corporate Events</h1>
<form method="post" action="search">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
What is the best way to make the 'data' variable available to $this->data in the controller? I checked the other threads with similar questions, but was unable to see how to do this.
Thanks!
Send it as POST ( refer to http://api.jquery.com/jQuery.post/ ) or url_encode (google "javascript url encode") the string and append it to the url. Not sure which was is better, both should work and be easy to implement.
Related
Can't figure out what's wrong but all that happens is the URL changes to "http://localhost/?search=test" if I enter "test" for instance.
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$("#Form").submit(function(e) {
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
</script>
</head>
<body>
<form id=Form>
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
search.php
<?php
echo 'The search is '. $_POST['search'];
?>
You're missing the action and method on your form, which are necessary for the form to generate a submit event.
<form id="Form" method="post" action="search.php" />
Now that we have the action and method defined, why not just take it from the form instead of re-writing it in Javascript? That would be better for re-usability. Also note that you have to assign event handlers when the DOM is ready. At the time you're assigning the event, the DOM element doesn't exist, so it will do nothing:
<script type="text/javascript">
$(document).ready(function() { // Here, after DOM is ready
$('#Form').submit(function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// At this point, we already have the response from the server (we got it asynchronously)
// Lets update a div, for example <div id="response_message"></div>
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
// Another option (same as before but with a function): Pass the response data to another function already defined: processData() in this case
// Use one or another, they're the same
processData( data );
},
error: function(err) {
alert('An error just happened...');
}
});
});
});
// This functions only receives data when the asynchronous call is finished
function processData( data )
{
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
}
</script>
Note that in asynchronous calls you DO NOT expect a return. It simply doesn't exist by design (because the script would be blocked until the data is ready, and that's called synchronous). What you do in asynchronous calls is to define a function/method that will be called at any time when the data is ready (that's the success handler function). You don't know at what time it will be called, you only know that it will be called when data has been fetched and the argument will be the actual response from the server.
1st you forget " Form id and good to add method=""
<form method="post" action="#" id="Form">
2nd try to use e.preventDefault(); in the beginning not the end
3rd try to rearrange the code
<body>
<form method="post" action="#" id="Form">
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
<script>
$("#Form").on('submit',function(e) {
e.preventDefault(); // use it here
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
});
</script>
I am writing a plugin for a wordpress, where I use jquery for AJAX.
Following code doesn't work. I expect to show the content in results div when I type in input box.
Here is the code I use for ajax request. It is located on my theme header file.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
//alert("sjsjs");
$("#se").keypress(function(e){
// e.preventDefault();
var search_val=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_string:search_val
},
success:function(data){
$('#results').append(response);
}
});
});
});
</script>
html content in template file
<form name="nn" action="" method="post"></br></br>
<input id ="se" type="text" name="test" width="20" />
<input type="submit" id="clicksubmit" value="Submit" />
</form>
<div id="results">val is:
</div>
Here is the code in plugin file
function wpay_search() {
//global $wpdb; // this is how you get access to the database
$whatever = $_POST['search_val'];
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
add_action('wp_ajax_wpay_search', 'wpay_search');
add_action('wp_ajax_nopriv_wpay_search', 'wpay_search');
I am new to wordpress plugin writing. Can anybody tell that where I have done the mistake?
Well one thing that obviously jumps out to me is this...
success:function(data){
$('#results').append(response);
}
Should be...
success:function(data){
$('#results').append(data);
}
Because you have no variable called response, you passed the function data as a variable, so you have to use that.
Also, you're passing search_string as a paremeter, when infact in your php file, the $_POST is looking for search_val.
So you need to send search_val as parameter and give your JavaScript search_val variable another variable name in the JavaScript, just for less confusion. In this case I made it search.
action:'wpay_search',
search_val:search
So overall it should look something like this...
$("#se").keypress(function(e){
e.preventDefault();
var search=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_val:search
},
success:function(data){
$('#results').append(data);
}
});
});
Hi I'm looking to check my database when a user signs up to my website to make sure that the username they chose doesn't already exist and if it does let them know. My code below isn't working though the returns in the ajax don't seem to be returned to my form no matter what i do and the form always submits. Why is this happening? Thank you for any help
HTML
<form name="signup" action="Test1.php" onsubmit="return checkUser();" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
Javascript
<script type="text/javascript" src="jquery-1.7.1.min.js"/></script>
<script type="text/javascript">
function checkUser(){
var userV = document.signup.user.value;
$.ajax({
url: "Test.php",
type: "POST",
data: {user:userV},
success: function (response) {
if(response=="0"){
//Username already exists notify user
return false;
}else{
return true;
}
}
});
}
</script>
Test.php
<?PHP
$user = $_POST['user'];
if($user=="test"){
die("0");
}else{
die("1")
}
?>
Test1.php
<?PHP
echo "Form submitted";
?>
You put the return value inside the success callback of your ajax call, whose execution is delayed till server answers.
onsubmit="return checkUser();" expects a true or false value in checkUser() function:
function checkUser(){
if( stuff )
return true;
else
return false;
}
Anyway this is an overall bad approach because it relies on intrusive javascript. A better solution would be moving all client side logic out of markup:
HTML
<form name="signup" action="Test1.php" method="get">
<label for="_user">Username:</label><input type="text" name="user" id="_user"/>
<input type="submit" value="Submit" />
</form>
JS
<script>
// wrapping the code in a $(function(){ ... }); call delays its execution till document is loaded
$(function(){
$('form[name="signup"]').on('submit', function(event){
// this prevents browser from actually following form url
event.preventDefault();
// a reference to the form to get used inside ajax callback
var form = this;
$.ajax({
url: $(form).attr('action'),
type: "POST",
data: {user:$(form.user).val()},
success: function (response) {
if(response=="0"){
alert('User exists!');
}else{
alert('User does not exist!');
}
}
});
});
});
</script>
Where the alerts would be a proper message to the user, or a more sophisticate validation - this is just for example's sake.
You return false in the callback, thats too "late", as it will be called when the request is done. Think about adding an explicit e.preventDefault() or return false to your function. Currently, it will return undefined, as you have defined the return statement in the "inner" function.
Of course you will then need to manually navigate to the target page.
Or set the async parameter of the $.ajax() call explictly to false.
I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;
a quick question. I am using the jQuery.forms.js plug-in.
I have a form that posts to a php page and returns data with jSon.
The data that is returned is code for a new form (it replaces the form that was used to post the information). The new form is not bound to any jQuery functions, as it was not around when the page loaded.
So, how can I get ajax form to recognize the new form, so that if i need to use the form a second time, it is also utilizing the jQuery function?
// jQuery for submitting info to php doc and, on success, replacing the form
$(document).ready(function() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
});
<!-- /////////////////////// POST ONLINE /////////////////////// -->
<div id='onlineStatus<?php echo $b_id ?>' class='postOnline'>
<form name="postOnline" id="postOnline<?php echo $b_id ?>" action="postOnline.php" method="post">
<input type="hidden" value="<?php echo $b_id ?>" name="b" />
<input type="hidden" value="1" name="p" />
<input type="submit" class="button" value="Post Online" />
</form>
</div>
<!-- /////////////////////// POST ONLINE /////////////////////// -->
// ... code for entering data into database and then...
$result = mysql_query( $sql );
if($result) {
if($show == '1'){$val = 'remove from online'; $num='0';}
if($show == '0'){$val = 'show online'; $num='1';}
$return = "
<form name='postOnline' id='postOnline$id' action='postOnline.php' method='post'>
<input type='hidden' value='$b_id' name='b' />
<input type='hidden' value='$num' name='p' />
<input type='submit' class='button' value='$val' />
</form>
";
print json_encode(array("rid" => $id, "formed" => $return));
}
?>
The easiest solution to this is not using jQuery's form plugin and doing it manually, which is really not very difficult:
$(document).ready(function() {
jQuery('form[id*=postOnline]').live('submit', function() {
var formdata = $(this).serialize();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
dataType: 'json',
data: formdata,
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
return false;
});
});
Now since you are using jQuery's new (1.3) live functionality, any forms you add that match the form[id*=postOnline] selector will still be wired with this event.
Alternatively, you can open up the jquery forms code and find wherever it does its binding and try to modify it so that it uses it live. Even another alternative would be to encompass the wiring in a function, and call it at the end of your success function, like so:
function bindForm() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
bindForm();
}
});
}
$(document).ready(function() {
bindForm();
});
I don't think it is very neat, but it should work.
You need to rebind the event handlers after the ajax call. I heard about a new feature in the newer version of jquery called live events, that would make this unnecessary though.
If for whatever reason you're stuck with a pre-1.3 version of jQuery, use the "livequery" plugin.