why replaced plus in string by space - php

I am using ajax to send data through an AJAX call to set.php:
$.ajax({
url: "ajax/set.php",
dataType: "html",
type: 'POST',
data: "data=" + data,
success: function (result) {
alert(result);
}
});
Before sending the AJAX call, I am using JavaScript to alert() the data, the data is:
JeCH+2CJZvAbH51zhvgKfg==
But when I use $_POST["data"], the data is:
JeCH 2CJZvAbH51zhvgKfg==
Which displays pluses replaced with spaces, how can I solve this problem?

When using $.ajax, use an object rather than a string with the data: option. Then jQuery will URL-encode it properly:
data: { data: data },
If you really want to pass a string, you should use encodeURIComponent on any values that might contain special characters:
data: 'data=' + encodeURIComponent(data),

Taking a look at the jQuery docs, you can pass an object to data instead of the actual query built by hand. Try:
$.ajax({
url: "ajax/set.php",
dataType: "html",
type: 'POST',
data: {
data: data
},
success: function (result) {
alert(result);
}
});

I believe you need to encode that + with its URL Encoded value %2B.
To do this, use the replace method.
var data = data.replace(/\+/g, "%2B");

Related

Sending # symbol with AJAX to PHP

I have got this Ajax that send comment's text to PHP
$.ajax({
type: "GET",
url: '../files/ajax.php',
data: "C=" + cc+"&I="+i,
success:function(data) {
alert(data);
}
});
if (isset($_GET["I"]) && isset($_GET["C"])) {
$RandS=$_GET["I"];
$Comment=$_GET["C"];
$Comment=trim($_GET["C"]);
$Comment=htmlspecialchars($_GET["C"]);
echo $Comment;
}
When comment is something like
Hope you like pancakes It returns everything perfectly,But when comment is '#I #Like pancakes' it does not return anything except error
Uncaught SyntaxError: Unexpected end of JSON input
You need to URL-encode the parameters if they contain special characters. When using $.ajax, the best way to ensure that they're encoded properly is to use an object rather than a string for the data: option.
$.ajax({
type: "GET",
url: '../files/ajax.php',
data: { C: cc, I: i },
success:function(data) {
alert(data);
}
});

Jquery query string type to

i am using serialize()
Some Event trigger(assume click)
var querydata= a=1&b=2&c=3 //jquery printing
$.ajax({
url: "script",
data: querydata,
method: "POST",
dataType: "text",
success: function(data) {
$("#counts").html(data);
}
});
in php do i just use the regular post method
a=htmlspecialchars($_POST["a"]); b=htmlspecialchars($_POST["b"]); and so on
or do i need to use jquery to get the string to variables and then send to data as a object array
if jquery is also an option could you tell me how i would do that im fairly new to jquery and i really want to learn it
Why bother creating a functionality that your browser+PHP provide already??
In your case, if you really have to send a raw string:
var querydata = 'a=1&b=2&c=3';
$.ajax({
url: "script",
data: querydata,
method: "POST",
dataType: "application/x-www-form-urlencoded",
success: function(data) {
$("#counts").html(data);
}
});
You may also want to simplify:
var querydata = {a: 1, b: 2, c: 3};
$.post('url', querydata, function(data){
$("#counts").html(data);
});

AJAX jQuery PHP Return Value

I am new to AJAX and am kind of confused by what PHP passes back to the jQuery.
So you have an AJAX function like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
(I took this from ajax another StackOverflow page.)
But on various other resources they will have the success section look like this:
success: function(data) {functionfoocommandshere}
I am just confused as to what dictates the naming of this variable? If the PHP ultimately echoes an array:
echo $myVar;
How can I get this from the AJAX?
An Ajax-Requests fetches a whole site. So you'll not get any data in variables, but the whole site in the data-parameter. All echos you made together will be in this parameter. If you want to retrieve an array, you should transform it to json before.
echo json_encode($myArray);
Then you can receive it via Ajax in this way
$.ajax({ url: '/my/site',
data: {action: 'test'},
dataType: 'json',
type: 'post',
success: function(output) {
alert(output);
}
});
In you PHP file, use json_encode to turn the array into a more convenient format for use in Javascript. So you would have something like:
echo json_encode($myArray);
Then, in your JavaScript, the data variable of the success method will hold the JSON. Use jQuery's parseJSON to convert this to a JavaScript object, which will then be very easy to manipulate. I don't know what you array contains, but you might do something like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.name[0] === "John");
}
});
Again, the data variable here will contain anything your PHP outputs, but JSON is a common and convenient way to transfer data back to your JavaScript.
<script type="text/javascript">
$.ajax({
url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
<?php
$action = $_POST['action'];
echo $action;?>
Any output that is printed/echoed will be returned to the success function. This is handy when you want to fill an html container with something that you need to run in real time.
Once you get the hang of this, another option is to use JSON to return variables with values.
The data that's returned from the PHP AJAX function, can be retrieved from the success block. Here's the manual
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
dataType: 'json',
success: function(output) {
//output is the data returned from PHP AJAX function in JSON format
alert(output);
}
});

jQuery AJAX call (POST to PHP) issues

I need to use the $.ajax() call within jQuery to post a little bit of JSON to my PHP script.
I have tried everything but nothing works as I would like it to. I simply try to echo a var_dump of the $_POST/$_GET arrays but it comes back empty.
var myJSONObject = {"bindings": [{"conversation": _conid} ]};
var obj = $.toJSON(myJSONObject);
$.ajax({
type: "POST",
url: "./code/ajax/fetch_messages.php",
data: obj,
async:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
},
beforeSend: function (XMLHttpRequest)
{
},
complete: function (XMLHttpRequest, textStatus)
{
}});
I can see that the post is made by looking in the headers:
{"bindings":[{"conversation":"38x001c61450ad4d5abd47c37408e8236eb5427f54e2930000306882646e4016c5f8ecf8e00a18a26ab3b6d07f6727bd187625daaedf951f93072d54d59e300e100"}]}
PHP:
echo var_dump($_POST);
Everything works great when using the $.post() call but I always run in to problems when I try to switch to $.ajax. I need to use it to be able to retreive the response UTF-8 encoded.
The code pasted in this post is just one of many snippets I've tried, even examples from tutorials on the web does not work.
Could someone please give me a snippet that you know do work so I can try that? Sending JSON through POST.
I think you must give your json string a key, so you can get it on the other side (PHP):
data: {"myjson": obj},
Then on PHP it will be in $_POST['myjson']
below is a slice of my routine and it works fine :
var data = 'post_type=' + post_type.val() + '&page_id=' +
page_id.val() + '&home_page='
+ home_page.attr('checked') + '&archive_page=' +
archive_page.attr('checked') + '&search_page=' +
search_page.attr('checked');
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "?service=set_data",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: true,
//success
success: function (html) {
$(".no-items").hide("slow");
$("#list_table").append(html).hide().slideDown('slow');
}
});

Can a Jquery Ajax Call Accept an Object on Succes from PHP?

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.
Here is my Javascript function
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}
Here is my php doc (so far, this is where I need to know how to return an object)...
<?php
$data = array('title'=>'this');
echo json_encode($data);
When I run the function I just get the alert "undefined".
Suggestions?
Thanks,
-J
Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data.title);
}
});
}
I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.
Your php page returns: {"title":"this"} in this case.
So you can reference the result with:
alert(data.title);
You may need to specify the data type:
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
dataType: 'json',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}

Categories