i'm trying to send an js object to a php function using jquery.ajax.
This is what i have so far:
js side:
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: {persoon : persoon2},
async: false,
success: function(){
alert(data);
return true;
}
});
php side:
$decode = json_decode($_GET["persoon"]);
$verzekering->setVoornaam($decode->persoon_voornaam);
in js this works: persoon2.persoon_voornaam
but i can't get to the value in php, what am i doing wrong?
few fixes
data: "persoon=persoon2", // check input format
success: function(data) { // missing data argument
EDIT your ajax code is working (check URL or php code)
http://jsfiddle.net/ish1301/KZndE/
Found the problem(s)
I was using this inside Drupal and the Jquery version was still 1.2.6. Upgrading it resolved a lot of the problems
The string i tried to catch with the $_GET["persoon"] was mall formated becaus i just send along a js object. Changing
data: {persoon : persoon2},
to
data: {persoon:JSON.stringify(persoon2)},
fixed the problem
Related
I am trying to get a jQuery variable to a PHP variable. I have looked it up but can't find a solution. I have the following jQuery:
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success');
}
});
When I console.log te "eventID" it correctly displays the number.
My PHP code is in the index.php. This is also where the .eventRow class is.
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
However nothing happens. The console.log just displays: "Number: " Is there something wrong with the code? Thanks for your help!
EDIT: Could it be the problem that the index.php is already loaded before I click on the button? Because this php code is in the index.php and thus the $phpEventId is not yet set.
In your Ajax, the type: "POST" is for jQuery prior to 1.9.0. If you're using the latest jQuery, then use method: "POST".
If you're using the latest jQuery and you don't specify method: "POST", then it defaults to method: "GET" and your PHP needs to capture it with $_GET['phpEventId'];.
After reading your update, let's try one thing. Change your PHP to return something meaningful to Ajax:
<?php
$phpEventId = $_POST['phpEventId'];
echo $phpEventId;
?>
Then try to capture the PHP response in your Ajax:
$.ajax({
url: "index.php",
method: "POST",
data: {'phpEventId': eventID },
success: function (result) {
alert("result: " + result);
}
});
This is just a part of your code, and the problem is somewhere else. In this context your code works just fine:
<div class="eventrow" id="1">This</div>
<div class="eventrow" id="2">That</div>
<script>
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index-1.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success: '+eventID);
}
});
});
</script>
With the matching index-1.php:
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
Not sure though why do you print javascript code (console.log) into an ajax response here...
Error Is Visible Even Here
According to WebZed round statistic report, this error was visible over 84% of web-developers.
Failed to post data to PHP via JQuery while both frameworks and codes were updated.
Possible Solutions Available Today
Try using other methods for posting because JQUERY and AJAX libraries are not as efficient as shown in the surveys.
New frameworks are available which can do better with PHP.
Alternative method is to create a post request via $_GET method.
Regular HTML5 supports <form></form> try method="post". For security reasons try using enctype="" command.
Try using React Native https://nativebase.io/
I'm trying to implement a custom suggestion engine using jquery.
I take the user input, call my codeigniter v2 php code in order to get matches from a pre-built synonyms table.
My javascript looks like this:
var user_str = $("#some-id").val();
$.ajax({
type: "POST",
url: "http://localhost/my-app/app/suggestions/",
data: {"doc": user_str},
processData: false
})
.done(function (data)
{
// Show suggestions...
});
My PHP code (controller) looks like this:
function suggestions()
{
$user_input = trim($_POST['doc']);
die("[$user_input]");
}
But the data is NOT posted to my PHP :( All I get as echo is an empty [] (with no 500 error or anything)
I've spent 2 days looking for an answer, what I've read in SO / on google didn't help. I was able to make this work using GET, but then again, this wouldn't work with unicode strings, so I figured I should use POST instead (only this won't work either :()
Anyone can tell me how to fix this? Also, this has to work with unicode strings, it's an important requirement in this project.
I'm using PHP 5.3.8
Try using the $.post method, then debug. Do it like this:
JS
var user_str = $("#some-id").val();
var url = "http://localhost/my-app/app/suggestions";
var postdata = {doc:user_str};
$.post(url, postdata, function(result){
console.log(result);
});
PHP
function suggestions(){
$user_input = $this->input->post('doc');
return "MESSAGE FROM CONTROLLER. USER INPUT: ".$user_input;
}
This should output the message to your console. Let me know if it works.
For those interested, this works for me, even with csrf_protection being set to true
var cct = $.cookie('csrf_the_cookie_whatever_name');
$.ajax({
url: the_url,
type: 'POST',
async: false,
dataType: 'json',
data: {'doc': user_str, 'csrf_test_your_name': cct}
})
.done(function(result) {
console.log(result);
});
I am trying to write a script that allows posting to a JSON file. For some reason the process is succeeding, but the JSON file isn't being written to.
Here is my jQuery code:
$(function() {
var data = {
name: 'cool',
drink: 'cool2',
};
$.ajax({
type: "POST",
url: '/api/orders',
dataType: 'json',
async: false,
data: JSON.stringify(data),
success: function() {
alert("Thanks!");
}
})
});
Here is my JSON code (/api/orders)
[
{"id":1,"name":"Ben","drink":"Americano w/ Creme"},
{"id":2,"name":"Ben2","drink":"Americano w/ Creme2"},
{"id":3,"name":"Ben3","drink":"Americano w/ Creme3"}
]
I can't figure out why Chrome is saying it is succeeding, but the code isn't posting to the JSON file.
The problem isn't with your JavaScript. The JSON.stringify just concerts the data to a JSON string and passes it to the url. Your problem will be in the Url that it is posted to /Ali/orders. That looks like a directory to me instead of an API to handle the string. I could be wrong in that as certain technologies hide that stuff. Still you need to look at where the data is going to.
Stuck on the first stage of a big project. I am trying to display the JSON value that I get from URL shown below. It shows the data when I past the URL on the a browser. But when I put the URL in variable and try to show in html it doesn't show the phrased value.(I will delete the app/key one I get the solution.) Thanks in advance.
http://jsfiddle.net/rexonms/6Adbu/
http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=72157629130565949&per_page=10&page=1&api_key=ccc93a20a1bb9060fa09041fa8e19fb5&jsoncallback=?
Have you tried using the $.getJSON() or the $.ajax() method? This seems to return the data just fine:
$.getJSON(apiCall, function(data) {
console.log(data);
});
Here's a working fiddle.
Additional Information
It seems like you may benefit from a simple tutorial that explains AJAX in relation to jQuery's $.getJSON() and $.ajax() methods.
$("<span>").html(apiCall)
apiCall is a string (containing the URL). All you're doing here is setting a span to have the URL as its content. You need to actually use AJAX to load said URL.
$.ajax({
url: 'http://api.flickr.com/services/rest/',
dataType: 'jsonp',
type: 'GET',
data: {
format: 'json',
method: 'flickr.photosets.getPhotos',
photoset_id: '72157629130565949',
per_page: 10,
page: 1,
api_key: 'ccc93a20a1bb9060fa09041fa8e19fb5'
},
jsonp: 'jsoncallback',
success: function(data){
console.log(data);
}
});
Inside success, data is the JSON object returned by the API.
I wrote a function in jquery and it works perfectly on localhost with the same setting
$('#resumey_graduation_add').live("click",function(){
var dataString=$('#job_form').serialize();
$.ajax({
type: 'GET',
url: 'app.php?name=job&op=resumey_graduation_add',
data: dataString,
cache: false,
beforeSend: function() {
$("#resumey_graduation_showall").html("<img src='images/loading.gif' />");
},
success: function(data2) {
$("#resumey_graduation_showall").html(data2);
}
});
return false;
});
but when moving it on my host , its not working and failed to load the data .
loading shows but not the result !
jquery versions are all tested and none of them worked
is there anything wrong , for expample not having JSON enabled or these things that are related to serialize() in jquery ?!
Since you are doing
type= get , data= $('#job_form').serialize(), url=Someurl.php?a=b&c=d
your url must be getting converted to
Someurl.php?a=b&c=d&props_from_form(name value pairs)
Do this way
$.ajax({
type: 'POST',
other things ....
sending form through GET may result in very big urls and that may get ignored by server.