PHP Page not getting data sent and not echoing - php

I have a simple setup that takes a hex value from a color picker converts it to RGB and then sends it to a PHP script from the HTML. The recieving file is not echoing and it is not refreshing either. I probably am doing something wrong but wanted to run it by someone just in case.
Java/Jquery
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
$(document).ready(function() {
var picker = $.farbtastic('#picker');
picker.linkTo(function onColorChange(color) {
var finalcolor=hexToRgb(color);
console.log(finalcolor,"helloworld");
$.post("imagedisplay.php", {var_value: finalcolor});
});
});
RECIEVING PHP
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$hex=$_POST['var_value'];
echo '$hex';
}
?>

When you use AJAX, the page is not refreshed automatically (that's generally the reason you use AJAX instead of normal form submission). You need a callback function in $.post to do something with the response from PHP:
$(document).ready(function() {
var picker = $.farbtastic('#picker');
picker.linkTo(function onColorChange(color) {
var finalcolor=hexToRgb(color);
console.log(finalcolor,"helloworld");
$.post("imagedisplay.php", {var_value: finalcolor}, function(response) {
alert('PHP said: ' + response);
});
});
});
In your PHP, $hex is an associative array. You can't echo an array, use:
print_r($hex);

Related

PHP file not picking up $POST parameter from JQuery

Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.

How to stop jQuery post page refresh

I am getting data from an MySQL database through PHP. I am sending the and getting the data from PHP using jQuery. Here is the code.
$.POST("SubmitCode.php", $("#questionCodeForm").serialize(),'json').done(function(data) {});
Now the problem is that once I send this data the page refreshes. How can I stop the page refresh. If I delete 'json' then the page stops refreshing but the problem is that I want to get the json data without page refresh. How can I do this?
-------------------------------------------after edit-----------------------------------------------------------------------------
Here is the updated code
$(document).ready(function() {
initialization();
codeSubmission();
});
function initialization() {
$("#answerForm").hide();
}
function codeSubmission() {
$("#submitButton").click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize()).done(function(data) {
var questionName = data.questionName,
options = data.options,
pollingStatus = data.pollingStatus,
codeExist = data.codeExist;
alert(data);
alert(data[1]);
alert(questionName);
alert(options);
if(codeExist == true) {
$("#questionTitle").text("questionName");
for(rowNum=1;rowNum<=5;rowNum++) {
$("#checkbox-"+rowNum).val("Answer1");
$("#checkbox"+rowNum+"label").text("Answer"+rowNum);
}
$("#answerForm").slideDown(500);
} else if(codeExist == false) {
alert("This quiz code is invalid");
}
},'json');
//return false;
});
//return false;
}
Now the problem is that the output of alert(questionName) is undefined. The data is passed as a string. How do I get the correct information in the correct variables?
Try this instead: (note the placement of the callback function, and lowercase .post method)
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
Also make sure that whatever is triggering the post isn't an actual link and if it is, you need to stop the default action from occuring. For example:
Click here to submit
javascript:
$(a).click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
});
You also have to parse the json on the client side. You can do this using
obj = jQuery.parseJSON(data);

javascript based Jquery ajax function, unable to send post values

Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29

Getting through the DOM from the file to which I did a post request through ajax

I used this simplify examples to explain better the question.
given the following post request under ajax:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$code = $("#code");
$.post("ajax.php", {option : $var, code: $code}, function()
{
//Getting through the DOM could be useful if you want to analyse the answer coming from the ajax.php file
var $DOMresponse = getElementByTagName("div")[0].firstChild.data; // I would want the correct code here because this is incorrect... this is ti give you an idea
if($DOMresponse == "your code is correct")
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
elseif($DOMresponse == "your code is incorrect. Go again trough the procedure")
{
$("#container2").fadeOut(400, function(){ $("#container2").html(result); });
$("#container2").fadeIn();
}
// In this second case I could fill the second container id="container2"
});
});
});
ajax.php example:
<?php
if($_POST['request']==1)
{
if($_POST['code']==$user['code'])
{
?><img src="...">
<div>tomatoes</div>
<div>potatoes</div>
<div id="answer">your code is correct</div> <?php
}
else
{
?><img src="...">
<div>apples</div>
<div>oranges</div>
<div>your code is incorrect. Go again trough the procedure</div> <?php
}
}
I would like to know how to get through the DOM of the ajax.php file.
how do I do this? Thanks
Do you need to do this before inserting the result to the page? If so create new element and insert the result to it. For example
var div = document.createElement('div');
var obj = $(div).html(response);
Now you have a standard jQuery object with the dom element.
Responding to the comment:
I am confused. Do you want to validate the code in php or js? It looks like your checking if what is send through post is the same as defined in $user variable. So validating the code is done in php. In that case wouldn't be simpler to use json as a response. In php script create result array with key status set to 1 or 0. In post resposne you can check response.status == 0.
Other wise it look just strange that you make the validation once in php and the twice in js after response. Besides if you set your response to be standard text then you have to create dom element and place the reponse inside to be able to search through it.
I think what you're asking is how do you get the value of $('#code') in the ajax.php file.
Here's what you're doing:
var $code = $('#code'); // jQuery object
$.post('ajax.php', { code: $code });
The problem with this is that you're passing the entire jQuery object to ajax.php. What you probably want to do is pass the value or html of the $('#code') object, like so:
var code = $('#code').html(); // if it's a non-input element
var code = $('#code').val(); // if it's an input
$.post('ajax.php', { code: code });
Then in the ajax.php file, your $_POST['code'] will equal the value of code (e.g. "ABC123"), which you can then use to compare with $user['code'] or whatever you want.
I hope I understand the problem correctly. Good luck.
EDIT: I think I understand what you're getting at now. What you want to do is this:
HTML:
Javascript:
var $option = 'request';
var $code = $('#code').val();
$.post('ajax.php', { option: $option, code: $code }, function(data) {
if (data == 'valid') {
// show valid code result here
} else {
// show invalid code result here
}
});
and ajax.php
<? if ($_POST['option'] == 'request') {
if ($_POST['code'] == '123ABC') {
echo 'valid';
} else {
echo 'invalid';
}
}
?>
Notice that the variable data comes from the function(data) part in the $.post parameter. That data variable contains the response from ajax.php (in my example, it would be 'valid'.)

How to call a specific function in a PHP script via Ajax?

Lets say I have a file called functions.php, and it has two separate functions inside:
One would get the time
And the other would get the date
How will I, using JQuery AJAX retrieve data from the function that retrieves the date. How do I specify in the JQuery code which function on the server to pick.
I hope I am making sense. Thanks.
You could include a selector in the ajax request data. For example:
$.ajax({
url: "functions.php",
data: "function=time", // or function=date if you want date
...
});
Then in your PHP code, a simple if-statement will check which one to output.
if(isset($_GET['function'])) {
if($_GET['function'] == 'time') {
// do time stuff
} elseif($_GET['function'] == 'date') {
// do date stuff
}
}
You don't specify in jQuery what function to execute in PHP. What you do is request a document, possibly with a query string, and read the results. Your functions.php script is responsible for executing whatever is requested.
So, you might from jQuery request functions.php?fn=time in one place and functions.php?fn=date in another. Then, in functions.php, you would examine the query string and execute the appropriate function for what was requested, returning the results to jQuery.
$(document).ready(function()
{
$(".link").click(function()
{
var data['func'] = "time";
var url = functions.php
$.get(url, data, function(result)
{
$("#feedback").html(result);
});
});
});
then your php file would be,
if(isset($_GET['func']))
{
if($_GET['func'] == "time")
{
showTime();
}
else
{
showDate();
}
}
function showTime()
{
//show time
}
function showDate()
{
//show date
}
Code is untested but should be a good starting point for you.
you can add a parameter to the url:
example:
function.php?g=1
now, on the serverside check for the get parameter:
if($_GET['g']==1)
{
echo date();
}
else
{
echo time();
}
What is the response your are getting. You are getting the response in XML or some other format. If your response is XML try with this option.
$.ajax({
url:path,
data:{projectId:inpprojectId},
dataType:"xml",
success:function(data){
$(data).find("CheckAmount").each(function(){
total = $(this).find("TotalAmount").text();
usdAmt = $(this).find("PettyCashAmount").text();
validateBudget(total,inp);
});
}
});

Categories