Having problems figuring out AJAX POST functions - javascript

I am trying to post using AJAX because I don't want to use a submit button and reload the page everytime I click it.
I am using this code for ajax:
<script language="JavaScript"><!--
function postit()
{
var frm = $('#pmconfirm');
$.ajax({
type: "POST",
url: "bitcin",
data: frm.serialize(),
success: function(msg){
$("#main").hide();
$("#main").html(msg).show();
},
error: function(msg){
$("#main").html("<font color='#ff0000'>Ajax loading error, please try again.</font>").show();
}
});
}
setTimeout("postit()",2000);
//--></script>
Next, I am using this form:
<form action="" name="fcaptcha" method="post">
<input type="hidden" id="bitcoin" name="bitcoin">
<input type="hidden" id="pmconfirm" name="pmconfirm" src="http://www.mvixusa.com/newsletter/2010/11/newsletter-membership-confirmation/images/confirm-button.png" alt="Submit Form" onclick=\"document.getElementById("fcaptcha").submit()\"/>
</form>
<div id="main">
</div>
This works it posts but I doesn't give me results ?
if (isset($_POST['bitcoin']))
{
// My code here works, because it works when i dont use ajax
// And I have some things to check like if it wasnt what i wanted
// it returns some message which is shown with php.
}
<div id="messaget">
<?php
if($failed == 1) echo $messages;
?>
</div>
This is the part where the messages should be displayed, I tried using a tag #messaget to display the HTML after post but it didn't work, I tried displaying the entire page in this page it still didn't work.
And the url: "bitcin", is entirely ok, i used htaccess.
Can somebody spot where the problem is ?

Add an id to the form :
<form id="pmform" action="" name="fcaptcha" method="post">
And change Js to:
var frm = $('#pmform');
When performing:
............
data: frm.serialize(), //this will take the form and make an array based on the names of the form elements thus having them accessible in the PHP script
..........

Related

Post on native php (without framework) Into Code Igniter using AJAX

I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

image button - no page change

I'm trying to call a php file without refreshing the page. The code executes the php file, but the value toid is not being passed along. If i manually query the page then it works fine. The other issue im having is the button needs to be an image with the path src="{ROOT_PATH}mchat/quote.gif"
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo {mchatrow.MCHAT_USERNAME}; ?>">
<div id="button_block">
<input type="submit" id="button" value="Enter">
</div>
</form>
<script>
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
$.ajax({
type: "POST",
url: "randomquote.php",
data: "toid=" + toid,
});
});
});
</script>
Any ideas?
When you say "if i manually query the page then it works fine", does that mean hitting the endpoint directly like
http://yoursite.com/randomquote.php?toid=239439
Have you tried sending the data as an object (like this):
$.ajax({
type: "POST",
url: "randomquote.php",
data: { toid: toid }
});
That may do the trick.

Getting data from form.serializaArray()

i need help..why does my code not working?what is the proper way to get the data from a form.serialize? mines not working.. also am doing it right when passing it to php? also my php code looks awful and does not look like a good oop
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="" id="title_val"/>
post topic
</form>
<div id="test">
</div>
Javascript
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'get',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
Php
<?php
class test{
public function test2($val){
return $val;
}
}
$test = new test();
echo $test->test2($_POST['title_val']);
?>
OUTPUT
You're telling your ajax call to send the variables as GET variables, then trying to access them with the $_POST hyperglobal. Change GET to POST:
type:'post',
Also, it should be noted that you are binding your ajax call to the click on your submit button, so your form will still be posting. You should bind on the form's submit function instead and use preventDefault to prevent the form posting.
$('#frm').submit(function(e) {
e.preventDefault(); // stop form processing normally
$.ajax({
url: 'topic.php',
type: 'post',
data: $(this).serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});

PHP Ajax button press conundrum

I have been trying to have a button execute a PHP script on a page and refresh just a div tag without any success. When I remove the $ajax part of the script my buttons change state but when I add the ajax part again nothing happens.
I need to load some content from a PHP file and then change the button's and div tags state. Some help will be very much appreciated as I can't seem to find the problem.
<div id="noah-content">
<script>
$(document).ready(function() {
$("#ON'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = true;
document.getElementById("OFF'.$id.'").disabled = false;
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src");
}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
$("#OFF'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = false;
document.getElementById("OFF'.$id.'").disabled = true;
});
});
</script>
<img src="images/about.png" alt="image" id="myimg" />
<input type="submit" class="ON" id = "ON'.$id.'" value=" ON " name="submit"/>
<input type="submit" class="OFF" id = "OFF'.$id.'" value=" OFF " name="submit" disabled="disable"/>
</div>
Lets start with evaluating your php:
In order to run your php you have to open php tags:
$("#ON<?php echo $id ?>")...
Replace it everywhere you want your id to appear. For debugging, open your page source in the browser and see what is being generated:
Example:
<input type="submit" class="ON" id="ON<?php echo $id ?>" value="ON" name="submit"/>
Firstly, your ids for your html tags, and the way you reference them in js, seem odd (though still perhaps valid when dropped into js or html as strings). Looks like your trying to reference a php value in an improper way in html and js.
Second, are you getting any errors on your javascript console? Does the ajax query complete (i.e. do you get the alert message)? Check your JS console because that will tell you something more than 'nothing happens'
Also
I usually use the success option for ajax rather than the done method. Personal choice.
You also have a syntax error after $(this).attr("src");. The semicolon indicates the end of a line of code usually, and you put it after an element in your array/object declaration for your data.
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src") //Removed the semicolon that was here
},
success: function(data){alert(msg)}
});

Categories