jQuery AJAX datatype html using - php

Hi I'm using jquery ajax function with php. Here is the my problem;
Firstly I'm using datatype:"html" my problem is php variables not returning.
js
$.ajax({
type: "POST",
dataType: "html",
url: ajaxurl,
data:dataajax,
success:function(data) {
var $data = $(data);
$(".list").append($data);
},
error : function(jqXHR, textStatus, errorThrown){
}});
php
echo "<div>".$_POST['value']."</div>";
if I use like this it's working but when I remove the html tags ajax return nothing.
broken php
echo myfunction($_POST['value']);
echo $_POST['value'];
How can I fix this or can I use return $output with jquery ajax?

The problem is with your success callback function.
data is a html string, and as such you don't need to wrap it in jquery.
Use this.
$.ajax({
type: "POST",
dataType: "html",
url: ajaxurl,
data:dataajax,
success:function(data) {
$(".list").append(data);
},
error : function(jqXHR, textStatus, errorThrown){
}});

Ajax uses JSON data for your request and response. what you are going to want to do is return a JSON variable so that the javascript response function can access elements properly.
Luckily php is designed to do just that thing.
$ajaxData = $_POST['value'];
echo json_encode(array('response' => $ajaxData));
what are you actually trying to do with this data? if all you need to do is wrap some html in a div you can use functions like wrap() in javascript and you wont actually have to send an ajax to the server.
Either way you should really consider your data needs and try to send a json object in the ajax request so that there are actual variables to send. html markup is probably not going to be useful for the php code.

Related

Cross domain jquery json

I have tried tons of thing to get json data from another url with jQuery. I have working code in php, but dont have any idea how to do it in jquery.
PHP:
$skin = rawurlencode($market_hash_name);
$skin2 = str_replace('%0A', '', $skin);
$link = "http://steamcommunity.com/market/priceoverview/?country=EU&currency=3&appid=730&market_hash_name=".$skin2;
$json2 = file_get_contents($link);
$obj2 = json_decode($json2);
$mediumPrice = $obj2->median_price;
Example of jQuery that i have tried:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU&currency=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
});
Typically a easy way around that is to create a Proxy, that is just a fancy word for saying have something else send and receive the data between the end points.
This can be as simple as using ajax to a PHP file on your server, from that PHP file using CURL to your endpoint, back to the output through echoing the return of the CURL script.
That way you can get around the restrictions on JavaScript. You mention
I have working code in php
So it should be relatively trivial to pipe the ajax call through that code and back.
Ok so instead of doing this
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU&currency=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
Do this
$.ajax({
type: 'GET',
url: 'http://yoursever.com/proxy.php/?country=EU&currency=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'json',
success: function (data) {
alert(data.median_price);
}
});
Then in proxy.php or whatever you chose to name it, use your working php code to make the call then simply return that data to the client through JSON as per normal AJAX. Then you are technically calling the remote sever using PHP and don't have the cross domain issue. But because you are using your sever as a Proxy you can still do it in real time.

send a text with ajax and receive a response

Hmm I have a little problem with that :
$.ajax({
type: 'POST',
data: {
name : 'aatrox'
},
dataType: "json",
async:false,
url: 'appliserv/testsendajax.php',
success: function(data){
console.log(data);
alert('good');
},
error: function(data){
console.log(data);
alert(fail);
}
});
the text in the alert is always fail ....
in my serv :
$text = $_POST['name'];
echo $text;
and I don't understand that. Thanks (sry if my english isn't good)
Your server-side script output plain text. So you have to change value of dataType option.
Change this:
dataType: "json"
to this:
dataType: "text"
Quite likely you're getting a parse error. This is because your ajax request is expecting JSON but you're are returning a plain string. Either return JSON from your PHP script or change the dataType to text:
dataType: "text",
Also be sure to change alert(fail); to:
alert('fail');
String literals must be delimited or variables have to be initialized before they are used.
You already got your answer, I just want to add that using
async: false
is a bad practice when dealing with ajax calls, it freezes your browser while waiting for the response.
If it's possible you should try to avoid this behavior and use
instead the ajax callbacks properly; however if you really want to block the UI you can try to use something like http://malsup.com/jquery/block/

javascript array to php array

i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.

ajax request is being sent to PHP to do some maintaining, but errors because it doesnt like php tag?

My AJAX request to pings the server, and the URL but returns an error because it doesnt like the '<' as the open tag for the php script.
AJAX script.
$.ajax({
url: "data.php",
type: "POST",
data: JSON.stringify({"data":transaction}),
dataType: "json",
success: function(data, textStatus, jqXHR){
alert("success");
currentProcesses -= 1;
$("<span>").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
},
error: function(jqXHR, textStatus, errorThrown){
alert("error with ajax call "+textStatus+" "+errorThrown);
}
});
php script
<?php
$win = $_POST['data'];
?>
Am I using the wrong flag settings for the AJAX call?
The body of your POST request is encoded as application/json instead of application/x-www-form-urlencoded.
You aren't doing anything to make the request say that the data is encoded in JSON and you aren't doing anything in PHP to try to parse JSON.
As a result, PHP fails to populate $_POST, because the data is in the wrong format.
The solution is: Don't send JSON. Just give the data property an object as its value, and jQuery will serialise it to application/x-www-form-urlencoded data for you.
data: { "data": transaction },
(Assuming that transaction is not a complex data type (like an array or object).
Additionally, the body variable is undefined. You should either use a string (to make it a selector: "body") or pass the body element directly: document.body.
Is it choking on what it's receiveing? Try this...put an id attribute on your span tag, and reference that.
In the page:
<span id="someName">...</span>
In your ajax call:
$("#someName").html(...
Try making the span more unique using class or id like
<span id="output"></span>
and try this.
$("#output").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
}

jQuery posts version in AJAX call

I have a simple script that gets the value of a textarea and posts this via AJAX. If I post "??" I get strange values. If I log out the value it retrieves before posting it all is correct. But the POST data my script receives includes the jQuery version number. My code and results are are below. Should I be escaping this somehow ?
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
My post data comes through as "jQuery17106460378167700797_1345234676316" for the value of text.
It's a POST request, not GET, and should be:
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data: {text : value}, //object
dataType:'JSON',
success:function(data){
}
});
PHP
$value = $_POST['text'];
Also, setting the dataType to JSON evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner, any malformed JSON is rejected and a parse error is thrown. This means any malformed JSON, and your ajax call will fail.
I am not sure when you are executing the script, is it on button press?
If not, you will need to wrap it so that it runs only after DOM had completed loading:
$(document).ready(function()
{
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
});

Categories