Receive Jquery/Ajax Post Request in PHP - 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.

Related

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

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
}
}
});

jquery ajax get and post to php

I am trying to send data to php file and I am using post and get to receive data base on if it is post or get.
The problem is that get is working and I click to receive data through post i do not receive anything.
php code process stops when it gets to GET then I send I POST and it does not respond to it. I can see ajax sends the data but php does not receive it when GET is working in php file.
php code:
if($_POST['id']){ show data}elseif{$_GET['id']{ get data}
jquery ajax:
// Youtube videos:
$(function() {
$('.image').click(function() {
var id = $(this).attr('id');
var msgbox = $("#video_status");
if(id.length > 5) {
$("#Video_status").html('<img src="assets/imgs/loading.gif" alt="loading ... " />');
$.ajax({
type: "POST",
url: "my_video.php",
data: 'id='+ id ,
cache: false,
success: function(msg){
$('#Video_status').html(msg);
if(msg ) {
msgbox.html(msg);
}else{
msgbox.html(msg);
}
}
});
}
return false;
});// End of youtube videos.
$(function() {
var loader = $("#Video_status").html('<img src="assets/imgs/loading.gif" alt=" loading ... " />');
var VideoWrap = $('#VideoWrap');
loader.fadeOut(1000);
$.get('my_video.php', '', function(data, status){
VideoWrap.fadeOut(1000);
VideoWrap.html(data);
VideoWrap.fadeIn();
});
return false;
});
});// get youtube video.
first check using isset
if(isset($_POST['id']))
{
//to show data echo/print something
echo $_POST['id'];
}
elseif(isset($_GET['id']))
{
//get data
}
try this
if($this->getRequest()->isPost()) {
}
if($this->getRequest()->isGet()) {
}
Why not something like this?
$postOrGetVar= $_GET['paramname'] ? $_GET['paramname'] : ($_POST['paramname'] ? $_POST['paramname'] : 'Param not sent via Post nor Get');
Simple, readable and easy.

How to make PHP action in AJAX

I created a PHP page that Insert into the database the value in the textbox, when someone click on the button it's redirect to the php page, But I want it to make the PHP action without redirecting, So how can I do it in ajax?
Thank you
woz and dragoste are right. Use jQuery to make it happen. you can use this function, it will fit to your requirement.
Here i used jQuery validation library http://jqueryvalidation.org/ to validate the form .
$(function()
{
var form = $("#booking_form").validate();
$('#success').hide();
$('#failure').hide();
$("form#your_form").submit(function() {
if(form.valid())
{
var name = $("#txtName").val();
var email = $("#txtEmail").val();
var phone = $("#txtPhone").val();
$.ajax({
url: "process_form.php",
type: "POST",
data: {
'name': name,
'email': email,
'phone': phone
},
dataType: "json",
success: function(data) {
if(data.status == 'success')
{
$('#your_form').hide();
$('#success').show();
}
else if(data.status == 'error')
{
$('#failure').show();
}
}
});
return false;
}
});
});

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"));
}

Submitting form via ajax in jquery

i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)
You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)
I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}
Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.

Categories