I have some problems loading input field from html using php. I am using jQuery Ajax $.post function to send my data from input filed to php file in order to do the query from the database.
I have fixed the code. Code below is working perfectly.
Here is the html from my main page
<input class="detail" maxlength="60" name="detail" placeholder="Type to search">
<button class="searchbtn" name="search">Search</button>
and this is the jQuery Ajax part
$(".searchbtn").click(function(e) {
makeAjaxRequest();
});
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",{detail:input},function(data,status){
$('#resultTable tbody').html(data);
});
Then last part is the php file (search.php)
if (isset($_POST['detail'])) {
$data = $_POST['detail'];
$query = "SELECT * FROM products WHERE ".%data;
$result = $conn->query($query) or trigger_error($mysqli->error."[$sql]");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
}
Now it worked perfectly. Thanks for the answer.
You are extracting $_POST['detail'] on your server side page, but while sending on client side, you are sending like this, $.post("search.php",input.
Data should be sent data as PlainObject or string. I mean, every POST data should have some index to get referenced on the other end.
Since you are extracting with index detail, add detail on following like:
$.post("search.php",{detail:input},function(data,status){
See : jQuery : $.post()
currently you're just sending a string with no key/value. You need to send a key/value pair as your data parameter, either as a string or an object (object is safer, as it'l get automatically urlencoded)
$.post("search.php",{detail:input},function(data,status){
You could try this.
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",
{detail: input},
function(data,status){
$('#resultTable tbody').html(data);
});
}
Related
assuming that i have an HTML textbox with a name with an array:
<input type="hidden" id="text_array" name="text_array[]" class="test">
and i have a jquery code that gets the data on the textbox:
$('.test').each(function(){
arr = $(this).val();
});
how can i get the array content and transfer it into another laravel view and then print it? i tried to get it by using echo my controller but i have recieved comments about printing outputs in a controller is a bad practice.
Hmm i would recommend to use a Database or Session storage. But one idea is to save the value via JavaScript into a cookie.
Disclaimer: Untested ;)
Save the Value:
$('.test').each(function(){
arr = $(this).val();
document.cookie = 'mycookie=' + arr +'expires=DateHere;path=/'
});
Get it (somewhere):
$value = $request->cookie('mycookie');
I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.
Iam adding html for input tag dynamically through enterPerson() and then calling onkeyup=changeOnType(this) which on echoing $results in autoInvit.php should display autocomplete, but WHY does my autocomlete code does not work,infact data shows if I alert it. can any one please help me out ?
Thank you in advance :)
header files for jquery and autocomplete:
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="//code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
autocomplete in "main.php" :
<script>
function changeOnType(x){
$.post(
"autoInvit.php",
{
vals: $(x).val()
},
function(data){
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
//alert(data);
}
);
}
</script>
here's the dynamic html's php code in "invities.php":
<?php
echo '<input class="e" type="email" id="email" onkeyup="changeOnType(this)" autocomplete="on" role="textbox" aria-autocomplete="list" aria-haspopup="true" />';
?>
Here's my php file "autoInvit.php" which echos the result:
<?php
include("includes/connection.php");
$value = strip_tags($_POST['vals']);
$req = "SELECT email as name "
."FROM members "
."WHERE email LIKE '".$value."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = $row['name'];
}
echo json_encode($results);
?>
Please help
There's no need to make the post request. Edit: There's no need to call a separate function or attach a listener to the input, just register the autocomplete plugin. This will need to be called once the DOM is ready, so you will need to wrap it in a ready function. This should be all the javascript you need:
$(function() {
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
});
What the user has typed will be passed with the request as the parameter term
From the jQuery docs for autocomplete:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
Also, you'll want to be careful when passing content from the user directly to the DB. You can open yourself to SQL injection.
I'm trying to use jQuery to send an input to be processed on another page but I'm having some trouble getting it to work.
When I open up the network console I can see a GET method set to common_functions, but there's no variables attached to it. I'm getting this
http://localhost/project/common_functions.php
instead of something like
http://localhost/project/common_functions.php?name=abcdef
Here's my HTML. It's fine as far as I know because I get an alert from the function receiving the input
<form method="post">
<table>
<tr><td>Project Name</td><td><input type = "textbox" name="project_name" id = "project_name" onkeyup = "get_name(this.value);" /></td></tr>
<tr><td>Project Description</td><td><input type = "textbox" name="project_name" id = "project_description" onkeyup = "get_description(this.value);"/></td></tr>
<tr><td><input type="submit" name="submit_project"></td></tr>
</table>
</form>
Here's the jQuery. I'm attempting to send a GET request.
function get_name(name){
var project_name = name;
$.get('common_functions.php', function(name) {
alert(project_name); //this displays the name
$('#project_name').html(name);
});
}
When I have just this I get an alert, so I know it's at least acknowledging the onkeyup.
You are not sending any data. You can either append the data to the script name or send it as key - value pairs:
$.get('common_functions.php', {'project_name': name}, function(data) {
And I would not use the same variable name in the callback function, that only leads to confusion.
What you are expecting to see is if you called your get function with the following parameter.
var url = 'common_functions.php?project_name=' + Name;
$.get(url , function(name) {
alert(project_name); //this displays the name
$('#project_name').html(name);
});
The second parameter is just the return function, this is what will get called when your call to common_functions.php returns.
The nicest way to do it is as #jeroen has shown.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What to do with php after jquery .serialize()
I am serializing the following form using jQuery, sending it to the server using ajax and deserializing using PHP.
When I deserializing I get the error:
Error at offset 0 of 39 bytes
<form id="Marriage" style="display: none">
<input type="text" name="city" class="txtt" value="city"/>
<input type='button' value='Apply' id="msendsend" class="sendaf" name="jobforming"/>
</form>
Here is the jquery function to send this form
$(document).ready(function () {
$('#msendsend').click(function () {
var id=getParam('ID');
$.ajax({
type:'POST',
url:"send.php",
data:{option:'apply', sr:$("form").serialize()},
success:function (jd) {
}
});
});
});
This is the server code:
if($_REQUEST['option']=='catapply') {
$sc=$_POST['sr'];
mysql_query("insert into user_data(uid,data) values('$session->userid','$sc')");
}
And here I am unserializing .
$sql = mysql_query("SELECT * from user_data");
while ($row = mysql_fetch_array($sql)) {
$un = unserialize($row['data']);
$city=$un['city'];
echo $city;
}
The data in the database is shown as
to=&select_category=25&msg=&city=laho
jQuery's serialize function is way different from PHP's. It creates a query string, as you can see in your database.
This format may be decoded in PHP with the parse_str function. Use it instead of unserialize.
Instead of parsing it manually, though, you may be better off posting your form data as the query string:
data: $("form").serialize(),
You can add a hidden field to convey the option=apply value.
That way, you don't have to decode anything (it'll already be in $_POST) and you may insert every value in a separate row. It'll save you a lot of trouble in the future, e.g. when there's more data and you need to search through it.