How to send "response" back to submitted Ajax form? - php

I am submitting a form using ajax. Then it is processed in PHP, and in the response i get the whole PHP/HTML code back. What is the right method to send back a "response" as variables from the PHP?
My JS
$.ajax({
url: 'index.php',
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});
and my PHP simply accepts the posted Input value and manipulates it:
if (isset($_POST["myInput"])) {
// doing something - and I want to send something back
}

Just echo and exit:
if (isset($_POST["myInput"]))
{
// doing something - and I want to send something back
exit('Success');
}
Then in your JS:
success: function(response) {
if (response == 'Success') {
// do something?
}
}
For example:
test.php single page html + php post handler
<?php
// Post Handler
if (count($_POST))
{
// do something with posted data
echo "You Posted: \r\n";
print_r($_POST);
exit();
}
// dummy data outside of the post handler, which will never be sent in response
echo "Test Page";
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.post('test.php', { "hello": "world" }, function(result) {
alert(result);
});
});
</script>
Outputs:

$.ajax({
url: 'index.php', // change your url or give conditional statement to print needed code
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});

Related

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

Receive Jquery/Ajax Post Request in PHP

I have Jquery/Ajax Code which sends Text Fields Data to PHP Script. But i don't know how i can receive that data and process for Validation.
Here is the Ajax Code:
$("#button").click(function (e) {
var dataa = $("#survay").serialize();
var data = $("#yourName ,#emailAdress , #phoneNumber , #zipCode").serialize();
$.ajax({
type: "POST",
url: 'processRequest.php',
data: dataa,
beforeSend : function(){
$('.eDis').empty().append('<div class="loader"><img src="images/32.gif" /> Loading...</div>').show();
},
success: function (html) {
if(html !='1') {
$('.eDis').empty().append(html).addClass("actEr");
setTimeout(function(){
$('.eDis').removeClass("actEr")}, 5000);
}
if(html == '1') {
$('.eDis').empty().append('<div class="success">Your Message has been sent</div>').addClass("actEr");
window.location ='../thank-you.html';
}
if(html =='0') { $('.eDis').empty().append('Error..').addClass("actEr"); setTimeout(function(){
$('.eDis').removeClass("actEr")}, 3000);
}}
});
});
processRequest.php should be PHP script which will handle all the texts fields data.
If above Text fields data is valid then i want it to Proceed further and redirect the page to thank-you.html
.eDis is CSS class, which i want to use to display valid,Invalid fields information.
It is in HTML.
Based on your information, I can't give you exact code, but, this is what you can do:
<?php
if(isset($_POST['itemName']) && isset($_POST['anotherItemName']) /* ...and so on */){
if($_POST['itemName'] == $validSomething)
echo 'WOW!';
}
else
echo 'error';
?>
What you are "echoing" is what you get in "success" data in your javascript.

Jquery AJAX - JSON or TEXT

I'm trying to retrieve the TEXT from the getsku javascript after submitting but not sure how to really do it.
1) How do i retrieve the POST data?
2) How do i retrieve and post it back , if i have multiple varaible to pass back (Datatype:text)
3) When should i use JSON, and when text.
4) If i'm using JSON how do i read it(after javascript) and display it(returned data to javascript).
javascript in main page
function getsku(){
$.ajax({
type: "POST",
url: "funcAjax.php",
data: { 'ddl1': $("#drop_1").val(), 'ddl2': $("#tier_two").val() },
dataType: 'text',
success: function(data) {
$("#sku").val(data);
},
complete: function() {
alert('Complete: Do something.');
},
error: function() {
alert('Error: Do something.');
}
});
}
Button
<input type="button" value="Get SKU" onclick="getsku();" >
Trying to retrieve from another php and return a data to the above php(Having Issues here)
if(isset($_REQUEST['ddl1'])) {
echo "FOUND1";
}else{
echo "FOUND2";
}
Always return JSON from your PHP. Then you can include as many variables as you need in your response, and an error code as well if appropriate - like this:
{"error":"0","result1":"result 1 data","result2":"result 2 data"}
Then your success function can become:
success: function(data) {
if (data.error != 0) {
// An error occurred on server: do something
} else {
$("#sku").val(data.result1);
// do something with data.result2
}
},
Your PHP would become something like this:
if(isset($_REQUEST['ddl1'])) {
echo json_encode(array("error"=>0, "result1"=>"FOUND1"));
}else{
json_encode(array("error"=>1, "result1"=>"NotFOUND"));
}

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

return php variable to jquery ajax

I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not
i have this :
echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';
<script type="text/javascript">
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
if(rmd==0)
alert("deleted");
else
alert("not empty");
window.location.reload(true);
}
});
}
</script>
and this
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
$rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>
my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?
thank you for your answers
PHP
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if (isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
?>
JS
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did}
}).done(function(rmd) {
if (rmd===0) {
alert("deleted");
}else{
alert("not empty");
window.location.reload(true);
}
});
}
i advice to use json or :
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
You need your php file to send something back, then you need the ajax call on the original page to behave based on the response.
php:
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo "{'rmd':$rmd}";
}
which will output one of two things: {"rmd": 0} or {"rmd": 1}
We can simulate this return on jsBin
Then use jquery to get the value and do something based on the response in our callback:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://jsbin.com/iwokag/3",
success: function(data){
alert('rmd = ' + data.rmd)
}
});
View the code, then watch it run.
Only I didn't send any data here, my example page always returns the same response.
Just try echoing $rmd in your ajax file, and then watching the console (try console.log(rmd) in your ajax response block)
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
console.log(rmd);
}
});
You can then act accordingly based on the response
Try echo the $rmd out in the php code, as an return to the ajax.
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
//if $rmd = 1 alert('directory not empty');
//if $rmd = 0 alert('directory deleted');
echo $rmd;
}
Your "rmd" in success: function(rmd) should receive the callabck.

Categories