do not receive the POSTed data in php code ( cakephp) - javascript

I am trying to use ajax for retrieving data from my server. I use cakephp and jquery.
The ajax code is as follows:
<script>
$(document).ready(function(){
$(".viewMode").click(function(){
$.ajax({
type: "POST",
url:"viewModeSwitching",
data: {
mobileViewCookie:12,
},
success:function(result){
// window.location.href = result;
}
}
);
});
});
</script>
...
<?php
echo "<br>";
echo $this->Form->button(__('Desktop View'), array('type' => 'button','class' =>"viewMode",));
echo "<br>";
?>
This works well, in firebug I see that the POST is sent with value mobileViewCookie=12.
The point is that my cakephp controllerfunction 'viewModeSwitching' cannot retrieve that data.
I checked $this->data, $this->params, $_POST, etc but no sign of the data that had been send in the POST message.
Any suggestions?
/Antoine

Related

Print response from php scrip through ajax call

I want to call a remote php script and that php script will echo any string and then I want to alert that string back to ajax. but when I am alerting that string, I am getting this
Following is my ajax code:
$(document).ready(function(){
var response= $.ajax({
type:"POST",
dataType:'text',
url:"http://mySiteURL.com/evote.php?checkVote="+voterId+"&fingerPrint="+fingerPrint,
async:true,
success:function(result){alert(result);},
error: function(result){alert(result);}
});
});
and following is my php script code
<?php
if(isset($_POST['checkVote'])){
$voterId=$_POST['checkVote'];
$fingerPrint=$_POST['fingerPrint'];
echo "Output from php";
}
?>
before this I searched many questions on stack overflow but problem persisted.
Change the reponse into string : JSON.stringify(result)
var response= $.ajax(
{
type:"POST",
dataType:'html', // <-----
url:"http://mySiteURL.com/evote.php?checkVote="+voterId+"&fingerPrint="+fingerPrint ,
// async:true, // <--- no need
success:function(result){alert(JSON.stringify(result));},
error: function(result){alert(JSON.stringify(result));} })
For the PHP
<?php
if(isset($_GET['checkVote'])){
$voterId=$_GET['checkVote'];
$fingerPrint=$_GET['fingerPrint'];
echo "Output from php";
} else {
echo "No POST";
}
?>

Not sending data with AJAX to database

I have a problem with catching AJAX data with PHP and send it to the database. Site is on the WordPress platform.
I have checked for the errors with mysqli_error but there nothing happened. Console not showing any error, just show there is `console.log data from the ajax, so the ajax work.
Here is what I have tried so far.
AJAX:
$.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: {
'creditCardValue':creditCardValue,
'creditCardValueCvc':creditCardValueCvc,
'phoneNumberForm':phoneNumberForm
}
});
Here is a PHP code:
<?php
if (isset($_POST['button'])) { // button name from html
$creditCardValue = $_POST['creditCardValue'];
$creditCardValueCvc = $_POST['creditCardValueCvc'];
$phoneNumberForm = $_POST['phoneNumberForm'];
$query = "INSERT INTO validations(credit_card_number, credit_card_cvc, phone_number) ";
$query .= "VALUES ({$creditCardValue}, '{$creditCardValueCvc}', '{$phoneNumberForm}' ) ";
$create_post_query = mysqli_query($connection, $query);
}
?>
I need to send all these data to the database so I can later call them and displayed them.
Thanks in advance.
Remove the check for $_POST['button'] as this is not sent with the AJAX data. If you want to check if it's an AJAX call then just check that one of the values has been POSTed:
if (isset($_POST['creditCardValue'])) { ...

how to make submit button both send form thru' PHP -> MySQL and execute javascript?

I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

JQuery, Ajax submit with Mysqli validation

How can I submit a form dynamically where I run mysqli to check if an email exists. If it exists, echo an error ALL DYNAMICALLY.
I would like to run a jquery ajax submit but echo out php errors. I can submit but nothing will echo.
function DYNAMIC_CHECK(X)
{
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
});
}
X is the formdata. It all works, but the PHP echo will not show up nor will any vars that are created and echoed out throughout the page as errors.
if(isset($_POST['REGISTER']))
{
$COUNT = mysqli_num_rows(mysqli_query($CON, "SELECT * FROM USER WHERE EMAIL='$EMAIL'"));
if($COUNT == 1) { $EMAIL_ERROR='EMAIL ALREADY EXISTS'; }
}
echo $EMAIL_ERROR;
Is this possible to dynamically show $EMAIL_ERROR?
You can use the shorthand function jQuery.post() which sends the serialized data of the form and returns the result into a variable.
$.post( "test.php", $( this ).serialize(), function ( data ) {
...what to do with data (returns the result of test.php)...
});
You can modify your ajax function to display result from the request.
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
success: function(data) {
alert(data);
}
});
The echo of the request will be returned in the data variable in the success: function. Use the alert(data) to see what info is returned from the request.

How to send multiple data from PHP to JavaScript

I don't know how to make a script for sending multiple variables from external php to javascript (jQuery)
For exemple:
<?php
$test = "tets"; -->this, I want something this, no echo
$dock = "dock"; --
echo $test; -->no, I don't want echo in PHP script
echo $dock; -->no, I don't want echo in PHP script
?>
and JS
<script>
function(){
$.post("url", {Some_Thing: "Some_Thing"}, function (data) {
alert(data); --> no, I don't want echo in PHP script
alert($test); --> this, I want something this, no echo
alert($dock);
}
}
</script>
Use a data structure, e.g:
<?php
$data = array('test', 'dock');
echo json_encode($data);
Then in your JS
$.post('url', {...}, function (data) {
alert(data[0]);
}, 'json');
^^^^^^^^--- tell jquery you're expecting back some json
you can just output your data in JSON format and then load the data to JavaScript using ajax like so:
<?
$arrayWithData = array('data1' => 123, 'data2' => 555);
echo json_encode($arrayWithData);
then call load the data using ajax:
$.ajax({
'url' : 'php-data-script.php',
'method' : 'get',
'dataType' : 'json'
}).done(function(data) {
// do whatever you want with the data
console.log(data);
});

Categories

Resources