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);
});
Related
Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.
I need to pass list of strings from multiple select to the controller. Though the requirement looked very simple to me, I was breaking my head for the past hour in this. I have did a fair research on this, but unable to succeed.
Below is my Javascript code. Please ignore the comments. I was successfully able to fetch the list of items in the multiple select. While i do the ajax call, I get the error "Object reference not set an instance of an object.
function submitForm() {
var selected = $('#selectedTasks option').map(function(){
return this.value
}).get()
var postData = { selectedTasks : selected } //corrected as suggested
//selectedTasks = JSON.stringify({ 'selectedTasks': selected });
alert(postData);
$.ajax({
type: "POST",
//contentType: 'application/json; charset=utf-8',
url: '#Url.Action("AssignTasks", "MonthEndApp")',
dataType: 'json',
data: postData,
traditional: true,
success: function (data) {
alert("Success");
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
MonthEndAppController.cs
[HttpPost]
public void AssignTasks(List<String> selectedTasks)
{
//do something
}
Can someone guide me where exactly I have gone wrong? Can someone suggest me what is wrong?
EDIT : As suggested by Mr. Rory I have made the java script changes. Now the Java script part works absolutely fine. But the Controller is not getting called when the ajax request is made. Can someone help me out if something wrong in the call made to controller ?
Have you tried with string[] instead of List<String> ?
The parameter your AssignTasks action is expecting is called selectedTasks, not values:
var postData = { selectedTasks: selected };
Also note that when debugging anything in JS you should always use console.log() over alert(), as the latter coerces all types to a string, which means you're not seeing a true representation of the actual value.
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 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.
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