Using jQuery's .get() to retrieve PHP data - php

I'm using jQuery's .ajax() to post to a PHP file called process.php. Process.php has a lot of code in it, but for simplicity's sake, let's just say it contains <?php echo 'hello'; ?>.
Is this the proper jQuery to insert process.php's results into div.results? :
$.get('process.php', function(data) {
$('.results').html(data);
});
So far it doesn't seem to be working.
Here's the HTML/Javascript file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#form").submit(function() {
var username = $('#username').attr('value');
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
return false;
});
});
</script>
</head>
<body id="body">
<form id="form" method="post">
<p>Your username: <input type="text" value="" name="username" id="username" /></p>
<input type="submit" id="submit" value="Submit" />
</form>
<div class="results"></div>
</body>
</html>
Here's process.php (greatly simplified):
<?php
/* get info from ajax post */
$username = htmlspecialchars(trim($_POST['username']));
echo $username;
?>

If you simply want to place the resulting string back into an element, use load().
$('.results').load('process.php');
However, looking at your code...
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
...shows you have misunderstood something. The correct anonymous function to assign to the success callback would be...
function(data) {
$('form#form').hide()
$('.results').html(data);
}

You could try something like this.
function ajax_login() {
if ($("#username").val()) {
$.post("/process.php", { username : $("#username").val() }, function(data) {
if (data.length) {
$("#login_form").hide();
$("#login_result").html(data);
}
})
} else {
$("#login_result").hide();
}
Then in process.php just echo out some text if the post sucesses.
process.php =>
if (isset($_POST['username'])
{
echo 'hello '.$_POST['username'];
}

Related

cannot get value from php ajax

Cannot get value from php true AJAX.
My php code is
<?php
$name = $_POST['name'];
$hobby = $_POST['hobby'];
if (!empty($name and $hobby)){
echo 'Data was succesfully captured';
}else {
echo 'Data was not captured'
}
my html code is
<div id="result"></div>
<form method="post">
<input name="name" type="text" id="name">
<br>
<input name="hobby" type="text" id="hobby">
<input name="snd_btn" type="button" id="snd_btn" value="Save">
</form>
JS
$(document).ready(function(){
$('#snd_btn').click(function() {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
url: "save.php",
type: "POST",
dataType: 'json',
data: { name, hobby,
success: function(result) {
$('#result').html(result);
},
}
});
});
});
if i Change in js to
success: function() {
$('#result').html('Data was succesfully captured');
},
it work but not from php
This one is wrong.
if (!empty($name and $hobby)) {
Please replace that with:
if (!empty($name) and !empty($hobby)) {
You have to check for emptiness of the variable for each one.
Problems:
After hobby comes a "}" before ",".
Then, you have an error-prone additional "}". The one after the closing "}," (btw, delete the ",") of success callback.
You forgot the semicolon at the end of the line echo 'Data was not captured'.
The ajax call expects a JSON encoded response, as you defined dataType: JSON. So, in PHP, you must encode the response string - with json_encode.
Since you don't have an error callback (error: function(...){...}) you can't see any errors. So, define one. An example is below.
Recommendations:
Define the data object as below.
The PHP check on empty values should happen as below.
You must also check if the posted values are set.
Don't show any specific error details to the users. Just display a general user-friendly message to them. So, don't do as I did - by printing the error details in the console :-)
index.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#snd_btn').click(function () {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
method: 'POST',
dataType: 'json',
url: 'save.php',
data: {
'name': name,
'hobby': hobby
},
success: function (result, textStatus, jqXHR) {
$('#result').html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error! See the console');
console.log(textStatus);
console.log(errorThrown);
console.log(jqXHR);
},
complete: function (jqXHR, textStatus) {
//...
}
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form method="post">
<input name="name" type="text" id="name">
<br>
<input name="hobby" type="text" id="hobby">
<input name="snd_btn" type="button" id="snd_btn" value="Save">
</form>
</body>
</html>
save.php:
<?php
/*
* Check if the values are set.
* I used here the short "null coalescing operator".
* Search for it in the link below.
*
* #link https://secure.php.net/manual/en/language.operators.comparison.php Comparison Operators.
*/
$name = $_POST['name'] ?? '';
$hobby = $_POST['hobby'] ?? '';
if (!empty($name) && !empty($hobby)) {
$response = 'Data was succesfully captured';
} else {
$response = 'Data was not captured';
}
echo json_encode($response);
First of all you have check that the ajax call will be successfully done or not
If ajax call was successfully done then,
Check the response of success data by print the in console.
Your php code should be like this
<?php
$name = $_POST['name'];
$hobby = $_POST['hobby'];
if ($name and $hobby ){
echo json_encode('Data was succesfully captured');
}else {
echo json_encode('Data was not captured');
}
From php you have to return data in form of json.
And js side:
$(document).ready(function(){
$('#snd_btn').click(function() {
var name = $('#name').val();
var hobby = $('#hobby').val();
$.ajax({
url: "save.php",
type: "POST",
dataType: 'json',
data: { name:name, hobby:hobby} // data in { key : value}
success: function(result) {
res = JSON.parse(res);
console.log(res);// display in developertools > console
$('#result').html(res);
},
}); }); });

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

Post data with ajax or ajax(json) to php in same page

I'm trying message application. My goal is get sender id and receiver id with a click on one button.
After then post this datas with ajax or ajax(json) to php in same page.
I will use the incoming data in php with mysql_query. I tryed many examples. But never get result. My example code at below.
Little Note: Success alert comes but doesn't print any data on screen.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
success: function(data)
{
alert("success");
}
});
};
</script>
<?php
if(isset($_POST['name']))
{
$value = $_POST['name'];
echo $value;
}
else
{
echo "don't work.";
}
?>
</body>
</html>
<?php
if(isset($_POST['name']))
{
echo json_encode(array(
'value' => $_POST['name']
));
exit();
}
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
dataType : 'json',
success: function(data)
{
alert("success");
}
});
};
</script>
</body>
</html>

Echo $_POST with $.ajax in PHP

I'm trying to echo $_POST with $.ajax in PHP with no success. In Xdebug I see the $_POST get the right value and executing the echo $_POST line, but I keep getting the else output clause. Also in chrome I see the headers that are sent valid. All the code is in the same page index.php.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<button type="button" id="but">Click Me!</button>
<script>
$('#but').click(function() {
$.ajax({
type: "POST",
url: "index.php",
data: {name: "John"},
success: function() {
alert('success');
}
});
});
</script>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
} else {
echo "Nothing to Show";
}
?>
At the moment the whole page is being returned in response to your AJAX request; HTML and all. You're also not retrieving the value returned from the request in your JS code, to do that you just need to accept a parameter on your success handler. Try this:
In it's own file, say foo.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
} else {
echo "Nothing to Show";
}
?>
Then in your HTML:
<script>
$('#but').click(function() {
$.ajax({
type: "POST",
dataType: 'text', // to ensure jQuery doesn't try to deserialise the repsonse
url: "foo.php",
data: { name: "John" },
success: function(response) {
console.log(response.trim()); // = 'John'
}
});
});
</script>
Ajax will return a response and you can use that response to display. It will not work on the same page.
Try as below :
main.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<button type="button" id="but">Click Me!</button>
<div id="result"></div>
<script>
$('#but').click(function() {
$.ajax({
type: "POST",
url: "test.php",
data: {name: "John"},
success: function(data) {
alert('success');
$('#result').html(data);
}
});
});
</script>
</body>
</html>
test.php
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
} else {
echo "Nothing to Show";
}
?>

Pass javascript variable to php with ajax and the result doesn't show anything

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

Categories