ajax jquery search form in PHP - php

This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.

If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});

If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}

First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});

After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).

First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});​

Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.

Related

Multiple forms using same AJAX call with different outcomes?

If I have many forms generated by PHP and want a "Reply" button on each of them, where it sends the content of the form via ajax to another php page, then can I use the same javascript snippet for all of these elements?
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Reply" />
</form>
So if I do something like the following, then can I still handle all the responses individually and display the response ONLY on the element that "Reply" was clicked on?
$("#foo").submit(function(event){
$.ajax({
url: "/form.php",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked only in the element it was clicked in!");
});
// prevent default posting of form
event.preventDefault();
});
If you want to handle all forms on the page, your code could work with minor changes.
$("form").submit(function(event){
$.ajax({
url: "/form.php",
type: "post",
// You have to have a way to retrieve the form data
data: getFormData(form),
success: function(response, textStatus, jqXHR){
console.log("Hooray, it worked only in the element it was clicked in!");
});
// prevent default posting of form or just return false
event.preventDefault();
});
No, there are multiple ways on submitting a form. You would want to change your first line to:
$("#replybutton").click(function(event){
Then you have to add that replybutton id to your button, and you'd have to explicitly list out the data elements in your ajax call. Also, the event.preventDefault() would be unnecessary. Come to think about it the whole <form> tags would be unnecessary as well.
There are other ways to do this using the form, but this is the simplest.

ajax post form when checkbox is changed jquery ajax not working

i am trying to create a form submit when checkbox is changed
my code is given below. . my problem is nothing happens on
gotofile.php
file but //dosomething
on the sucess function is executed
the jquery:
$("#container input[type=checkbox]").change(function(e){
if($(this).attr('checked'))
{
var cnType=$(this).attr("id");
$.ajax({
type: "POST",
url: "gotofile.php",
data: "typID="+cnType ,
cache: false,
success: function(){
//do something
}
});
}
});
the php:
include '../dbconnection/dbconfig.php';
$typeID=$_POST['typID'];
$qryConnections="INSERT INTO ...";
$rslt1 = mysql_query($qryConnections);
the html
<form id="cnct" method="POST">
<div id="container" style="">
<ul style="list-style: none;">
<li><input type="checkbox" id="1" />A</li>
<li><input type="checkbox" id="2" />B</li>
</ul>
</div></form>
Can any one help me what i am doing wrong?
A couple of security issues
Always keep in mind that your JS is viewable to anyone that navigates to your site. Using:
data : "typID="+cnType
Would make me think that typID is the field in your SQL. You have no CSRF filter, therefore I could write an ajax script to spoof valid requests and update all of your fields from an external location. Something to keep in mind, I recommend you read up on CSRF or Cross Site Request Forgery.
Why doesnt your script work
If the success function is firing, then the script has run. Debug it by outputing the value of $_POST['typID'] in your PHP. You will see the variables value in the console if it sent correctly.
As well as this it's always good to have your PHP echo out a JSON response for your success function to validate that all went well.
echo json_encode(array('response' => 'success'));
or ('response' => 'failed') or whatever you need. You can then evaluate the JSON in your success function.
I hope this helps.
The first thing is you should use click instead of change event for the checkbox in your Jquery code.
The second thing, you did not provide any value to the checkbox in your html code.
Kindly ask if it not worked for you.
Try
$("#container input[type='checkbox']").click(function(e){
var cnType=$(this).attr("id");
$.ajax({
type: "POST",
url: "gotofile.php",
data: "typID="+cnType ,
cache: false,
success: function(){
//do something
}
});
});

Ajax & Jquery form submission

I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.
Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});
If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault
Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.
I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.
Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

How could I stop spam if my form is using ajax submit method (with no reload)?

I have a form which uses ajax for data submitting. Here is the html:
<form>
<input type="text" id="content" name="content">
<input type="submit" class="button" name="button">
</form>
and the JavaScript (jQuery):
$(function() {
//Update Message...
$(".button").click(function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
}
return false;
});
});
It is all working fine, but there is a big problem: I cannot stop spam.
Last time I used spam filters, it was in PHP (I used a hidden input and then checked in the PHP file if it is filled out). But that was totally in PHP, no JS.
So here is my question:
How could I stop spam in this form submission? Also, can I create an if statement in the update_data.php file?
I you do not like to add Captcha here is a good solution:
First add input that is hidden with css in the form. If the bot submits the form the hidden field will have some value filled by the bot. In normal cases the human will not see it and will be empty. In the case of a bot you will check it and if it has some value you will discard.
Also you need to add input (also hidden with css) with javascript on document ready. If it is browser it will execute the javascript and will insert the input in the form. If it is a bot then the bots do not execute js and there will be no input field generated by js and on the server side you will see that there is no such field and you will discard the request.
So on the server side you will check if the first hidden field has value or the second hidden field does not exist discard the request.
First fast answer is putting inside the form something that could help you to understand if the user submitting your form is a bot or not.
Captcha for sure, or just a question not easy to answer for a bot.

Categories