Javascript script (ajax) not working (php+ajax for live search) - javascript

I tried to make live search with php and ajax but this function is not working at not it's not entering the script.. I don't know why.
The PHP code is working.
<form autocomplete="off">
<input type="search" id="search" name="search" placeholder="Search..." />
</form>
<br>
<div id="search_result"></div>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
$("search_result").show();
var txt = $(this).val();
$.ajax({
type="GET",
url:"fetch.php",
data:"q=" + txt,
success:function(data)
{
$("#search_result").html(data);
}
});
});
});
</script>

$("search_result").show();
should be
$("#search_result").show();
and as mentioned
type="GET",
should be
type: "GET",
What is the php code returning?
And what are the console errors?

type="GET" should be type: "GET"

Related

Form submit only one value with AJAX passing form data to PHP in the same page

I need to pass a single value from my form to my php in the same page. It´s probably not an option to create another .php file and take the code there since there´s a lot going on.
This is the part of the code I need to fix, currently it only works when the code is on another file, since the $_POST is not messing around with other parts of the code. Specifically I need to manage to pass the 'client' or the 'empre' from the form alone to the php.
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
if($(".cliente").click(function() {
var name = $("#client").val();
var dataString = 'client='+ name;
}))else if($(".empresa").click(function() {
var name = $("#empre").val();
var dataString = 'empre='+ name;
}));
$.ajax({
type: "POST",
data: dataString});
});
</script>
</head>
<body>
<form>
<input name="client" type="text"><br>
<input class="cliente" type="submit" value="Buscar cliente"/><br>
<input name="empre" type="text"><br>
<input class="empresa" type="submit" value="Buscar empresa"/><br>
</form>
//PHP HERE
//HTML AGAIN
</body>
</html>
PHP (same page, just separating for readability)
if(isset($_POST['empre'])){
//DB QUERY
}
elseif(isset($_POST['client'])){
//DB QUERY
}
You can combine and send it in same AJAX call as below, and in PHP you can do:
$parameters = json_decode($_POST['params']);
$parameters would have all the variables sent in that AJAX call.
I would recommend, not to use same page for your AJAX. You should keep it in separate file. That would make code much cleaner, lighter, readable and easy-to-tweak.
$(function() {
$(".cliente, .empresa").click(function(e) {
e.preventDefault();
var paramsToSend = {};
if ($(this).hasClass('client'))
paramsToSend['client'] = $('form[name="client"]').serialize();
else
paramsToSend['empre'] = $('form[name="client"]').serialize()
$.ajax({
url: 'index.php' //assuming this is index.php (same page)
type: "POST",
data: {
params: JSON.stringify(paramsToSend)
},
success: function(data) {},
failure: function(error) {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="client">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente" />
</form>
<form name="empre">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa" />
</form>
//PHP HERE //HTML AGAIN
Why not use separate forms to process the data? (Your PHP logic mentioned will work with this proposed solution)
$(function() {
$(".cliente").click(function(e) {
e.preventDefault();
alert('Going to post data for client, check the console log now');
$.ajax({
url: $('form[name="client"]').attr('action'),
type: "POST",
data: $('form[name="client"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
$(".empresa").click(function(e) {
e.preventDefault();
alert('Going to post data for empre, check the console log now');
$.ajax({
url: $('form[name="empre"]').attr('action'),
type: "POST",
data: $('form[name="empre"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="client" action="https://someurl.com/fileto.php">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente"/>
</form>
<form name="empre" action="https://someurl.com/fileto.php">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa"/>
</form>

Submit jQuery ajax Form with multi buttons and PHP

here is my problem:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="roomform" action="room.php" method="POST">
<button name="room" value="Room01">IMG01</button>
<button name="room" value="Room02">IMG02</button>
<button name="room" value="Room03">IMG03</button>
<button name="room" value="Room04">IMG04</button>
<button name="room" value="Room05">IMG05</button>
<button name="room" value="Room06">IMG06</button>
<button name="room" value="Room07">IMG07</button>
<button name="room" value="Room08">IMG08</button>
<button name="room" value="Room09">IMG09</button>
<button name="room" value="Room10">IMG10</button>
</form>
<script type="text/javascript">
var frm = $('#roomform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP using $_POST['room'] to get the room name Room01-Room10(Room100 maybe?) and doing something special.
It works good.
Now I need to do this using Ajax. Above code seems ok, but I cannot get any data(Room01-Room10) from it.
then I found this:
<form action="/vote/" method="post" class="vote_form">
<input type="hidden" name="question_id" value="10" />
<input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
<input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>
$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
// do something with response (data)
});
});
but it seems not suitable to my case, my all buttons with same name="room" for $_POST['room'] and no class.
and this not works:
$(function() {
$('input[name=room]').click(function(){
var _data= $('#roomform').serialize() + '&room=' + $(this).val();
$.ajax({
type: 'POST',
url: "room.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
anyone know how to solve this problem?
Your (last) code is not sending AJAX requests because you attached the handler to the wrong input selector. Your buttons are button elements, not input elements. This should work:
$('button[name=room]').click(function() { ...
Edit:
Your first code isn't working because your buttons are just buttons. You have to add the type attribute to let your form know you're pressing a submit button: <button type="submit"...>
The serialize() method does not collect the data from a button element. Take a look to the documentation on this link: https://api.jquery.com/serialize/. In your code I would assume that your data object is empty.
Also if you post several form controls (serialized) , they should have different name attributes.

Form submitting on return false

I have the following form:
<form id="sizeForm" style="float:right;">
<input value="test" name="comments" type="text">
<input class="btn-sm btn-main" value="Save" type="submit">
</form>
Which I'm trying to submit using ajax but the form is posting, here's the JQuery:
$("#sizeForm").submit(function () {
$.ajax({
type: "POST",
url: "/ajax/actions/editSize.php",
data: $(this).serialize(),
success: function (dataBack) {
$('#size2'+dataBack).fadeOut().promise().done(
function(){
$('#size1'+dataBack).fadeIn();
}
);
}
});
return false;
});
Any ideas where I'm going wrong?
The issue may be with your PHP script (which you haven't provided), but here are some ideas.
HTML:
<form id="sizeForm" style="float:right;">
<input value="test" name="comments" type="text">
<input class="btn-sm btn-main" value="Save" type="submit">
</form>
javascript:
$("#sizeForm").on('submit', function () {
$.ajax({
type: "POST",
url: "/ajax/actions/editSize.php",
data: $(this).serialize(),
success: function (dataBack) {
$('#size2'+dataBack).fadeOut().promise().done(
function(){
$('#size1'+dataBack).fadeIn();
}
);
}
});
return false;
});
In your PHP script add something like this so you know the value is received. This will show in the network tab in the browser developer tools.
if (!empty($_POST['comments'])) {
echo "form submitted!";
exit;
}
In the network tab, you should see an entry like POST editSize.php. If you don't see it, the form was not sent. If you do see it, open it up and look at the "post" tab. This will show you what was sent. Then, your "response" tab will show you the output from your PHP script.

Is there a way to send data from html tags to php?

I am trying to alter the functionality of submit button for some reasons. If have called a JS function which is called by clicking submit button but i have no idea how can i manually send my data from html tags to php variables. Below is the short description of code.
<html>
<body>
<input class="inputtext" id="email" name="email" type="text"></div>
<input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">
<script>
function myFunction() {
var TestVar =document.getElementById("email").value;
document.write(TestVar);
//store data of testvar to php
}
</script>
<html>
<body>
I know it can be done by form but i need it this way.
Using a PHP form would be a really simple solution: http://www.w3schools.com/php/php_forms.asp
You could pretty much post it strait to the PHP page.
I hope you are comfortable with jQuery.
Try
$("#login").click(function(){
var email= $("#email").val();
jQuery.post(
"*your parsing url*",
{email:email},
function(data){
// Data returned from the ajax call
}
)
});
The jQuery library makes this, and many other tasks, very simple:
<html><head></head><body>
<form id="myForm">
<input class="inputtext" id="email" name="email" type="text"></div>
<input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function myFunction() {
jQuery.ajax({
url: 'yourcode.php',
type: 'POST',
data: jQuery('#myForm').serialize(),
success: function(response) {
alert('The data was sent, and the server said '+response);
}
});
}
</script>
</body></html>
See http://api.jquery.com/jquery.ajax/ for more information.

input value data is not passing using jquery/ajax to Php

I'm trying to get result from Mysql database but I'm getting warning message it's because it's not passing the html field value to jquery/ajax method. I think issue is on this line data : SearchValue,. So that In my php page it's not getting $search = $_POST['SearchValue']; value and showing warning message.
Can anyone tell what is wrong in my code ? Thank You.
Html Page:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
var SearchValue = $('#txt_name').val();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "doSearch.php",
data : SearchValue,
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="text" name="search" id="txt_name" /> </td>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
Php page:
$search = $_POST['SearchValue'];
Please Use Below Code :
$(document).ready(function() {
$("#display").click(function() {
var SearchValue = $('#txt_name').val();
var str = $( "#form_id" ).serialize();
$.ajax({
//create an ajax request to load_page.php
type: "POST",
url: "doSearch.php?searchValue="+SearchValue,
data : str,
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
You are submitting the form via native method. That means if you click on your submit button the page will be reloading (since in your case you haven't included the form action).
One thing you could do is make a button and a textfield outside of the form and declare its onClick attribute like this:
<input type="text" id="search">
<button onclick="doSearch(document.getElementById('search').value)"> Search <button>
OR
<input type="text" id="search">
<button onclick="doSearch($("#search").val())"> Search <button>

Categories

Resources