I am trying to get values from form with serialize function and I correctly post and save to database but after this step my codes don't work . Someone help please ?
$(document).ready(function() {
$("#kform").submit(function() {
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "yenikayit2.php",
data: data,
dataType: "json",
success: function(data) {
if (data.tip === "dosya") {
alert("tralalala d");
}
if (data.tip === "tercume") {
alert("tralalala t");
}
if (data.tip === "hata") {
alert("tralalala hata");
}
}
});
});
PHP Code
<?php
if($musteri_ekle) { //mysql control function
$musteri_id=mysqli_insert_id($baglanti);
$_SESSION[ 'musteri_id']=$musteri_id;
if ($secilen=="dosya" )
{ echo json_encode(array( "tip"=>"dosya")); }
else if ($secilen == "tercume")
{ echo json_encode(array("tip"=>"tercume")); } }
else { echo json_encode(array("tip"=>"hata")); } ?>
Modify yenikayit2.php to avoid PHP fatal error and notices. You can either use error_reporting(null);
or edit the code as below
if (isset($musteri_ekle)) { // to avoid undefined variable error
$musteri_id = mysqli_insert_id($baglanti);
$_SESSION['musteri_id'] = $musteri_id;
if ($secilen == "dosya") {
echo json_encode(array("tip" => "dosya"));
} else if ($secilen == "tercume") {
echo json_encode(array("tip" => "tercume"));
}
} else {
echo json_encode(array("tip" => "hata"));
}
Well, i realized that i forgot put this fields on form action="" and method=""
after this i changed my jquery code :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
$("#kayit").click(function(event) { var data=$("#kform").serialize(); }
And this works correctly
Related
I'm trying to call some php code using ajax:
$(document).ready(function() {
$("#email_address").on("keypress", function() {
request = $.ajax({
url: '../verify_email.php',
data: {email: $("#email_address").val(),
submitted: true},
type: 'post'
});
request.done(function(response) {
//fooling around to see if this works
if(response) {
alert("valid email");
} else {
alert("invalid email");
}
});
request.error(function(response) {
alert("an error occurred");
});
});
});
However, the request.error function runs. I'm not too sure why. Here is the php code:
<?php
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo 'true';
} else {
echo 'false';
}
}
?>
Thanks in advance.
ugh, noob mistake. i had set the php url to be relative to the .js file instead of to the web page. it was supposed to be:
request = $.ajax({
url: 'verify_email.php'
instead of
request = $.ajax({
url: '../verify_email.php',
i figured it out with the use of Chrome's web inspector . i learned two new things today: what the url has to be relative to and how to use Chrome's web inspector. thanks all for your help
If your url work fine, in php try to return json ;)
<?php
$return = false;
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$return = true;
} else {
$return = false;
}
}
header('Content-Type: application/json');
echo json_encode(array('result' => $return));
die;
?>
And in javascript try:
request.done(function(response) {
//fooling around to see if this works
if(response.result) {
alert("valid email");
} else {
alert("invalid email");
}
});
I am building an inline code validation for a web form. With my current script, When a bad code is entered and it is being corrected (same length), POST data is not using the latest value. For example, I first enter "QFFE" and then correct it to "QFFF", but the latter is not stored in $_POST. See Firebug extract ("QFFF" passed but "QFFE" processed):
Here is the code (AJAX part):
var data = {};
$(document).ready(function() {
$('input[type="submit"]').on('click', function() {
resetErrors();
var url = 'process.php';
$.each($('form input, form select'), function(i, v) {
if (v.type !== 'submit') {
data[v.name] = v.value;
}
}); //end each
console.log(data);
$.ajax({
dataType: 'json',
type: 'POST',
url: url,
data: data,
cache: false,
success: function(resp) {
if (resp === true) {
//successful validation
alert("OK, processing with workflow...");
// $('form').submit();
return false;
} else {
$.each(resp, function(i, v) {
console.log(i + " => " + v); // view in console for error messages
var msg = '<label class="error" for="'+i+'">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(resp);
$('input[name="'+keys[0]+'"]').focus();
console.log('QD: error val');
}
return false;
},
error: function() {
console.log('there was a problem checking the fields');
}
});
return false;
});
});
function resetErrors() {
$('form input, form select').removeClass('inputTxtError');
$('label.error').remove();
}
And here my PHP script (process.php):
<?php
//List of accepted codes
$code_list = array("QWOLVE", "QFFF");
session_start();
if(isset($_POST)){
if (empty($_POST['promo_code'])) {
$_SESSION['errors']['promo_code'] = 'Please enter a promo code to access the beta site';
}elseif(! in_array($_POST['promo_code'], $code_list)){
$_SESSION['errors']['promo_code'] = $_POST['promo_code']." is not a valid code";
unset($_POST);
}
if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
// header('Location: redirect.php');
exit;
}
//This is when Javascript is turned off:
echo "<ul>";
foreach($_SESSION['errors'] as $key => $value){
echo "<li>" . $value . "</li>";
}
echo "</ul>";exit;
}else{
//Form validation successful - process data here:
echo json_encode(true);
}
}
?>
How can I make sure that the process.php is always using the latest form data?
I'm not sure why you store errors in the the session, but since you don't seem to clear that session, the next time you call the POST method $_SESSION['errors'] will still have the previous error in it (QFFE), hence the output.
I'm trying to make a login page that validates the users input data. If "username" and "password" does not match in the database he would receive a warning.
I'm a total newbie when it comes to this, so the code I have now is a combination of different tutorials.
my signin.php looks like this:
header('Content-Type: application/json')
$data = array(); // array to pass back data
if(!empty($_POST["action"]))
{
if($_POST["action"] == "signin")
{
...all the SQL code here...
if(!empty($result))
{
foreach ($result as $row)
{
...some SQL code here...
$data["success"] = true;
$data["message"] = "Success!";
}
}
else
{
$data["success"] = false;
$data["message"] = "Error!";
}
echo json_encode($data);
}
}
Now I want this json data to be used in a jquery submit function that uses ajax to get the data from signin.php:
<script>
$("#login-form").submit(function(event) {
$.ajax({
type : 'POST',
url : 'signin.php',
data : { 'action': 'signin' },
dataType : 'json'
}).done(function(data) {
console.log(data.success);
if(!data.success)
{
alert("ERROR");
}
else if (data.success)
{
alert("SUCCESS");
}
});
event.preventDefault();
});
</script>
Trying to get jQuery to send the content of a textarea to update a record but it won't. When I change the value of the textarea so that it begins with a number then it sends fine. I can verify that the content is handed to the JS function successfully by using alert(), but it won't get to the PHP file. All other JS functions work fine.
Edited to add more code which may be relevant.
Javascript:
<script>
function add_vid(t) {
if ($('#vref').val().length <5) return;
var vref = $('#vref').val();
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'add_vid', 't':'<?=$_SESSION['t']?>', 'vref':vref},
beforeSend:function(){
$('#add_vid_status').html('Adding...');
},
success:function(data){
if (data == 'added') {
$('#add_vid_status').html('Added');
$('#vid_list').prepend('<div align="center" class="vid">'+vref+'</div>');
$('#vref').val('');
}
else $('#add_vid_status').html('Error');
},
error:function(){
$('#add_vid_status').html('Error');
}
});
}
function del_vid(id) {
var confirmdel = confirm('Delete ?');
if (confirmdel) {
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'del_vid', 't':'<?=$_SESSION['t']?>', 'id':id},
success:function(data){
if (data == 'deleted') {
$("#v"+id).hide(900);
}
},
error:function(){
//$("#"+msg_id+'_a').html('error');
}
});
}
return false;
}
function update_vid(id) {
vref = $("#update"+id).val();
alert(vref);
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'update_vid', 't':'<?=$_SESSION['t']?>', 'id':id, 'vref':vref},
success:function(data){
alert(data);
if (data == 'updated') {
$("#if"+id).html(vref);
}
},
error:function(){
//$("#"+msg_id+'_a').html('error');
}
});
return false;
}
function move_vid(id,dir) {
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'move_vid', 't':'<?=$_SESSION['t']?>', 'id':id,'dir':dir},
success:function(data){
pos = data.split('_');
pos_from = pos[0];
pos_to = pos[1];
//$("#if"+id).hide();
if ($("#pos"+pos_to).length) {//if the id2 is on page (and not on a different paginated page) - swap them on-screen
temp_html = $("#pos"+pos_from).html();
$("#pos"+pos_from).html($("#pos"+pos_to).html());
$("#pos"+pos_to).html(temp_html);
temp_html = null;
}
else $("#pos"+pos_from).html('<div>Video moved off page.<br> Reload to see the result.</div>');
//$("#if"+id).fadeIn(400);
},
error:function(){
//$("#"+msg_id+'_a').html('error');
}
});
return false;
}
</script>
HTML:
<textarea name="vref" cols="55" rows="3" id="vref" placeholder="Video embed code"></textarea>
<input type="button" value="Add" onclick="add_vid('<?=$_SESSION['t']?>')"> <span id="add_vid_status"></span>
<input type="button" value="update" onClick="update_vid(27)">
<textarea cols="65" rows="3" id="update27"><iframe src="http://player.vimeo.com/video/123456789?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></textarea>
PHP code:
<?
session_start();
if ($_SESSION['auth'] != 1 || $_POST['t'] != $_SESSION['t']) exit();
elseif (isset($_POST['a'])) {
require_once('cfg.php');
db_connect();
if ($_POST['a'] == 'add_vid' && strlen($_POST['vref'])>4) {
//ADDS VIDEO TO DB AND ECHOES "added"
}
elseif ($_POST['a'] == 'del_vid' && is_numeric($_POST['id'])) {
//DELETES VIDEO AND ECHOES "deleted"
}
elseif ($_POST['a'] == 'update_vid' && is_numeric($_POST['id']) && strlen($_POST['vref']>4)) {
$id = (int)$_POST['id'];
//echo 'PHP: '.$_POST['vref']; (here i can test if the argument reaches.)
$vref = mysql_real_escape_string($_POST['vref']);
$q = mysql_query("UPDATE `videos` SET `vref`='{$vref}' WHERE `id`={$id}") or die ('update error: '.mysql_error());
if ($q) echo 'updated';
}
// CODE GOES ON...
}
?>
You've got a typo in your Ajax data object:
't':'<?=$_SESSION['t']?>'
You use the same type of quotes twice, so Javascript thinks that t is a variable, and doesn't recognise it. Changing your quotes like this fixes the error that your code was throwing:
't':'<?=$_SESSION["t"]?>'
Otherwhise, if you did mean for this to be a variable, you need to use it as following:
't':'<?=$_SESSION["'+ t +'"]?>'
After abandoning the update feature, yesterday when I wanted to copy the code for a similar project I noticed the glaring mistake in the PHP code where I am checking the string length: I had written strlen($_POST['vref']>4) instead of strlen($_POST['vref'])>4. After
correcting this it works perfectly.
I am trying to call ajax but it always goes in error part. Please help and tell me where I am wrong. I have also tried writing the final value in a text file and it was perfect but don't know why it is not working. I have also checked the URL it is also correct.
PHP Code:
public function checkLockBeforeSend()
{
$mail_key = $_POST['mail_key'];
$this->load->model('dl_master/email_compose');
$result = $this->model_dl_master_email_compose->checkLock($mail_key);
if($result['isopen'] == 1 && $result['openedby'] != $_SESSION['user_id'])
{
$this->load->model('dl_common/commonutil');
$userResult = $this->model_dl_common_commonutil->getUserById($result['openedby']);
$userName = $userResult['firstname'] . " " . $userResult['lastname'];
$html = $userName;
}
else
{
$html = "Empty";
}
/* Just to check what value is coming */
$fp = fopen("C:\\test.txt","w");
fwrite($fp,$html);
fclose($fp);
echo $html;
}
Ajax function:
function checkLockBeforeSend(mail_key)
{
var ajaxUrl = "index.php?route=dl_master/email_compose/checkLockBeforeSend&token=" + token;
$.ajax ({
url:ajaxUrl,
type:'post',
dataType: 'html',
data:{'mail_key':mail_key},
success:function (result)
{
alert(result);
if(result.trim() != "Empty")
{
finalResult = confirm(result);
}
},
error: function ()
{
alert("An error occurred.");
}
});
}
Please help me.
Please try data:{mail_key:mail_key}, instead of data:{'mail_key':mail_key},.