using jQuery/ajax for GET request - php

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.

Related

Jquery.ajax load data from html using php

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);
});
}

Pass an array by ajax to php page

I need to pass an array to a php page with AJAX. This array of input elements gets sent to the other page:
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith" size="117" >
This is how I prepare it for sending:
var txtCoursesNamewith = $.serialize($('#txtCoursesNamewith').val());
But I get this error when running the script:
TypeError: $.serialize is not a function
How can I send an array with AJAX?
I am facing same problem and, i am just using code like this.
but first of all please insert one hidden field and set textbox id like this:
<input type="hidden" name="txt_count" id="txt_count" value="3" />
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith1" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith2" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith3" size="117" >
<script type="text/javascript">
var txt_count= $('#txt_count').val();
for (i=1; i<=txt_count; i++){
queryString += "&txtCoursesNamewith%5B%5D=" + $('#txtCoursesNamewith'+i).val();
}
</script>
finally we can pass queryString variable to ajax, and you can print array.
<?php
echo "<pre>";
print_r($_GET); // or print_r($_POST);
?>
var textBoxes;
$('input[name="txtCoursesNamewith[]"]').each(function() {
textBoxes+=$(this).val()+"|||";
});
Now the textBoxes have all the values of text field with ||| separated and pass to php script and use explode() function to split each input value . may it helps u
You don't need to use .val() because .serialize() works on a the field itself, not on the value. (because it needs to get the name and the value from the field)
You can also call serialize() directly on a jQuery object, rather than using the jquery object as a parameter. Do it like this:
var txtCoursesNamewith = $('#txtCoursesNamewith').serialize();
Hope that helps.
Because $.serialize($('#txtCoursesNamewith').val()) is a string and not a jQuery object, it doesn't have the serialize function.
If you want to serialize the input (with its value), use $('#txtCoursesNamewith').serialize();
$.ajax({
type: 'POST',
url: your url,
data: $('#'+form_id).serialize(),
success: function(data) {
$('#debug').html(data);
}
});
Then in php
<?php
print_r($_POST);
?>

Jquery - How to get current input value from a repeating from

I have a comment system in which i want to add delete option, for this i have implemented a POST form in each comment which posts comment-id to delete.php, it is working in php, but not in jquery.
i.e in order to delete comment a comment id must be posted to delete.php file which handles deletion of comment from database.
i am trying to fetch that comment-id from input value to post with jquery like this but it gives me the first comment-id value not the selected value.
Jquery
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]").val();
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
repeating form is like this
<form name="comments" action="../../delete.php" method="post">
<input name="comment-delete" type="hidden" value="<?php echo $list['comment-id']; ?>" />
<input value="Delete" type="submit" />
</form>
if i use .each() or .map() it gives me all the comment-id values.
Please see and suggest any possible way to do this.
Thanks.
To find the relevant input, that is the one of the form you submit, you could use this :
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
BTW, I'm not totally sure of what you do but you might be missing a .val() to get the value of the input.
You have the same name on each hidden input, naturally you get all those inputs as you have not targeted the correct form when doing:
$("input[name=comment-delete]");
"this" whould point to the form inside your submit function. Try this.
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
As dystroy said, you are probably missing .val().
var commentId = $(this).find("input[name=comment-delete]").val();
try this
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]", this);
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
this refers to the form being submitted (more generally, to the event source).
$(...) accepts a second parameter, which is then used as a context for the selector. $(selector, context) is equivalent to $(context).find(selector)

Adding Table Cell Contents to PHP $_POST

From my understanding, the only way to retrieve $_POST data is using the name attribute of the element, like so:
<INPUT type="text" name="txt">
and the PHP portion:
<?php $text = $_POST["txt"]; ?>
I've got a table with cells containing plain text, for example:
<td class="textField" id="txt1"> Some text </td>
Is there anyway to post the text in these table cells and retrieve them using either the class or id? Maybe there is a clever way to get around this? <td> doesn't have a name attribute thus the reason for my question.
Thanks!
You can use ajax, getting values from the table with javascript. JQuery is a good library for this:
http://api.jquery.com/category/ajax/
$_POST and $_GET come from the request. Meaning the browser sends them with the headers and PHP provides an interface to them with $_POST, $_GET, $_COOKIE, and $_REQUEST. The browser doesn't send contents of a table in the request.
If you're trying to make a field 'read-only' you're going about it the wrong way. If a field is read-only you should never trust the browser to re-send that same value.
To retrieve values from many form-fields who all have the same name (because you generate them with a loop in PHP), append brackets to the names of your fields.
Simple example:
<form method="post">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
</form>
If you add to your code:
<?php print_r($_POST); ?>
you'll notice that the $_POST variable is populated with an array named "myfield" having 4 values from $_POST['myfield'][0] to $_POST['myfield'][3]. You may then use a foreach loop in PHP to retrieve all values.
The solution that ended up working for me was to grab the data using jQuery, encode it in JSON, and add it to a serial array of the rest of the form data.
$("#orderForm").submit(function(e) {
e.preventDefault();
// Get NON-INPUT table cell data
var subtotal = new Array();
$('#priceTable td.subtotal').each(function() {
subtotal.push($(this).html());
});
// Get all INPUT form data and organize as array
var formData = $(this).serializeArray();
// Encode with JSON
var subArray = JSON.stringify(subtotal);
// Add to formData array
formData.push({name: 'sub', value: subArray});
// Submit with AJAX
$.ajax({
url: "submitOrder.php",
data: formData,
type: 'post',
success: function(data) {
alert(data);
}
});
});
And on the PHP side:
$subtotals = json_decode($_POST['sub']);

Can I submit a predefined local variable as a POST w/out putting into a form field?

I have a local variable I'd like to be sent along with the rest of the POST data taken from an HTML form. Is there a function that lets me put more data from the current page into the POST array?
no function, simply add a hidden field with the value.
<input type='hidden' name='what_ever' value='<?php echo $my_var?>' />
If you need the value to remain totally hidden from the user, then use the SESSION to pass it's value between requests.
I am assuming that when you say "local data" you mean client side data. You could do this with some javascript.
function addFormData(key, name) {
var f = document.getElementById('myform');
var g = document.createElement('input');
g.setAttribute('name', key);
g.setAttribute('type', 'hidden');
g.value = name;
f.appendChild(g);
f.submit();
}

Categories