Im trying to transfer an array from jQuery to PHP but for some reason after hours of searching nothing will work. Below is what I have and what others seem to be using online but for some reason I only get the error alert. Anyone know what it is I'm doing wrong? It seems to be something to do with my jQuery code but I can put in anything there and get the same results so it is useless for telling me what I am supposed to fix. Also Im not sure if it is important but the array Im using is 2d.
FINAL WORKING CODE:
jQuery:
$.ajax({
type: "POST",
url: "phpfile.php",
data: {"myData" : myArray},
success: function(data){
alert("Success");
//appends code to end of my webpage, just for testing purposes
$('#button').after(data);
},
error: function(e){
alert("Error")
}
});
PHP:
$data = $_POST['myData'];
//creates xml file
var_dump($data);
The following is copied from the comment so this question can be marked as answered:
It seems like it should be working so I would try a simple, very basic ajax test and make sure at least that is working correctly. I would try to:
1) Get rid of the dataType json line.
2) Take the "/" out of the url.
3) Change the data to {"myData" : "testing"} or even get rid of the data line altogether.
4) Change the PHP to only be: echo "test".
Then see if you alert Success. This will hopefully tell you that your ajax is working. If so, you can start putting your code back in and see where it fails.
The mistake might be:
data: {"myData" : myjsonString}
Try this, assumming that jsonString is a string
data: "myData="+ jsonString
Related
I'm building a autocomplete with Twitter typeahead using an ajax JSON call to my PHP file to get some data but it keeps displaying the following in the dropdown result list:
undefined
undefined
undefined
but when i do:
alert(data);
I get the right data displayed but somehow the autocomplete list keeps displaying undefined, I've read and tried multiple things by some articles here on StackOverflow, but I can't seem to get it to work.
I have to following jquery code:
$('.item-name .typeahead').typeahead(null,{
source: function (query, process) {
$.ajax({
url: 'ajaxItems.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
// alert(data);
process(data);
}
});
}
});
And my ajaxItems.php has the following code for testing purpose:
<?PHP
$results = array();
$results[] = 'jeans';
$results[] = 'sweater';
$json = json_encode($results);
print_r($json);
?>
The JSON output is as follows:
["jeans","sweater"]
I hope someone can shine some light on what I'm doing wrong or point me in the right direction.
edit
I am using the following typeahead file:
http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js
I had the exact same problem. To fix it I had to return an array containing key/value pairs with the key 'value' like this:
[{'value': 'first', 'value': 'second', 'value': 'third'}]
I don't think the typeahead docs make it clear enough but I believe it is the displayKey option which is set to 'value' by default.
The closest answer is ian's though it does not really work (only returns last value). Working answer is :
[{'value': 'first'}, {'value': 'second'}, {'value': 'third'}]
I had similar problems using source: and I ended up using remote:.
In your case, it would be something like this:
$('.item-name .typeahead').typeahead({
remote: 'ajaxItems.php?query=%QUERY'
});
Note that I deleted null on typeahead(null,{ since I think it's not necessary but I might be wrong. Obviously, you'll have to use $_GET instead of $_POST but I think it's much easier this way.
The problem is the typeahead is expecting a array with suggestions. Not the JSON !
use $.makeArray() like this:
success: function(data){
process($.makeArray(data));
}
if it doesn't , may be JSON.parse() should help ?
Mark it as answer if helpful :)
Absolutely new to PHP and so far it isn't pretty.
Anyway, I'm trying to pass a variable over to a PHP script, do a couple things with it, and pass it back to my Javascipt code.
Here's where I pass it off to PHP:
var src=encodeURIComponent("http://www.someonlinesite.com/file.swf");
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response)
}
});
and here's the script:
<?php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm trying to pass the URL of a .SWF video file over to a small PHP script that will use getImagesize() to figure it's dimensions and pass them back.... but I'm not seeing anything in the response and the alert isn't firing.
What's going wrong?
UPDATE:
I've updated the code with the most recent - according to the advice from some nice SO members. When I hardcode the $src variable and navigate directly to the test.php it echoes everything perfectly. So, it looks like the PHP is working. However, it appears like either the callback is never firing or the PHP file isn't returning the data. In the console there still isn't anything in the response.
You need to concatenate your url string parameter in get():
$.get('test.php?src=' + src, function(data){
alert(data);
});
And also, your src variable begins with a double quote and is closed with a single quote. That will cause issues.
var src="http://www.someonelinesite.com/file.swf";
Also, it's probably a bad idea to do this via $_GET since you are passing a URL. $_POST would be better or encode the URL before you pass it. The current url you are passing right now would look like this in a browser:
http://www.mysite.com/test.php?src=http://www.someonelinesite.com/file.swf
That's not pretty. Using encodeURIComponent(), your whole URL will end up looking like this:
http://www.mysite.com/test.php?src=http%3A%2F%2Fwww.someonelinesite.com%2Ffile.swf
Edit to $.ajax
$.get above would work just fine, but going with the implementation of $.ajax works too:
$.ajax({
url:'test.php',
type: 'GET', //Add the type
dataType:'json',
data: {'src': src}, //Add the data, leave it out the url
success:function(data){
alert(data)
}
});
Try this :
In Jquery :
var src="http://www.someonelinesite.com/file.swf";
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response.size);
}
});
In php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm sending some data from php through ajax to jquery.
If $content="ABC"; everything is OK. I get alert with ABC.
If $content="<div>ABC</div>"; then Houston has a problem. Nothing happens at all.
Here is PHP code
$json = json_encode(array("content" => $content));
echo $json;
And this is Jquery
$('#'+pic_type+'_form_n_'+pic_number).ajaxSubmit({
success: function(responseimage){
result = jQuery.parseJSON(responseimage);
alert(result.content);
Any ideas ?
UPDATE!
I've removed jQuery.parseJSON
so that line has only this code
result = responseimage;
And now I get the result in alert.
The result is the following
{"content":".<div>ABC<\/div>."}</div>
So we can see that JSON is not created well. I;ve tried utf8_encode and trim , but they do nothing to the result. result is strange.
PHP (and JSON) code seems fine, provided that the variable $content actually has any content. Else the PHP script will fail and there's your problem.
Did you define the dataType as "json" in the AJAX request?
$.ajax({
url: 'json.php',
dataType: 'json',
success:function(data){
console.log(data);
}
});
I think you just need to utf8_encode your response before doing json_encode.
Just change this :
$content = utf8_encode("<div>ABC</div>");
You are delivering invalid json somehow - please put your raw response in JSONLint, it will tell you what is wrong.
I have an odd problem regarding jQuery dataType.
I have a very simple PHP program that returns (echo's) an XML file (string). Looks like this:
$xmlFile = "sampleXMLFile.xml";
$xml = simplexml_load_file($xmlFile);
echo $xml->saveXML();
My client/javascript code calls the php program via ajax:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "myPHPFile.php",
dataType: "xml",
success: myCompleteFunction,
complete: mySuccessFunction,
failure: function(data) {
alert("Problem getting XML");
} });
});
The "myCompleteFunction" takes the XML and simply writes the first node into a div element, like this:
function myCompleteFunction(xml)
{
$(xml).find("Row").each(function()
{
$("#result3").append($(this).attr("myrow"));
});
}
OK - in IE 8, this works fine. In Firefox and Chrome I get no results. However, if I change the dataType to "html" I get correct results in Firefox and Chrome and then get no results in IE.'
Continue to go crazy with this. Do I actually need to put conditional logic for the browsers?
The dataType: option explained in the jQuery manual seems clear enough. I even tried to leave dataType out
(per manual: If none is specified, jQuery will try to infer it based on the MIME
type of the response)
I also tried multiple types - e.g. "text xml". No good.
Anyone ever run into this problem? Any direction would be appreciated.
Thank you.
p.s. I know I can read an XML file in jQuery. The resultant XML from the PHP program would be substantially more involved. I only used that as an example.
Updated:
Well, I saw Phil's comment about producing something before XML data sent. There was certainly nothing obvious. I removed a blank line above my first <?php line. This has somehow worked! Still seems odd to me. So my new, tighter PHP code is now:
<?php
// Load XML
$xmlFile = "sample.xml";
$xml = simplexml_load_file($xmlFile);
header('Content-type: text/xml');
echo $xml->saveXML();
?>
I will also pay mind to your other suggestion about properly handling jQuery.ajax() callbacks. Thanks.
I very much appreciate your help w/this!!
Stick with the "xml" dataType and add this to your PHP file before the echo...
header('Content-type: text/xml');
Also, you seem to be mixing up some of the jQuery.ajax() callbacks.
Use success to handle the returned data.
Use error(jqXHR, textStatus, errorThrown) (not failure) to handle HTTP errors
Use complete to execute some tasks after success and error callbacks have executed
ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})