I'm learning js and jquery. I will post values as array with jquery ajax and in php code I will use it with foreach loop.
<select name="passenger['+i+'][nationality]">
<option value="GRE">GRE</option>
...
</select>
<input name="passenger['+i+'][gsm]" value="">
I have a form like that (for example). In php code I will use this names like that :
$passengers = $_POST['passenger']
foreach ($passengers as $i => $passenger) {
echo $passenger['nationality'] . '<br>';
echo $passenger['gsm'] . '<br>';
}
But to use in php I must post with jquery ajax. But I cant get array passenger with jquery to post as passenger array.
JS CODES
I need a passenger variable.
jQuery.ajax({
url: link,
type: "POST",
data: {passenger : passenger},
dataType: "json",
success: function(s) {
},
error: function() {
}
});
You can use serialize to get all the values within a form. So your JS can be:
$.post( link , $( "#testform" ).serialize() , function() {
alert('Succes');
});
Related
I have a Leaflet map, and a text input. I want to take the address from the textbox, run it through a PHP script, and get the result all through jQuery.
Here is my form:
<form id="mapcheck" method="POST" action="geo.php">
<input id="largetxt" type="text" name="checkAddress">
<input id="button" type="submit" name="submit" value="Check">
</form>
Here is part of the PHP:
<?php
if (isset($_POST["checkAddress"])) { //Checks if action value exists
$checkAddress = $_POST["checkAddress"];
$plus = str_replace(" ", "+", $checkAddress);
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=GMAPSKEY');
$obj = json_decode($json);
$mapLat = $obj->results[0]->geometry->location->lat;
$mapLng = $obj->results[0]->geometry->location->lng;
$coords = ('' . $mapLat . ', ' . $mapLng . '');
return $coords;
}
?>
And the jQuery:
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largetxt").val()
},
success: function(response){
console.log(response);
}
});
});
});
I need to listen on submit of the form via jQuery (NOT PHP), run it through a geocode script, then take that result and put it through regular JavaScript (Leaflet map.) I have played around with the AJAX feature of jQuery to no avail. There is a very simple solution to this, but I have not figured it out.
UPDATE: Problem resolved, thanks Vic.
You would need AJAX. Remove the form element but keep the inputs.
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largeText").val()
},
success: function(response){
console.log(response);
//your script
}
})
});
I have a ajax function that would retrieve data from my database and display it in my textbox. I am using a JQuery Form Plugin to shorten the ajax process a little bit. Now what I want to do is to get the data back from the php script that I called from the ajax function.
The form markup is:
<form action="searchFunction.php" method="post" id="searchForm">
<input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
<input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>
Server code in searchFunction.php
$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);
return $row;
The ajax script that processes the php is
$(document).ready(function() {
$('#searchForm').ajaxForm({
dataType: 'json',
success: processSearch
});
});
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
In PHP, if I want to call the data, I would just simply create a function for the database and just for example echo $row['username'] it. But how do I do this with ajax? I'm fairly new to this so, please explain the process.
$('#Search').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/<SolutionName>/<MethodName>",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: processSearch,
});
});
function processSearch(data) {
var username= ($(data).find('#username'));
}
Change the input type submit to button. Submit will trigger the action in the form so the form will get reloaded. if you are performing an ajax call change it into button.
Everything seems to be fine, except this bit -
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
You need to change it to -
function processSearch(data) {
// data is a JSON object. Need to access it with dot notation
alert(data.username);
}
UPDATE
You also need to return a JSON response from your PHP file. Something like -
// Set the Content Type to JSON
header('Content-Type: application/json');
$data = [
"key" => "value"
];
return json_encode($data);
In your case you can directly encode the $row like so -
return json_encode($row);
I'm trying to send a JavaScript variable to a php script using ajax. This is my first time using ajax and I don't know where I went wrong. Here's my code
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
dataType: "script",
data: { "selected_category" : v}
}).done(function() {
window.location.href = "http://mywebsite.com";
});
}
All help is appreciated
Here's the HTML
<ul class="cat">
<li class="opt" onclick="selectcat('option1')">option1</li>
<li class="opt" onclick="selectcat('option2')">Option 2</li>
</ul>
This is the ajax php file
<?php
session_start();
$ctgry = $_GET['selected_category'];
$_SESSION['select_cat'] = $ctgry;
?>
You need to remove dataType: "script" since you are just sending data. Do it like this:
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
data: {"selected_category": v}
}).done(function(result) {
console.log(result);
//window.location.href = "http://mywebsite.com";
});
}
Hi this is what I do to call an ajax request
You can post data or load a file using following code:
$("#button click or any other event").click(function(){
try
{
$.post("my php page address",
{
'Status':'6',
'var one':$("#myid or .class").val().trim(),
'var 2':'var 2'
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax request you
//can send any type of data whether json or or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
I hope this help!
AJAX is easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#divID').click({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.
Your example could be changed to look something like:
HTML:
<ul class="cat">
<li class="opt" value="TheFirstOption">option1</li>
<li class="opt" value="The Second Option">Option 2</li>
</ul>
javascript/jQuery:
$('.opt').click(function(){
var v = $(this).val();
$.ajax({
type: "POST",
url: "myurl.php",
dataType: "html",
data: { "selected_category" : v}
}).done(function(data) {
$('#div_to_insert_the_response').html(data);
});
});
PHP:
<?php
$val = $_POST['selected_category'];
echo 'You selected: ' . $val;
dataType: "script" has no sense here, I think you want json or leave it empty.
Your PHP script should work if you try to get the variable with $_GET['selected_category']
I suggest you this modification to help yourself for debugging
$.ajax({
type: "GET",
url: "myurl.php",
data: { "selected_category" : v},
success: function(data){
console.log(data);
// you can also do redirection here (or in complete below)
},
complete: function(data){
// when request is done, independent of success or error.
},
error: function(data){
// display things to the user
console.error(data);
}
})
I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});
Update: Got this working by disabling CodeIgniter Profiler which was interfering with the Ajax success response. I think it adds a div to the JSON response.
I am trying to populate a dependent select box with data from mysql database. The problem is that the dependent select box is not getting populated in spite of getting data in the correct format in response to Ajax request.
Please help me as I am totally clueless about what's happening here. Below is my JavaScript code.
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
$("#cities > option").remove();
var form_data = {
country: $('#country').val(),
csrf_token_name: $.cookie("csrf_cookie_name")
};
$.ajax({
type: "POST",
url: "http://localhost/outlets/get_cities",
data: form_data,
dataType : "JSON",
success: function(cities)
{
$.each(cities,function(id,name)
{
var opt = $('<option />');
opt.val(id);
opt.text(name);
$('#cities').append(opt);
});
}
});
});
});
</script>
And here is the HTML. I am using Codeigniter.
<form id="form">
<?php $cities['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</form>
Here is the controller:
function get_cities(){
$country = $this->input->post('country');
$this->load->model('city');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->city->get_cities($country)));
}
& the Model:
function get_cities($country = NULL){
$this->db->select('id, name');
if($country != NULL){
$this->db->where('countries_id', $country);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->name;
}
return $cities;
}else{
return FALSE;
}
}
Change your ajax success callback to:
success: function (cities) {
for (var id in cities) {
var opt = $('<option />');
opt.val(id);
opt.text(cities[id]);
$('#cities').append(opt);
}
}
Because your ajax result is not a array but an json object.
Alright everyone, I managed to get this working by disabling CodeIgniter Profiler. Codeigniter profiler, that otherwise is a handy tool, breaks javascript on any page with Ajax. If you can't do without profiler, use the solution provided on Making CodeIgniter’s Profiler AJAX compatible