I'm trying to update the user votes into database. This below ajax codes returns correct rating datas. But, I'm unable to get the alert data on another page. In my car_user_rating.php page I have tried this echo $post_rating = $_POST['performance_rating'];. But it doesn't get the performance_rating data value.
I have checked my console. It returns the rating values (4). I'm confused why it doesn't get the data value?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: "<?=CAR_USER_RATINGS?>",
data: { performance_rating: performance_rating },
success : function(data){
alert(performance_rating)
},
});
});
});
you should alert the data which you pass in success: function()
like
success : function(response){
alert(response);
},
use 'var' in submit handler, may it's because of scope:
var performance_rating = $('input:radio[name=rating]:checked').val();
I am not sure of your context so cant say exactly. Also i dont know if you are using exact same code as above or you have written teh above code in a hurry since there are mistakes there!!!
However Firstly try these
data: { "performance_rating": performance_rating },
url: "<?php=CAR_USER_RATINGS?>" //you have forgotten php
success : function(data, testStatus, xhr){
},
and check each values of data, testStatus, xhr
Also what is the value of
performace_Rating before $.ajax
"<?php=CAR_USER_RATINGS?>" before $.ajax
Just to summarize. I could figure out from your comment that your php is as below:
no. I have this codes on my php page inside the body tag
<?php echo $post_rating = $_POST['performance_rating'];
/*var_dump($get_rating); echo $sql = "UPDATE ".TBL_CAR_USER_RATINGS." SET performance = '$get_rating' WHERE model_id = '2'"; die(); mysql_query($sql, $CN) or die(mysql_error()); */ ?>
This is present inside the body tag!!! Well if you are using body tag i presume you are using other html, header(optional) tags as well
For a ajax response page the reply to client should "ONLY" be the value you want to send back.
Having tags will result in the the ajax response containing these tags as well.
So if you want your ajax page to return performance rating do the below:
//car_return_Rating.php
<?php echo $_POST['performance_rating']; ?>
If you have below code your response is shown below
//car_Return_rating.php
<html>
<body>
<?php echo $_POST['performance_rating']; ?>
</body>
</html>
then response i.e. data in success(data){}
will be equal to
data = "<html><body>4</body></html>"; //assuming 4 to be equal to $_POST['performance_rating'];
Related
I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps
If you wish to visit my webpage
Login details that can be used are
(case sensitive):
Username: stack
Password: stack
Click on yourhours tab.
My overall goal is to send all data from input boxes to a database. However currently I am just trying to get the interaction from the javascript and the PHP working. In the console I can see that the data variable has the value of "". I cannot see why this is happening.
PHP
<?php
$startTime = $_POST["startTime"];
echo $startTime;
?>
HTML
http://pastebin.com/7p9NiV44
Your javascript is working and is sending the value of the startDate input element to your sendHours.php. Your PHP-script is also correct.
By some reason your $_POST array isn't populated and it's not possible to come up with a solution based on your question alone. I would start by checking my php.ini, especially the setting post_max_size.
Also, you could try replacing your PHP-code with a simple <?php echo "Hello world"; ?> to verify that your setup is working to that extent at least.
not a solution but add the error section to get a better idea of what is going on.
function d(){
var startTime = document.getElementById("startTime").value;
console.log(startTime);
$.ajax({
type: "POST",
url: "sendHours.php",
data: {startTime: startTime},
success: function(data){
console.log(data);
},
error: function(err, status) { console.log(err);}
})
}
I have a small problem maybe because i am a beginner in ajax programming, i make a function in ajax jquery that calls a php file, which makes a request to the database for informations about a player. When the php file replies to the ajax function, i get an object with null values as an answer.
Is there a line i've missed in my code? or something i forgot to do?
Here is my code,
AJAX function:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
And the php file :
<?php
include("connexion_bdd.php");
$_GET['mail'] = $mail;
$req = $bdd->prepare('SELECT * FROM joueurs WHERE mail = ?');
$req->execute(array($mail));
$reponse = $req->fetch();
$return = array();
$return["user_name"] = $reponse["nickname"];
$return["profile_pic"] = $reponse["profile_pic"];
$return["user_id"] = $reponse["id"];
print(json_encode($return));
?>
In the success of the ajax function, i get this :
{"user_name":null,"profile_pic":null,"user_id":null}
Although the database is not null.
Where do you think is my mistake? php file or ajax function? or both?
Thanks for helping :)
Edit :
I've changed my code according to the remarks i had on the way i pass the variable AJAX->PHP.
I've tested my sql query on my database and it works fine, but i still have the problem of null values after i pass the object from my php file to the succes function of the AJAX/JS file.
Any ideas about what's wrong with my code?
Thanks again.
You have two problems here.
First, you are not sending the mail parameter in your jQuery AJAX request. You need to append the GET parameter to the end of the URL under the url key:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php?mail=youremail#gmail.com",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
The second problem is that you have your $mail variable assignment in your PHP script backwards. It should be
$mail = $_GET['mail'];
$_GET['mail'] is automatically set by PHP when you call the script with a GET request. But since you are referencing $mail in your prepared SQL statement, you want to assign the value of $_GET['mail'] to $mail.
This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
Im on project to make an app with codeigniter but i got stuck, when i want to pass same variable outside field via ajax into controller i got error the variable is not defined.
this is a example.
$("#form_status_update").submit(function() {
var date = new Date().toString();`
$.ajax({
type: 'POST',
url: "<?php echo base_url()?>socialcontroller/setdate",
data:date,
success: function(data) {
window.location.href = "<?php echo base_url()?>socialcontroller/ssetdate";
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
});
after passing some var i want to insert into my database.
and my question is how to pass a variable not field into controller via ajax thanks, i already search on google but i didnt geting the right answer :)
`
The line data:date, is wrong. You are passing up a number on the querystring and not a key/value pair.
It needs to be
data: {date : date},
or
data: "date=" + encodeURIComponent(date),
From jQuery Docs:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
Here is the code that help you with your problem
You can just adapt it with your code and it should work !
<script>
$(document).ready(function(){
$("button").click(function(){
var myDate = new Date();
$.ajax({
// Send with POST mean you must retrieve it in server side with POST
type: 'POST',
// change this to the url of your controller
url:"index.php",
// Set the data that you are submitting
data:({date:myDate}),
success:function(result){
// Change here with what you need to do with your data if you need of course
$("#div1").html(result);
}});
});
});
</script>
<body>
<div id="div1">
<p>Today date here</h2>
</div>
<button> Get Date< /button>
</body>
</html>
and your PHP code can be something like this !
<?php
// This line of code should get your data that you are sending
$data = $_POST['date'];
/// This code was just for checking purpose that it is returning the same value through ajax
$arr = array(
'receive_date'=>$data,
);
echo json_encode($arr);
I think this code can work with must of MVC framework if you are setting your controller URL as url parameter. Check also the Framework documentation about getting the data through POST !
your selector $("form_status_update") doesn't match a class or an id of the DOM.
and it doesn't match an html element either.
so this for sure gives you some (extra) problems.
couldnt you have tried running the date function at the php controller youre calling from the ajax function.
i dont see any specific reason as to why you have to send in date as the input parameter from the javascript function.
remove the date var and data field.
and in your php controller.
when you get the controller called.
run a date function in the php code and use the date from there.