I'm implementing a photo tagging system.
in my php file I have:
if($_POST['type'] == "insert") {
$pid = $post->ID;
$tag_name = $_POST['tag_name'];
$tag_link = $_POST['tag_link'];
$pic_x = $_POST['pic_x'];
$pic_y = $_POST['pic_y'];
$arr = array("tag_name" => $tag_name, "tag_link" => $tag_link, "pic_x" => $pic_x, "pic_y" => $pic_y);
add_photo_tag($pid, $arr);
wp_redirect("http://www.test.com");
}
to catch the data. in my js file i have:
$('#tagit #btnsave').live('click',function(){
name = $('#tagname').val();
link = $('#taglink').val();
counter++;
$('#taglist ol').append('<li rel="'+counter+'">'+counter+'. '+name+' (<a class="remove">Entfernen</a>)</li>');
$('#imgtag').append('<div class="tagview" id="view_'+counter+'">'+counter+'</div>');
$('#view_' + counter).css({top:mouseY,left:mouseX});
$('#tagit').fadeOut();
$.ajax({
type: "POST",
url: "content.php",
data: "tag_name=" + name + "&tag_link=" + link + "&pic_x=" + mouseX + "&pic_y=" + mouseY + "&type=insert",
cache: true,
success: function(data) {
alert("success!");
}
});
});
Somehow the variables don't get passed to the php resulting in me not able to save the data properly to database.
The problem must be somewhere in either the $.ajax part or php. Can someone help me?
Well, you're checking post variable $_POST['type'] == "insert_tag" while it's actual value is: &type=insert. Others look fine. Btw never user .live(), it's obsolete, do it with .on()
Also, if all your elements are on a form you may use $('your_form_selector').serialize() - that'l be your post data
Your php code is looking for 'type' to be equal to 'insert_tag'.
Your JavaScript is POSTing with type=insert - so your php code ignores it.
Why are you redirecting in your PHP code? Remove this line:
wp_redirect("http://www.test.com");
You can replace it with some sort of a simple feedback system. After all you want the server-side to pass back the status and maybe some validation messages.
$return = array('status' => 0, 'msg' => 'all is well');
if(!add_photo_tag($pid, $arr)) {
$return['msg'] = __('Could not add photo tag.');
$return['status'] = -1;
}
echo json_encode($return);
Try with the following code:
$.ajax({
type: "POST",
url: "content.php",
data: {"tag_name": name,"tag_link":link,"pic_x": mouseX,"pic_y":mouseY, "type":"insert"},
//change here like I have done
cache: true,
success: function(data) {
alert("success!");
}
});
And Replace the if($_POST['type'] == "insert_tag") line with following:
if($_POST['type'] == "insert")
As the value you are passing of $_POST['type'] is insert not insert_tag.
EDITED:
one more thing as I have found that is you have not used the var before initializing the variable. use the var name = ...
Related
I am trying to to an on the fly database update of a select field but there can be more than one instance on the page of this field. I had this working for a single on change select field change, but with more than one I am simply passing the values for the first one.
I have in the past dealt with creating unique DOM ids for these on the page, but in this instance with a select field and using the change function I am a bit befuddled. Also most of the situations I found in searching this were not for select fields or dealing with passing variables in this way. I am fully aware this is crude and probably there is a much better way to accomplish this task.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $('.preferenceData').val(), data2: $('#userID').val()}, // this second data element not really needed but is passing var
dataType: 'text',
success: function(html){
if(html) {
$("div#updateDisplay").replaceWith('<div id="updateDisplay">' + html + '</div>');
}
})
});
The form bit:
echo '<div id="userPref"><select class="preferenceData" name="preferenceData'.$row['uid'].'">';
$prefs = enum_select($db,'db_table_name','email_preferences');
foreach($prefs as $pref)
{
echo '<option value="'.$pref['value'].'-'.$data['topicid'].'-'.$row['uid'].'"'.($row['email_updates'] == $pref['value'] ? ' selected' : '').'>'.$pref['display'].'</option>';
}
echo '</select></div>';
The function it's passed to:
function save_preferences()
{
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
$db = new db(0);
$vars = $_POST['data1'];
$data = explode("-", $vars);
// Update Database
$data = $db->Exec('UPDATE km_vendors_users SET email_updates = "'.$data[0].'" WHERE vid = "'.$data[1].'" AND uid = "'.$data[2].'"');
if($data==false)
{
echo $db->log;
//return false;
}
else
echo '<img src="/images/icons/success_check_animated.gif">';
}
}
For your code, you are trying to pass $('.preferenceData').val() for data1, which will be fairly unexpected results (and usually not a value).
Instead you can use $(this).val() which refers the specific element that changed, and its value.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $(this).val()},
...etc...
});
});
I have used ajax as below:
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var valueSelected = valueSelected.replace(/ /gi,"%20");
var valueSelected = encodeURIComponent(valueSelected);
//alert(valueSelected);
$.ajax({
type: 'post',
encoding:"UTF-8",
url: "<?php echo base_url();?>Search/cities_of_province/"+valueSelected,
data: '',
contentType: "charset=utf-8",
success: function (result) {
//alert(result);
$('.city').html(result);
return false;
}
});
return false;
});
valueSelected in above url is a persion statement with space in it. for example it is استان آذربایجان شرقی.
when it is post to the url, just first part(استان) is recieved.
I aslo removed valueSelected.replace(/ /gi,"%20") and encodeURIComponent(valueSelected) but nothing happend.
what is the solution?
I faced no issue like that.. I used no encodeURIComponent no encoding:"UTF-8" no contentType: "charset=utf-8"
Nothing needed. And it works simply perfect. I tested it with following code
I have Html
<input id='yourInputId' value='استان آذربایجان شرقی' />
JavaScript
<script>
var valueSelected = $('#yourInputId').val();
//before ajax request
alert(valueSelected ); // it gives me here =>استان آذربایجان شرقی
//before making ajax reuest plz confirm you get above value correctly here
alert(<?php echo base_url();?>); //it must be valid as well
$.ajax
({
type: "POST",
url: "<?php echo base_url();?>Search/cities_of_province", //should be valid
data: { province : valueSelected },
success: function (result) {
alert(result); //it gives => استان آذربایجان شرقی
},
error:function(a)
{
alert(a.responseText);
}
});
</script>
PHP
<?php
if(isset($_POST['province']))
$v = $_POST['province'];
else
$v = 'Province value not provided from client side';
echo $v;
?>
So it looks like you are using a select input here. If that is the case, you should use alphanumeric/ASCII value key in your options and not the human readable labels. That might look like:
<option value="some_ascii_key">استان آذربایجان شرقی</option>
You can then have a reliable key to use in your AJAX request.
I also think your request should be a GET and not a POST since you are just reading values from API rather than trying to create/update records via API.
Putting it all together, you might have something like this:
// note values for each property/ley may not be important here
// as they are not really needed to validate that the province key
// in option value has not been modified by client,
// which is really what you are using this for.
// If you need to have option label text available in
// javascript you can store that here as shown.
var provinceConfiguration = {
'key1': 'استان آذربایجان شرق';
'key2': 'some other Persian string';
// and so on...
}
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
// perhaps validate that value provided is amongst expected keys
// this used the provinceConfiguration object proposed in this example
if(typeof provinceConfiguration[valueSelected] === 'undefined') {
console.log('Unexpected province key passed');
e.stopPropagation();
return false;
}
// probably can drop this line if defined keys do not need encoding
var valueSelected = encodeURIComponent(valueSelected);
// since you can use default GET setting you can use this shorthand
$.get(
'<?php echo base_url();>Search/cities_of_province/' +
valueSelected,
function(result) {
// console.log(result);
$('.city').html(result);
return false;
}
);
/*
Or more verbose option
$.ajax({
type: 'GET',
// not valid setting key -> encoding:"UTF-8",
url: '<?php echo base_url();>Search/cities_of_province/' + valueSelected,
// default is fine here so not needed -> contentType: "charset=utf-8",
success: function (result) {
// console.log(result);
$('.city').html(result);
return false;
}
});
*/
return false;
});
Note that you should be using console.log() to debug code rather than alert(), as alert actually blocks code execution and may make some debugging more problematic as your debugging mechanism changes how your code executes. This can problem can be exacerbated when debugging asynchronous code.
Your server-side code would obviously need to be updated to understand the province keys as well.
Please take a look at this javascript library. That can be of help to you.
Fix Persian zero-width non-joiner(Replace spaces by half-space)
import { halfSpace } from "persian-tools2";
halfSpace("نمی خواهی درخت ها را ببینیم؟") // "نمیخواهی درختها را ببینیم؟"
Fix Persian characters in URL.
import { isPersian, toPersianChars } from "persian-tools2";
URLfix(
"https://fa.wikipedia.org/wiki/%D9%85%D8%AF%DB%8C%D8%A7%D9%88%DB%8C%DA%A9%DB%8C:Gadget-Extra-Editbuttons-botworks.js",
); // "https://fa.wikipedia.org/wiki/مدیاویکی:Gadget-Extra-Editbuttons-botworks.js"
URLfix("https://en.wikipedia.org/wiki/Persian_alphabet"); // "https://en.wikipedia.org/wiki/Persian_alphabet",
URLfix("Sample Text"); // "Sample Text"
I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST
I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!
I'm using jQuery with PHP for form validation. I want to return the fields that do not validate so i can highlight them using javascript
this is my attempt using PHP(validate.php):
<?php
...
$a_invalidInput = array();
$from = $_POST['from'];
$to = $_POST['to'];
$email_to = $_POST['email_to'];
if( empty($from) ){
$a_invalidInput[] = 'from';
}
if( empty($to) ){
$a_invalidInput[] = 'to';
}
//validate the email_to address
if( empty($email_to) ){
$a_invalidInput[] = 'email_to';
} else{
//do more validation for email
}
...
?>
This is my jquery code:
...
var data = "from="+ from + "&to=" + to + "&email_to=" + email_to;
$.ajax({
url: "includes/validate.php",
type: "POST",
data: data,
success: function(){
//highlight fields that do not pass validation
}
});
...
I'm not sure if i'm on the right path or not AND how to return the input fields that do not pass validation so i can add a class to highlight the fields that do not pass validation.
I could do this using javascript but i prefer using a php file for validation
Thanks
Marco
One way to go would be to return a json encoded array of fields that do not pass.
From your PHP script, output your Invalid Input array (json encoded so your javascript can use it). Then on the Javascript side, you want to check if that output has any values. If it does, use them.
<?php
// at the end of your script
header('Content-type: application/json');
echo json_encode($a_invalidInput);
exit();
?>
Now in your JQuery, you want to use that json output...
$.ajax({
url: "includes/validate.php",
type: "POST",
dataType: "json",
data: data,
success: function(data){
if (data !== undefined
&& data.length > 0) {
for (var i = 0; i < data.length; i++) {
var field_name = data[i];
var field = $('input[name=' + field_name + ']');
// now you have the field, so you can modify it accordingly.
}
}
}
})
Look into using jQuery for the form validation -- I personally find it easier. That said, you should always double check the data and ALWAYS escape it on the server-side.
http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/