how to get the php variable without submitting form through ajax - php

I am new to AJAX
I want to do something like
$query="select name from login_master where name=txtName.value();";
//txtName is a name of textbox.
But without submitting the form.
can i do this with ajax?

In AJAX you will make a call to whatever PHP page it is that contains this query. Your php page will carry out the query and echo out the results in a form your Javascript can understand, possibly either HTML or JSON.
In the success handler of your ajax call you can then handle the returned data.
Also on the server side be careful because anything input by the user can be potentially hazardous. Use prepared statements with mysqli or PDO.

Something like this should work:
<script type="text/javascript">
$(document).ready(function() {
$('#submit-btn').click(function() {
$.ajax({
type:'POST', //POST or GET depending if you want to use _GET or _POST in php
url:'your-page.php', //Effectively the form action, where it goes to.
data:$('#txtName').val(), //The data to send to the page (Also look up form serialise)
success:function(e) {
// On success this fill fire, depends on the return you will use in your page.
}
});
return false;
});
});
</script>
<form>
<input type="text" id="txtName" />
<input type="submit" id="submit-btn" value="Send" />
</form>
Then in your your-page.php or whatever you will call it you will pickup the $_POST['txtName'] and query your database.

Related

Insert into db and call AJAX for that data in one click

I've spent several days trying to find an answer for this problem. Although i've read numerous answers to similar questions, i'm having a hard time getting it to work in the context of my problem. I'm new to ajax so i'm hopefully missing a simple step here.
I'm trying to insert data into a table (php/MySQLi) and using ajax to retrieve that data in one click and displaying it on the page. Inserting and ajax both work fine, but the ajax call is always once step behind.
This is the php script for inserting a name + id:
if(isset($_POST['name'])) {
$name = get_post($con, 'name');
$query = "INSERT INTO testtable VALUES" . "('$name', 'NULL')";
$result = $con->query($query);
}
function get_post($con, $var) {
return $con->real_escape_string($_POST[$var]);
}
?>
So far so good, the data is inserted correctly. I'm outputting the data from the table in this script, which is response.php:
$query = "SELECT * FROM testtable";
$result = $con->query($query);
$rows = mysqli_num_rows($result);
for ($i = 0; $i < $rows; $i++) {
$fetch = mysqli_fetch_row($result);
echo <<<_END
<p>Name: $fetch[0]</p>
<p>ID: $fetch[1]</p>
_END;
}
This is the ajax script:
$(document).ready(function() {
$("#button").click(function() {
$.ajax({
url: "response.php",
success: function(result) {
$("#output").html(result);
}})
});
});
If it helps, here's the html:
<iframe name="frame" style="display: none"></iframe>
<form action="index.php" method="post" target="frame">
<input type="text" name="name">
<input type="submit" id="button" value="click" name="button">
</form>
<div id="output">Some output here</div>
I'm using an iframe as target to prevent the page from refreshing. I've found there are other ways to prevent the page from reloading but this seems to be working good.
Now, whenever I click the submit button, the data is inserted into the db, but there's no ajax output because I guess there's no data available because both the insert and the ajax call are fired at once. On the second submit, the first submit is shown etc. In this construction, Ajax is always lagging one step behind.
Whenever I click to insert I want to immediately output that new entry on the page. What am I missing?
Thanks.
I'm using an iframe as target to prevent the page from refreshing.
Let's not do that.
Inserting and ajax both work fine, but the ajax call is always once step behind.
I'm not sure how your code is working with AJAX since you never pass the data...
Solution
First, let's fix/minimize your HTML. We'll add an ID to your form to reference it after.
<form action="index.php" method="post" id="myform">
<input type="text" name="name">
<input type="submit" value="click">
</form>
<div id="output">Some output here</div>
Next, let's attach an onsubmit event handler to your form using jQuery.
$('#myform').submit(function (e) {
var form = $(this);
// proper way to prevent the form from submitting
e.preventDefault();
// send request WHILE passing the form's data
// we'll use $.post(url, data, callback) which is a shorthand method to $.ajax()
$.post('response.php', form.serialize(), function (res) {
$("#output").html(result);
});
});
Lastly, your two scripts need to be one in response.php if they are not... insert logic followed by retrieving logic.
For more information,
Shorthand methods
.serialize() method
.submit() method Read in particular their first example.
First of all, they are NOT "fired at once". That is just impossible by its nature - other then by total accident.
Although, right, it MAY happen that the INSERT transaction is not yet over as the DB engine receives SELECT request - for whatever reason.
So as the most usual suspect - check your autocommit mysqli property to be ON.
Or, alternatively, do a commit explicitly after INSERT.
Solution1->The simple solution is when you insert data using ajax file and while getting the response from the ajax. Send the data which you want to print in response and set them in a html as success : function(res){ jQuery('.all_data').html(res); }
This will be the more easy solution.
Solution2-> make another ajax call on success of insert complete ajax and fetch the data from table and set them in success

Post Javascript variable to PHP

I use Facebook JavaScript SDK.
I want to know how to post the Javascript variables to another page with GET or POST or any other way.
For example i have:
userInfo = document.getElementById('user-info');
How to post it to new page ?
location.href="http://www.walla.com/?info=" + info.id;
Not working
Better use ajax for this ..
here is an example.
<script type="text/javascript">
$(document).ready(function() {
$('#submit-btn').click(function() {
$.ajax({
type:'POST', //POST or GET depending if you want to use _GET or _POST in php
url:'your-page.php', //Effectively the form action, where it goes to.
data:$('#txtName').val(), //The data to send to the page (Also look up form serialise)
success:function(e) {
// On success this fill fire, depends on the return you will use in your page.
}
});
return false;
});
});
</script>
<form>
<input type="text" id="txtName" />
<input type="submit" id="submit-btn" value="Send" />
</form>
Hope it works for u.
That looks okay. You should be able to obtain info.id via $_GET['info'] from PHP.
However, that's assuming userInfo is a simple string.
If it isn't, you may have to convert it to string first. One way to do that is through JSON as JSON is decodable at PHP's side using json_decode().

jquery php insert data into mysql without refreshing the page

Hello I have the next code into my website:
<input type="text" id="name" name="name" width="25px"/>
Add User
I need that when I click "newUser" the value of the name is saved into my mysql database without refreshing the page.
Any exemple of how to do this?
If you don't want to use a <form> and a submit button which would be the absolutely correct way to do this, you will need to use javascript and AJAX:
Subscribe for the onclick event of the anchor
Send an AJAX request to the server passing the value of the name entered in the textbox
Cancel the default action of the link
Add User
and the insert function could be defined in a separate javascript file:
function insert() {
var name = document.getElementById('name').value;
// TODO: send an AJAX request to the server
return false;
}
http://api.jquery.com/jQuery.ajax/
$('#newUser').click(function(ev){
$.ajax(...);
ev.preventDefault();
});
This can be done on the client side with jquery's ajax libraries to create the refreshless submit.
Here's an example of some html and javascript
<html>
<head>
<script type="text/javascript" src="jq/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function adduser()
{
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "adduser.php",
data: data,
dataType: "html",
});
}
</script>
</head>
<body>
<form id="adduserform" name="adduserform">
<fieldset>
<input type="text" id="name" name="name" width="25px"/>
</fieldset>
</form>
Add User
</body>
</html>​
On the php side just code like you would if you were submitting a form via post.
I haven't had time to try it, but I hope it works :)
Like the others have suggested, look on the jquery site for more info.
You can do an Ajax call with JQuery that will send the name to the server. In your PHP code you will be able to create the Insert Query in your user table.
You can use JavaScript for that. Take a look at jQuery ajax: http://api.jquery.com/jQuery.ajax/
note: next time try googling, or at least provide what you have tried

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

$.post not POSTing anything

i am using the following jquery to post comments to user_submit.php
var submit = document.getElementById("submit_js");
var comment = document.getElementById("comment");
$("#submit").bind('click', function(){
$.post("user_submit.php", {
comment: $("#comment").text()
});
});
the user_submit.php listens like:
$comment = htmlspecialchars($_POST["comment"]);
i can see in the Firebug console that there is no POST happening. only a single GET that i use for a different function (can this be the culprit?)
Assuming:
<input type="text" id="comment">
<input type="button" id="submit_js">
you want:
$(function() {
$("#submit_js").click(function() {
$.post("user_submit.php", {
comment: $("#comment").val()
});
});
});
PHP:
<?php
$comment = $_POST['comment'];
//...
echo htmlspecialchars($comment); // nothing catches this currently
?>
You also seem to be confusing "submit" and "submit_js" in your code. I'd advise against mixing Javascript and jQuery code unnecessarily too (the "getElementById()" business). You should familiarize yourself with jQuery selectors. For example:
$("#submit_js")
will create a jQuery object with all the elements (which should only be zero or one elements) with the ID of submit_js.
Remember that you're posting via AJAX, so even if you're echoing back the field value, it won't show on your screen unless you're listening for it in the $.post callback.
To check what the problem may be, submit the form normally without jQuery. If your PHP script is echoing back the field value, then the PHP script is working - check your JavaScript. If the you're getting blank, or empty array when using print_r(), then make sure the field name in your form is the same as what you're using in the PHP script.
Don't want you to have to rewrite your code, but here's what I recommend to do.
<form class="comments" method="post" action="user_submit.php">
<input type="text" name="comment" />
<input type="submit" value="Submit" />
</form>
JavaScript:
$('.comments').submit(function() {
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data, status) {
console.log(data);
}
);
return false;
}
This will submit your form to the PHP script. In the callback function, "data" is the returned data from the PHP script. So if you echo the field value back, the Firebug console will display the value.
In the event the user's browser has JavaScript disabled, the form will still submit properly. Of course your PHP script would have to check if the form was submitted via AJAX so that it can process properly depending on the request method. An easy way to test is to check for the X-Requested-With header. If it was sent via AJAX, the value would be XMLHttpRequest.

Categories