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);
Related
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);
I have a problem with jQuery. I'm checking the password and username with the code above.
It's working but the issue here is how can I send the data from this HTML form to my PHP file, or how can I start a session here and transfer it to PHP?
$("#girisButon").click(function (giris) {
if ($("#kadi").val() == "" || $("#sifre").val() == "")
alert('Username or Password is empty');
else
$.post($("#login").attr("action"),
$("#login :input").serializeArray(),
function (data) {
if (data == "1") {
$("#mesaj").removeClass("mesaj").addClass("basarili").text("OK").fadeIn(300);
// window.location.replace("index.php");
} else {
$("#mesaj").removeClass("basarili").addClass("mesaj").text("WRONG").fadeIn(300);
$("#giris").effect("shake", {
times: 2
}, 300);
}
});
$("#login").submit(function () {
return false;
});
});
$("#login").submit(function () {
window.location = 'phpprocessingpage.php';
});
Then, in phpprocessingpage.php, use POST variables to access any <input> elements that were part of the #login form:
$_POST['input1']
I like to save POST variables to my own local variables in this manner:
$input1 = (isset($_POST['$input1'])) ? $_POST['$input1'] : '';
You can't start a session on javascript and transfer it to PHP. You need to call PHP file on background with necessary parameters and start the session.
According to your script, you are currently making a request to your PHP file using $.post method, which takes URL from #login's action attribute.
Simply edit the PHP file and create sessions. After that, echo 1 to browser so javascript can understand your response.
Finally, this is the block that runs if server returns 1
if (data == "1") { }
Do whatever you want here. Sessions should be created.
I am using the Jquery form plugin to submit a login form data. This works well but I have problem redirecting a successful logged in user to the client panel from the login page in my PHP script, that is whenever the user is logged in successfully, I redirect using header("location:panel.php") in my php script, this page is sent back to the login page as a response and it will be embedded in the login page instead of showing as a whole page.
jquery code;
$(document).ready(function(){
$("#loginform").ajaxForm({
target: '#responselogin'
}).submit();
});
php code;
<?php
$username=$_POST['username'];
$password=$_POST['password'];
if($username=="tarhe" && $password=="oweh") {
header("location:panel.php");
} else {
echo"login failed";
}
?>
Please I need help, thanks in advance
your using ajax, so your 301 location header will have no effect to the overall browser window. you will have to return a structured data to your javascript and have javascript redirect instead.
$(document).ready(function(){
$("#loginform").ajaxForm({
success: function (data) {
if (data == "login failed") {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
its actually better if you use json response for this. Since it's formatted better for browser consumption.
for handling this using json you can do the following. first change your php code to return a json response
$success = 0;
if($username=="tarhe" && $password=="oweh") {
$success = 1;
}
echo json_encode(array('success' => $success));
Then in your javascript code
$(document).ready(function(){
$("#loginform").ajaxForm({
type: 'json',
success: function (data) {
if (data.success == 0) {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
I don't think you can use the location flag inside the http header with ajax. Think about it: You submit a form with ajax, so you're getting the response back in Javascript, and not into the browser.
Bind a success handler to the .submit() form, and set window.location.href=http://your-url.com
You are using ajax so make a response data and on success redirect the user.
window.location.href = "somewhere.html";
I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick
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);
});
}
});