Post jQuery variable on same file and receive with PHP - javascript

How can I post jQuery data and receive on the same file without passing through the URL as a variable (eg. test.php?data=xxx).
For example here's the response.data that I can see in the console log.
function (response) {
console.log(response.data);
},
I want to post that data and receive on the same file. I have tried following:
function (response) {
//console.log(response.data);
$.post(window.location.href, {json_data: response.data});
},
but when in the body of same file I print
print_r($_POST);
it does not display anything.

Make sure that response.data is Type: PlainObject or String. See more here on PlainObjects
UPDATE
Here is a video that describes what this code sample does.
Code Sample
<?php
if (empty($_POST)) :
?>
Nothing was posted, please click there \/<br><br>
<?php
else :
echo 'You posted: '.print_r($_POST['json_data'], 1).'<br><br>';
endif;
?>
click here (simple string)<br>
click here (plain object)
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function fake_simple_response (response) {
console.log(response);
$.post(window.location.href, {json_data: response});
}
</script>

If you want to use POST, one way is to create a form and submit it with jQuery.
<form id="form-id" method="post" action="">
<input type="hidden" value="hello world" />
</form>
<script>
$('#form-id').submit();
</script>

Related

Trying to send js variables to a php file

I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null.
My goal is to send the data to finalmap.php and redirect to it.
To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work.
<button type="button" id="submit-button">FINISH</button>
Note, no <form> is needed; you're submitting through AJAX.
Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
You use your web console to see the console.log message.
Now, try out the ajax command with a simple post:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
finalmap.php
<?php echo 'This is finalmap.php';
If you see This is finalmap.php in the web console after pressing the button, then you can try sending data.
finalmap.php
<?php
echo 'You sent the following data: ';
print_r($_POST);
See where we're going with this? The way to eat an elephant is one bite at a time.
./finalmap.php is not a thing.
Instead the code must look like this:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
Try using this instead.
EDIT: OOPS SORRY, I JUST CPED AND PASTED.

Passing variable from PHP onto Javascript with JSON

I'm trying to pass a string from PHP onto a javascript file using the $.getJSON function but it keeps alerting 'getJSON request failed'. So far, I've tried using the $.ajax with and without async: true and the regular $.get jQuery functions but I get the same problem. I've also tried including the
$( document ).ready() function.
The enterComment function is executed upon sending a form in the php file 'pannkakor.php'. Just to be clear, the enterComment function does execute when clicking the button but the $.getJSON function fails.
Also worth noting is that I am using the knockout.js framework.
What am I doing wrong?
PHP CODE SNIPPET:
<?php
$username = "test";
$array = array('username' => $username);
echo json_encode($array);
?>
Javascript code:
this.enterComment = function (comment) {
$.getJSON("localhost:8888/Sem4/recept/pannkakor.php", function (jsonData) {
alert("TESTING THAT IT WORKS");
})
.done(function () {
alert('getJSON request succeeded!');
})
.fail(function () {
alert('getJSON request failed');
});
};
HTML/PHP FOR THE FORM SUBMITTED:
<form data-bind="submit: enterComment.bind($data,$data.comment )">
<input type="text" data-bind="value: $data.comment"/>
<button type="submit">Submit Comment</button>
</form>

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 :-)

Why this ajax call is not working?

$(document).ready(function(){
$('.clickthetext').click(function(){
$.post("submit.php", $("#formbox").serialize(), function(response) {
$('#content').html(response);
});
return false;
});
});
My target to pass content from the form and edit the data and show response at current page.
.clickthetext button content:
<div class="clickthetext">Click here to see the result</div>
content inside id #formbox:
Part of the form inside this id. rest of the form is out side this id will be processed later. only content/input inside of id "formbox" will be processed.
Whatever response we will get, we will show inside of "#content" id.
What i am doing wrong here?
----edit----
i didn't add anything on submit.php
only to show response, i wrote there:
<?php
echo 'somthing blah blah blah something';
?>
Maybe there is a problem with the result of submit.php
You can try calling
$(document).ready(function(){
$('.clickthetext').click(function(){
$.ajax({
type: "POST",
url: "submit.php",
data: $("#formbox").serialize(),
success: function(response) { $('#content').html(response); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); },
dataType: dataType
});
return false;
});
});
instead and get more detail of the result of the ajax call.
Here's the API for the ajax object in jQuery
Recreating your set up,
JS/HTML
<form action="" id="formbox">
<input type="text" name="firstName" value="First Name">
</form>
<button class="clickthetext">Button</button>
<div id="content"></div>
<script>
jQuery(document).ready(function ($) {
$('.clickthetext').click(function() {
$.post("submit.php", $("#formbox").serialize(), function (response) {
$('#content').html(response);
})
})
});
</script>
PHP: submit.php
<?php echo 'this is the response'; ?>
Everything works perfectly.
Debugging tips:
1) Most likely - Check your javascript console for any errors. You probably have errors elsewhere in the page.
2) Ensure you're accessing the HTML page with the javascript via localhost, not a filepath
3) Unlikely, but check your PHP log.

Categories