I am making a web app, where I want to provide a search function. I am sending the searched name with an ajax request, and i want to pull the records of that particular person. But since there are many details that are to be displayed, I am finding it difficult to get the response. (I am not able to get more than one response at a time)
I want to know, if there is a way to get multiple responses for a single request, or a way to send all my variables in the target PHP file to the requesting javascript file as an array or something.
Thank you. If this question is asked before, please provide the link.
Use JSON as the datatype to communicate between PHP(Backend) and Javascript(Frontend). Example:
PHP
<?
$person = array("name"=>"Jon Skeet","Reputation"=>"Infinitely Increasing");
header("Content-Type: application/json");
echo json_encode($person);
?>
Javascript/jQuery
$.ajax({
url: "your_script.php",
dataType: "JSON"
}).success(function(person) {
alert(person.name) //alerts Jon Skeet
});
Add everything you want to an array, then call json_encode on it.
$data = array();
$data[] = $person1;
$data[] = $person2;
echo json_encode($data);
Related
I am trying to UPLOAD multiple file using Post jQuery method but I get an error of undefined index when trying to view the array result. Tried to search the answers but still unable to do it. What is the correct way to do this. Below are the example of my codes,
HTML
<input type="file" name="others[]" multiple="multiple">
jQuery
$(document).ready(function(){
$("#submit").click(function(){
var array = [$("input[name='others']").val()],
others = {
"upload[]": array,
},
id = $("input[name='id']").val();
$.post('updated-file-others.php',
{
others : others,
id : id
}, function(data){
$("#result_post").html(data);
});
});
});
PHP
if(isset($_POST['id'])){
$id = $_POST['id'];
$others = array($_FILES['upload']['name']);
}
echo "<pre>"; print_r($others); echo "</pre>";
A couple of things
$("input[name='others']") doesnt match others[] in your HTML. Why dont you use an id and match it?
You might need to ensure that you have
enctype="multipart/form-data" inside your form.
whats the output of $("input[name='id']").val(); You have not provided any clue in your code.
Refer to php documentation on file upload - Uploading multiple files
Refer to this stackoverflow question - Multiple file upload in php
I would suggest formatting your desired array as a JSON string, and then using php_decode to convert it to an array.
$json = '["apple","orange","banana","strawberry"]';
$ar = json_decode($json);
echo $ar[0]; // apple
More info about JSON with PHP can be found here:
http://www.dyn-web.com/tutorials/php-js/json/decode.php
The file upload via ajax using $.post doesn't work this way, to achieve this, you must configure the ajax call as follows:
$.ajax({
type: 'POST',
url: your_url,
data: new FormData($('#form-id').get(0)),
processData: false, //set it to false to send a DOMDocument, or other non-processed data
contentType: false //pass false to tell jQuery to not set any content type header
}).done(function (data) {
alert('success');
})
This will send you the entire form to the server, and there you can process the files and other fields as you want.
You can read a little more about the processData and contentType configuration in the jQuery ajax documentation
Please let us know if this work for you,
Greetings
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm working in a project and I'm stuck here, I don't know why I can't get the list from my database\
Here is my JAVASCRIPT
$(document).ready(function(){
$.ajax({
url:'datos.php?accion=ac',
success:function(datos){
for(x = 0;x<datos.length;x++){
//$("#PAIS").append("<option value='"+datos[x].id_pais+"'>"+datos[x].pais+"</option>");
$("#PAIS").append(new Option( datos[x].pais, datos[x].id_pais));
}
}
})
$("#PAIS").change(function(){
//var felix=$('#PAIS option:selected').val();
//alert(felix);
$.ajax({
url:'datos.php?accion=ad',
alert('hola22');
success:function(datos1){
console.log("hola");
for(x = 0;x<=datos1.length;x++){
//$("#PAIS").append("<option value='"+datos[x].id_pais+"'>"+datos[x].pais+"</option>");
$("#REGION").append(new Option( datos1[x].region, datos1[x].id_region));
}
}
})
});
})
And my functions.php:
<?php
$server="localhost";
$usr="root";
$passwd="";
$data="combo";
$db=mysqli_connect($server,$usr,$passwd,$data) or die ("Error en la conexion1");
$Accion = $_GET['accion'];
if($Accion=="ac"){
header('Content-Type: application/json');
$paises = array();
$Consulta = mysqli_query($db,"SELECT * FROM paises")or die ("Error en la conexion7");
while($Fila=mysqli_fetch_assoc($Consulta)){
$paises[] = $Fila;
}
echo json_encode($paises);
}
if($Accion=="ad"){
header('Content-Type: application/json');
$regiones = array();
$Consulta1 = mysqli_query($db,"SELECT * FROM regiones WHERE id_pais=4");//.$_REQUEST['id_pais']);
while($Fila=mysqli_fetch_assoc($Consulta1)){
$regiones[] = $Fila;
//echo json_encode($Fila);
}
echo json_encode($regiones);
}
?>
Well, my problem it's that I really don't know how the first really works :D, but when I'm calling url:datos.php=ad this block doesn't work :/
First, you will find it helpful to review these simple examples about AJAX. Do not just read them, copy them to your server and make them work. Change a few names or values -- see how they work.
AJAX request callback using jQuery
Next, here is a post that gives an overview to how PHP / web page / AJAX all work together. Take a few minutes and read it carefully. See if you can follow the logic. I bet the lightbulb will come on for you.
PHP - Secure member-only pages with a login system
Make your code as standard as possible. Don't take any shortcuts. Use the full $.ajax() structure, not the shortcuts of $.post() or $.get() (these are both shortcut forms of $.ajax(). Don't skip anything. As you get better, you can start to take some shortcuts. But for now, make sure your AJAX code block looks like this:
var var_value = $('#someElement').val();
$.ajax({
type: 'post',
url: 'your_ajax_processor.php',
data: 'post_var_name=' +var_value,
success: function(dataz){
if (dataz.length) alert(dataz);
$('body').append(dataz);
}
});
In your PHP, you will receive the value you posted in the $_POST array variable. If, in AJAX, you named your variable post_var_name (as we did in the example above), then that is how you access the contents:
$myVar = $_POST['post_var_name'];
When you are having trouble, a great idea is to put in some tests. (1) On the PHP side, comment out everything and at the top put in an echo command, like:
<?php
echo 'I got here';
die();
Back on the web page, in the AJAX success function, just alert what you get:
success: function(d){
alert(d);
}
At that point, you know two things:
Your AJAX -to- PHP communications are working, and
You see what value got passed over to PHP.
Then, you might do something like this
js/jQuery:
var var_value = $('#someElement').val();
$.ajax({
type: 'post',
url: 'your_ajax_processor.php',
data: 'post_var_name=' +var_value,
success: function(dataz){
if (dataz.length) alert(dataz);
$('body').append(dataz);
}
});
PHP:
<?php
$myVar = $_POST['post_var_name'];
//Now you can do something with variable `$myVar`, such as:
$out = '
<div class="red-background"> '.$myVar.' </div>
';
//This content is received in the AJAX code block using the variable name you specified: "dataz"
echo $out;
is this in french? lol, luckily it's still all code.
try this:
inside of your success(datos1) function replace datos1 with datos1.data. Ajax gives you the whole response, you just want the data from the response generally.
success:function(datos1){
console.log(datos1);
console.log(datos1.data);
for(x = 0;x<=datos1.data.length;x++){
//$("#PAIS").append("<option value='"+datos.data[x].id_pais+"'>"+datos.data[x].pais+"</option>");
$("#REGION").append(new Option( datos.data[x].region, datos.data[x].id_region));
}
I am using javascript to retrieve a bunch of values from the Riot API, however I want to store them in my own database using php. For example, I'm trying to store the gameID and this is what I'm trying right now.
<?php
$insrt = "INSERT INTO game (gameId)
VALUES (".<script>b.gameId</script>.")";
mysqli_query($dbc, $insrt);
?>
I'm pretty sure that I'm not even close to correct but I'm not sure how to do this.
You need to take a different approach. You can make an ajax call to a php script to do this for you. But the initiator will be javascript from the client side. Using jQuery(let me know if you can't), you can do
$.ajax({url: "insert_game_id.php", data: {gameId :b.gameId} });
and your php script
<?php
$gameId = $_POST['gameId'];
$insrt = "INSERT INTO game (gameId)
VALUES ($gameId)";
mysqli_query($dbc, $insrt);
?>
See jQuery Ajax POST example with PHP
I have a page with the following URL test.php?city=Paris and I have a php script (getData.php) which executes a SQL request and return a JSON object. To execute my request I need the parameter city in my URL. I call the getData.php script like this :
var ville = "<?php echo $_GET['ville']?>";
$.getJSON("bat/getData.php", {ville: ville}, function( data ) {
console.log(data);
});
I don't think that is the best way to send the URL parameter to my php script.
What do you think?
You should not echo arbitrary data into a script. You have opened yourself up to cross-site scripting attacks.
You can get around the problem by JSON-encoding your data, which is compatible with JavaScript.
var ville = <?php echo json_encode($_GET['ville']); ?>;
There is nothing wrong with passing parameters as part of the query string.
But implementing a little REST service is probably more elegant. Based on your current implementation the REST service would provide the following resources:
GET /cities/{cityname}
Example:
GET /cities/paris
So I half got jQuery's ajax ($.post) to work. But, for some reason, I haven't been successful with finding the right online article to explain to me how PHP retrieves the ajax data that is sent. I've found some stuff on json_decode, but upon me doing that to basically decode it, it wont work (and yes, I am using json for the $.post command).
Here is my javascript code
$.post("notificationNum.php", {"user":"1"},
function(data){
$(".example-number").html(data.amount);
}, "json");
Here is my PHP code
<?php
session_start();
//link to db info here
$user_id_got = json_decode($_REQUEST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>
Mind you all, I've also tried using the $_POST command instead of the $_REQUEST. Any ideas how to send data to the PHP file so I can use it?
"json" in your jQuery call is how your php should write its output, not how jQuery sends it. Use normal $_REQUEST in your php:
$user_id_got = $_REQUEST['user'];
try this
notificationNum.php
<?php
//link to db info here
$user_id_got = intval($_POST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>