Passing a string dynamically to a page using AJAX - php

I have a registration form with a text field. I am trying to pass the string that is inputted on that field to a php file to validate the string dynamically. What would be the best(performance-wise) way to do it.
using
data: { cont: str , inputType : vtype}
or a query string
url: 'validate.php?q='+str+'t='+vtype;
this is my current script:
function validate(str,vtype) {
$.ajax({
type: 'GET',
url: 'validate.php?q='+str+'t='+vtype,
timeout: 1000,
success: function (data) {
$("#validationIndicator").html(data);
},
error: function (XMLHttpRequest, errorThrown) {
$("#validationIndicator").html('');
}
});
}

First of all, jQuery is meant to make JavaScript development easier; why go through string concatenation with more elegant alternatives?
The other thing jQuery does is to make sure your data is properly escaped; to give an example, the equivalent of using data: is actually this:
url: 'validate.php?q=' + encodeURIComponent(str) + 't=' + encodeURIComponent(vtype);
Otherwise, the values of str or vtype may mess up the query string.
Second, the time spent constructing the request vs the round trip to the server is negligible, so you should pick the option that's simpler and less error prone.
Conclusion
Go with this:
data: { cont: str , inputType : vtype}

Interesting question! When you pass data key-value pair within $.ajax({}), it converts it into a query string, and appends it to URL. This is similar to you doing following:
url: 'validate.php?q=' + str + '&t=' + vtype;
In other words, for GET request, it is better to build and use URL (with query string) explicitly, rather than letting jQuery do the conversion for you.
Also, there is a processData boolean that you can pass within your Ajax request. This boolean, if provided FALSE, won't convert data to query string automatically.
Source: https://api.jquery.com/jQuery.ajax/

Related

javascript unexpected token < , is there any way I can escape the errors(or atleast skip those useless characters)

In php, I have an array like this :
$arr['a'] = "some big data so may contain some chars that bring us headache"
$arr['b'] = "some big data same as above"
$data = json_encode($arr)
echo $data
My javascript code containing a jquery ajax call, $.ajax . It calls the file containing the above php code so, on success, the json_encoded(by php) is returned to my javascript variable . In my javascript file, I am doing like this :
jsdata = JSON.parse(data); //Getting error here
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp'
}).done(function(d) {
print("success");
});
From the above code, in the line jsdata = JSON.parse(data), I am getting errors something like
Error : UNEXPECTED TOKEN <
As the data contains lot of different content, its normal to get those errors . They need to be escaped properly . Can anyone tell me how to do that correctly . Whatever the data may be , I shouldnot get error regarding the data .
Thanks
Well, a couple of things you should probably know jsdata = JSON.parse(data); tries to parse whatever json string you assigned to data, and return it as a JS object. I think you want to do the opposite: jsdata = JSON.stringify(data);
Besides, since you are using jQuery, you could just leave that line out: jQuery will convert the data to the appropriate format before sending the request anyway, no need to bother with parsing or stringify-ing it yourself.
Yeah you forgot the ; at the end of two lines, so PHP is outputing an error, which is no JSON-compliant.
Always do this :
Catch errors and output them in a way that is understable by your application (a 5xx status can be enough)
Next time you have this, use Chrome Developper tool or Firebug to see what your app really returns
Also, you're outputing json, not jsonp which is different and what your app expects
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp',
success: function(d) {
print("success");
}
})
try it this way
This is much more simple than it might seem.
Call urlencode($arr['a']) and urlencode($arr['b']) (for each data value in $arr) before encoding the JSON and echoing $data to the JavaScript. This will URL-Encode the data in the array so that it will cause you no problems.
When you are done parsing the JSON, you will have to call the JavaScript function unescape(string) on each of the large data values. This will return them to the way they originally were. It's a sort of superhero-team-up of PHP and JavaScript!

How to use 'data:' in jQuery AJAX function?

I'm using this jQuery AJAX function and I'm trying to figure out how to use the 'data:' part of it. According to this page (http://api.jquery.com/jQuery.ajax/) I can use 'data:' to send the number 22 to 'process_stage.php' so I can use it.
Can anyone tell me what I need to type in my process_stage.php page to access the number 22?
function myAJAX(){
$.ajax({
url: 'process_stage.php',
data: '22',
dataType: 'json',
success: function(data) {
var videoid = data[0];
var currentID = data[1];
$('#youtube').html("<iframe width='400' height='225' src='http://www.youtube.com/embed/"+videoid+"?rel=0&autohide=1&showinfo=0&autoplay=1' frameborder='0' allowfullscreen></iframe>");
setTimeout(function (){
timedCount(currentID);
},1000);
}
});
}
As you're making a HTTP GET request, data needs to be key-value pairs, as that's how a GET request is constructed (e.g. /get.php?var1=a&var2=b&var3=c).
jQuery.ajax() accepts this key-value pairs as either an object map, or a string, as described in the documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So you should use either;
data: "value=22"
or
data: {
value: 22
}
Then in PHP you can use $_GET['value'] to retrieve it.
Your value needs a field name to go with it. To do this, make data an object e.g. {my_value: 22}. Then in your PHP script look for the field called my_value.

json_encode, json.parse dropping a '+' character?

A quick question
Does php function json_encode or js JSON.parse function drops '+' character by default? I definitely get a '+' lost somewhere and at cannot figure out where. This is quite urgent as it's actually an xml feed from realex, which authorizes (or in this case doesn't authorize) payments on one of our live sites. To make things more complex, I cannot use dev environment at the moment and I cannot play in printing out values on the screen on the live site. So I'm trying to make a guessed-fix for the start
Ok, here's some exmaple
I get a value from Realex
$RESPONSE_THREEDSECURE_CAVV = 'jFvMUENpUEzLARAQBtmeh+Q5o/U=';
$parametersToPass['cavv'] = $RESPONSE_THREEDSECURE_CAVV;
There are more values in parametersToPass array, but this is the one that's causing troubles.
I encode it in php
$encoded = json_encode($parametersToPass);
die($encoded);
This is being returned in jquery ajax call success as 'data'
success: function(data) {
$.ajax({
type: "POST",
url: 'action/payment-process_auth.php',
data: "data="+data
});
}
I retieve it in payment-process-auth
$decoded = json_decode($_POST['data']);
$parametersToPass['cavv'] = $decoded->cavv;
At this point cavv value is jFvMUENpUEzLARAQBtmeh Q5o/U= instead of jFvMUENpUEzLARAQBtmeh+Q5o/U= (space instead of a +)
How can I sort this out?
No, json_decode and JSON.parse both respect + characters.
In a URL, though, a + is turned into a space if not properly urlencoded to %2B... so if you're json_decodeing a $_GET parameter that may be what's going on.
Try posting your data with AJAX in a proper JSON format?
success: function(data) {
$.ajax({
type: "POST",
url: 'action/payment-process_auth.php',
data: {"data": data}
});
}

how can save a string as it is in mysql database

Im trying to save this string:
~`##$%^&*()_+}{":?><,./;'[]=-|\
using a AJAX call in php. But in the database it saves as this:
~`##$%^????
this is my AJAX call
function saveComment(timesheetId,activityId,date,comment,employeeId) {
var r = $.ajax({
type: 'POST',
url: commentlink,
data: "timesheetId="+timesheetId+"&activityId="+activityId+"&date="+date+"&comment="+comment+"&employeeId="+employeeId,
async: false
}).responseText;
return r;
}
Edit: Fixed display of strings and code.
You need to in javascript call encodeURIComponent on the string with the weird characters before you send it to the server.
EDIT: Tomalak pointed out a better method.
If you want to put a variable 'text' in the data, you should run it through $.URLEncode(text) before doing so; as it is, the '&' character in the text introduces a new parameter.
jQuery supports an object as the data parameter in Ajax requests. This also does the URL encoding for you automatically:
$.ajax({
type: 'POST',
url: commentlink,
data: {
timesheetId: timesheetId,
activityId: activityId,
date: date,
comment: comment,
employeeId: employeeId
},
success: function (data) {
alert(data);
}
});
Also - you should never use synchronous Ajax requests. Always work with callback functions.

Handling JSON repsonse

I'm doing an AJAX call using jQuery's JSON feature.
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
pop_word_list(json, paging_value);
}
});
}
As you can see, I'm sending the response to another JavaScript function, but what I'd like to do is send the response to PHP. Is this possible, say to directly convert the response into a PHP array (not using JavaScript) and then use PHP to handle the array, etc?
Thanks in advance.
You could perform another Ajax call to the php script in the success function, passing along the JSON data as a POST param.
do this?
js (ajax) -> php (array conver to ajax) -> js (ajax) -> php ?
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
json["paging_value"] = paging_value;
$.post("x.php", json);
}
});
}
The whole idea doesn't stick together at all... but:
If there is a reason to do that - then You want to do the $.post('phpfile.php',json,function(){},'text or whatever type You want in return');
and the whole json object goes to PHP's $_POST[] as suggested above, but I can see NO case where it should be done that way.
If You get that json from some code You can't change and want to use data in php do:
use cURL to get the data from another thing
use json_decode($data,true) to get assoc table of the whole thing
If You don't know what You're doing :)
just pass the object to another function without useless sending stuff back and forth. You might want to do empty AJAX call to trigger the php file, nothing more.

Categories