so I'm doing a basic assignment for uni, they asked us to use ajax and php to create a text input that validates the name and email plus a live search bar, all this without using db. So I have the html already set up, the .php with 3 different arrays with names, emails and news stored in and a main.js that already displays whatever you type in the text input in the console with the keyup event trigger. I just can't figure out a way to make an ajax request to compare what you type in to the info stored in the arrays.
In the arrays.php I have this :
*$classes = array('1' => 101, '2'=> 102, '3'=>103 );*
*$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');*
*$news = array('Title'=>array('El papa muere', 'Argentina gana el mundial', 'Fondos buitres cancelados' )'Noticia'=>array('noticia1', 'noticia2', 'noticia3')
);*
and in the main.js I have something like this:
$('#name').keyup(function(){
var name=$(this).val();
console.log(name);
that retrieves what I type in each text field. As far as I can remember, the prof wrote something like this to give us a hint:
$.ajax({
url: ' ',
type: ' ',
success:function(data){
}
}):
But I just can't figure it out so any help would be much appretiated!
The general idea is to pass the current value of the search box to your PHP script via ajax. Then in your PHP script, you would filter your options based on the current value passed to it and return a filtered response. The javascript would then take the filtered response and output it on the page.
People usually use JSON as a format for passing information between Javascript and PHP.
To give you a little better understanding what $.ajax does. It will make a request to your server and then process the results. The parameters specified do the following:
url: The URL to request
type: The format of the response (eg. text, xml, json, etc.)
success: A callback to be called when the response comes back from the response.
Also note that the A in AJAX stands for asynchronous. This is why you need to give the $.ajax function a callback. Due to the nature of HTTP, you make a request and the response can return right away or in 30 seconds or never. When the response returns the callback will execute. It is not linear. Therefore the callback can execute after code below the the $.ajax call depending on how long it takes for the response to come back.
Maybe take a look at the example below to give you a better idea of how to do this:
<?php
$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');
$result = array();
foreach($names as $name)
{
if (strpos($name, $_GET['name']) !== false)
{
$result[] = $name;
}
}
echo json_encode($result);
?>
And the javascript
$('#name').keyup(function() {
var name=$(this).val();
$.ajax({
url: '?name=' + name,
type: 'json',
success: function(data) {
console.log(data);
// add data to results
}
}):
});
Related
Im trying to send an array to the PHP script:
usedAnswers = [1,2];
// funtion for displaying a question
displayQuestion = () => {
$.ajax({
url: "backend/retriveData.php",
data: {usedAnswers:usedAnswers} ,
type:"post",
success: function(response) {
console.log(response);
}
});
}
// inital display of question
displayQuestion();
Then when I want to access the array in the PHP script
<?php
echo print_r($_POST['usedAnswers']);
?>
I get the following problem on screen
Why is he adding an extra 1 ?
When I try to access the first element of the Array like this:
echo print_r($_POST['usedAnswers'][0]);
He console.logs me the number 11?
What am I doing wrong what is the correct way to send an Array via Ajax?
Is it also possible to send a set via Ajax?
so, based on your comments, it appears your question is really referring to how to send data through, rather than the odd output you're getting, which Jay has already answered for you.
as far as your code reads, what you're actually sending is this:
{[1, 2]:[1, 2]}
which is invalid JSON.
if you're trying to actually have a 'usedAnswers' key (which it looks like from your php), then you need to do this:
$.ajax({
url: "backend/retriveData.php",
data: {'usedAnswers':usedAnswers}, // <-- note the quotes around the key
type:"post",
success: function(response) {
console.log(response);
}
});
Because you are echoing the print_r() (which in and of itself is a type of echo) you're returning a value for the truthiness of the print_r(). Change the line to this
print_r($_POST['usedAnswers']);
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
In basic terms I am trying to make a cross domain AJAX call using JSONP. The JS and PHP files need to be on a different domain. I can't seem to get the returned data back to the original function.
To explain how the page works. A user will enter something into an input box. e.g. Surname.
Input and search.
After the user clicks search a the searchClick() function is called. This function takes the text the user has inserted into the input box and calls another function called getInfo().
function searchClick() {
var jsonOfData = getInfo($('#searchInput').val());
console.log(jsonOfData );
}
The getInfo() function has to be in a JS file on a different domain.
function getInfo(surname) {
$.ajax({
url: "https://www.otherdomain.com/api/lookup.php",
dataType: 'jsonp',
crossDomain: true,
data: {
surname: surname
},
success: (data) => {
console.log(data); // This works
return data; // This doesn't
}
});
}
This ajax call goes off to my PHP page and does a search on the database. It then created a JSON array and sends it back. From my research instead of ending the file with the usual echo json_encode($array); I ended the file with:
echo $_GET['callback'] . "(" . json_encode($responseArr) . ")";
This is the point at which I have my problem. As you can see, in the AJAX success function, the data is successfully displayed and logged to the console but I can't return it back to the original jsonOfData variable.
I hope this makes sense and i'll be so thankful to anyone who can help me out.
What you're trying to do won't work, because the $.ajax calls works asynchronously.
Instead of work with the return of the function call at this point:
var jsonOfData = getInfo($('#searchInput').val());
Try to build your logic inside the success function of your $.ajax call.
Does anyone know how pass form values into PHP and still return the data to JavaScript? (For use in Google Charts if anyone is wondering.)
I have an HTML form with 4 radio boxes. I'd like to pass the value of the form so that my PHP request will be modified based on the user's selection.
The results from the PHP request need to be passed to JavaScript for processing.
In the radio button on click event place a javascript function that will perform an XMLHttpRequest to the php page and have the PHP page echo some JSON content that can be decoded in the return of the XHR in Javascript.
Example of such
May this can help you.
I think that you must do an Ajax request
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( data) {
alert( "Data Saved: " + data);
});
You send data to server form your form (here sent are name and location). You read this data with javascript with OnSelect and transfert it to your PHP code and,
You get back data from server into your JavaScript code and you can do what you want with it.
Sorry if my solution use JQuery, it is better for cross-browser with less code writing !
You could use this line to parse an array into json and use it later in javascript:
json_encode($rows); //format array named $rows into json data
More info: http://php.net/manual/en/function.json-encode.php
I am trying to pass a javascript variable which I get when a button is clicked to php and then run a mysql query. My code:
function ajaxCall(nodeID) {
$.ajax({
type: "POST",
url: "tree.php",
data: {activeNodeID : nodeID},
success: function(data) {
alert("Success!");
}
}
);
}
function onButtonClick(e, data) {
switch (data.name) {
case "add":
break;
case "edit":
break;
case "delete":
nodeid = data.context.id;
ajaxCall(nodeid);
//query
break;
}
}
<?php
if (isset($_POST['activeNodeID'])) {
$nodeid = $_POST['activeNodeID'];
}
else {
$nodeid = 0;
}
?>
I haven't done this before, so I am not sure why this doesn't work. Any suggestions?
EDIT: Maybe I haven't explained myself well enough. I realise that php is server side and javascript is client side. I have an org chart that is displayed using javascript based on all the info is saved in my db. What I need to do is: when one of the javascript buttons is clicked (edit, delete, add) get the ID of the active node and use it as variable in php to run query. For example, delete the row in the db. What's the best way to do it?
There's a bit of confusion here, the success value stores a callback that gets called when the Ajax call is successful. To give you a simple example, let's say you have an Ajax call like this:
function ajaxCall(nodeID) {
$.ajax({
type: "POST",
url: "tree.php",
data: {activeNodeID : nodeID},
success: function(data) {
console.log(data.my_message);
}
});
This calls a PHP page called tree.php. In this page you do some computation and then return a value, in this case as JSON. So the page looks like this (note that I'm keeping it simple, you should validate input values, always):
$v = $_REQUEST['activeNodeID'];
$to_return = "the value sent is: " . $v;
return json_encode(array('my_message' => $to_return));
This simple PHP page returns that string as a JSON. In your javascript, in the specified callback (that is success), you get data as an object that contains the PHP's $to_return value. What you have written does not really makes sense since PHP is a server language and cannot be processed from the browser like JavaScript.
I don't understand how the success function works in a $.ajax call with jquery.
for instance
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
useReturnData(data /* ??? not sure how to use the data var */ );
}
};
ajax.php:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
?>
how do i use that data within the success function? No where seems to explain what the data parameter is, they just seem to use it ambiguously.
another side question, is the data: "function=1" related to the data as a parameter for the success function?
The data variable contains the output of your php file, so if in your php file you do:
echo "<p>success</p>";
data will contain <p>success</p>.
In your example you would change your php file to:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
// other stuff...
echo $string;
?>
The content of the data parameter depends on the type of the response. If the Content-Type is application/json, then it's parsed as JSON. If it's text/html or similar, the content is HTML. In your case, it looks like you're returning text. If you make your Content-Type header text/plain or similar, then data should just be a string.
To answer your second question, the data property for the Ajax request is something different; it specifies the request data that is sent. In other words, it's the query string if you have a GET request, and the post "form" variables if it's a POST request.
data is whatever is returned by the server side script, so in this case it would be
this is the data i want to return and use
Providing the if() condition is met.
Nobody really says what data contains because it can contain various different things, although it's always a string. Sometimes it's HTML, sometimes it's JSON and sometimes just a return message.
In your case, data will just be a string providing you echo the string out in your server side script.
The easiest way is to load the data into some placeholder element (div?)
E.G.
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
$('div.selector').load(data);
}
};