jQuery/ajax won't send post data - php

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.

Related

I am unable to post data using ajax on url friendly blog detailing page where I am already using url value in Query

I know that it may be so tricky!
In detail:
on the blog detailing page(blog-single.php/title) I have a subscription form this subscription form is working fine on another page with the same PHP action file and ajax
and blog-single.php/title is also working fine until I did not submit the form
On this page in the starting, I have bellow query
<?php
$query_head="SELECT * FROM blog_post WHERE friendly_url = '{$_GET['url']}' ";
$result_head= $fetchPostData->runBaseQuery($query_head);
foreach ($result_head as $k0 => $v0)
{
//----- some echo
}
?>
and my subscription form code:
<form action="" method="post" class="subscribe_frm" id="subscribe_frm2">
<input type="email" placeholder="Enter email here" name="email" id="subscribe_eml2">
<button type="button" id="subscribe2">Subscribe</button>
</form>
and ajax code is bellow:
$(document).ready(function() {
$("#subscribe2").click( function() {
subscribe_frm_val2 = false;
/*email validation*/
var emailReg2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($("#subscribe_eml2").val().length <= 0) {
$("#subscribe_eml_Err2").html("Required field");
//console.log("Required");
subscribe_frm_val2 = false;
}
else if(!emailReg2.test($("#subscribe_eml2").val()))
{
$("#subscribe_eml_Err2").html("Enter a valid email");
}
else{
$("#subscribe_eml2").html("");
subscribe_frm_val2 = true;
//console.log("final else");
if(subscribe_frm_val2 == true)
{
console.log("frm true");
var form = $('#subscribe_frm2')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "updation/subscribe_action.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
beforeSend: function(){
// Show image container
$("#submition_loader").show();
//alert ("yyy");
},
success: function (data) {
// console.log();
$(document).ajaxStop(function(){
$("#subscribe_eml_Err2").html(data);
});
},
complete:function(data){
// Hide image container
$("#submition_loader").hide();
}
});
}
else{
alert('Please fill all required field !');
}
}
});
});
When I submit my form above the first query is giving a warning like below:
Warning: Invalid argument supplied for foreach() in D:\xamp\htdocs\my\bootstrapfriendly\category.PHP on line 13
and after warning page doing misbehave
I think the error because of URL passing but I am not sure how to solve it
Please help me with solving it.
Thank's
I got the solution
its very simple just converted my relative URL into an absolute URL
I just created a PHP function for base URL
function base_url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
and then using this base URL function inside script like this
$.ajax({
----
url: "<?php echo base_url()?>/updation/subscribe_action.php",
-----
});

Ajax form validation without caching

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 cant get response from json encode

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

How to properly switch a bind in javascript to on or live?

I am new to php, and I am trying to learn through tutorials. Right now, I am working on a chat tutorial. Lately, I ran into a problem where the tutorial asked that I use bind, but I don't think it works with jquery anymore. I am trying to throw the message to my message box. Here is the code to my javascript
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'fetch' },
success: function(data) {
$('.chat .messages').html(data);
}
});
}
chat.throwMessage = function (message) {
if ($.trim(message).length != 0) {
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'throw', messsage: message },
success: function(data) {
chat.fetchMessages();
chat.entry.val('');
}
});
}
}
chat.entry = $('.chat .entry');
chat.entry.bind('keydown', function(e) {
if (e.keyCode === 13 && e.shiftKey === false) {
chat.throwMessage($(this).val());
e.preventDefault();
}
});
chat.interval = setInterval(chat.fetchMessages, 4000);
chat.fetchMessages();
Here is the php file that is being sent the information:
<?php
require '../core/init.php';
if (isset($_POST['method']) === true && empty($_POST['method']) === false) {
$chat = new Chat();
$method = trim($_POST['method']);
if ($method === 'fetch') {
$messages = $chat->fetchMessages();
if (empty($messages) === true) {
echo 'There are currently no messages in the chat';
} else {
foreach($messages as $message) {
?>
<div class="message">
<?php echo $message['username']; ?> says:
<p><?php echo $message['message']; ?></p>
</div>
<?php
}
}
} else if ($method === 'throw' && isset($_POST['message']) === true) {
$message = trim($_POST['message']);
if (empty($message) === false) {
$chat->throwMessage($_SESSION['user'], $message);
}
}
}
When I open up inspector, all the tests are working properly, but the php code does not seem to be putting the data on on my message box.
$(document).on('keydown', chat.entry, function(e) {
if (e.keyCode === 13 && !e.shiftKey) {
e.preventDefault();
chat.throwMessage( this.value );
}
});
instead of document use rather an #element
With "bind" only the existing element will be affected, if you add another element this one will not be affected by the event.
Live affects existing elements and elements that will be added in runtime.

livevalidation.js custom username check function

I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.
i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)
try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};

Categories