I'm trying to POST a variable through a select box, which will submit the data through AJAX and then I need to be able to use that variable on the original page, which updates the SQL queries.
Here is the code I have got so far:
<script type="text/javascript">
function selectCategory() {
document.getElementById('categoryText').addEventListener("change", function() {
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","/category.php?category3="
+document.getElementById("categoryText").value, false);
xmlhttp.send(null);
});
}
</script>
and the AJAX (which I'm struggling with)
<?php
/*Retrieving the Value from the select box */
$categoryFilter = $_GET['category3'];
?>
When you say "select box" do you mean a select menu - ie: dropdown? If that is the case then generally you access the value of the selected element like this:-
var oSel=document.getElementById("categoryText");
var value=oSel.options[ oSel.options.selectedIndex ].value
<script type="text/javascript">
function selectCategory() {
var oSel=document.getElementById('categoryText')
oSel.addEventListener("change", function() {
var xmlhttp=new XMLHttpRequest();
xmlhttp.open( "GET", "/category.php?category3="+this.options[ this.options.selectedIndex ].value, false );
xmlhttp.send(null);
}.bind( oSel ) );
}
selectCategory.call( this );
</script>
Maybe:
data=[];
data.push({name: 'category3', value: checked/unchecked });
$('.submit').click(function() {
$.ajax({
type: 'POST',
url: 'your php page url',
data: formData,
success:function(data){
// successful request; do something with the data
alert(data);
},
error:function(){
// failed request; give feedback to user
alert("error");
}
});
});
and in PHP:
$categoryFilter = $POST['category3'];
Related
i am creating two ajax functions one in the traditional method and one with jquery. but when i do this the traditional method gets called first and in return i dont get some of my desired outcomes. how can i make the traditional ajax method to be translated into jquery?
here is my traditional ajax method:
function countFollowers() {
var xmlHttp = GetXmlHttpObject();
var url = "checkFollowers.php?username=" + document.followForm.follow_id.value;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var r = xmlHttp.responseText.trim();
if (r != "error") {
document.getElementById('followersCount').innerHTML = xmlHttp.responseText;
error = true;
return false;
}
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
if (error == true) {
return false;
}
}
here is my jquery ajax:
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow=" + follow_id,
success: function(data) {
}
});
});
});
here is what i come up with so far to make the two ajax functions in the same on click function:
jQuery(document).ready(function($){
$('.msg-icon').on('click', function(e){
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow="+follow_id,
success: function(data) {
}
});
$.ajax({
data: follow_id,
type: "post",
url: "checkFollowers.php?username="+follow_id,
success: function(data) {
}
});
});
});
but it is still not executing the response text that is coming from my php file
php code:
<?php
include("functions.php");
include("session.php");
require("connection.php");
if(isset($_GET['username'])){
$username =$_GET['username'];
$result= $db->prepare("SELECT * FROM users WHERE username=?");
$result->bindValue(1,$username);
$result->execute();
$row = $result->fetch();
if($result){
echo "Followers </br>". $row["followers_count"];
}
else{
echo "error";
}
}
?>
how will i get it to echo the $row["followers_count"] inside my span element?
You said in the comments you wanted to run the two requests sequentially instead of in parallel. Here's an all-round better way to organise your code which both allows that, and makes the code more re-usable, more maintainable and testable, and easier to understand in general.
I've used the Promise/Deferred interface provided by jQuery and AJAX as the way to chain the requests in sequence. Notice how each call is separated into each own function (so it's re-usable), but that function returns the Deferred object from the AJAX request, so you can use it to do something else when the request finishes.
Also based on your PHP I think the call to checkfollowers needs to be a GET (because PHP checks $_GET for the input value, and that's what your original XHR call was), and also you need to set the data with an explicit "username" parameter name so it'll be recognised.
It's not clear whether your call to followingsystem.php is correct or not because I can't see the PHP code for it.
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
var request = follow(follow_id); //run the initial request, get back the Deferred object representing that request.
request.done(function() { //when the first request is done, run the second one.
checkFollowers(follow_id);
});
});
});
function follow(follow_id) {
return $.ajax({
data: { follow: follow_id},
type: "post",
url: "followingsystem.php?follow=" + follow_id
});
}
function checkFollowers(follow_id) {
return $.ajax({
data: { username: follow_id },
type: "get",
url: "checkFollowers.php",
success: function(data) {
document.getElementById('followersCount').innerHTML = data;
}
});
}
I want simply to send an element via a event so that to catch it as a parameter in a servlet, but NOT from the regular Form's button.
I would appreciate a suggestion.
<script>
$(document).ready(function () {
$('#idSelect').change(function () {
$.post("SelectChange",$('#idSelect'), function () {
});
});
});
</script>
Like so, capture the value on change, then send it to the php file.
Access in the PHP with $_POST['select_data'];
$(document).ready(function () {
$('#idSelect').change(function () {
var select_value = $("#idSelect").val();
$.ajax({
type: "POST",
url: '/var/www/file-receiving-data.php',
data: ({ select_data: select_value}),
success: function(data) {
console.log("successfully sent to php file");
}
});
});
});
So, with the 1st answer (without which no chance to get it), til fix the other simpler permanently, the working solution is:
In servlet:
String val = request.getParameter("val");
In jsp, append the value to the url, as follows:
<script>
$(document).ready(function () {
$('#idSelect').change(function () {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "SelectChange?val="+$('#idSelect').val(), true);
xhttp.setRequestHeader("String", "application/x-www-form-urlencoded");
alert("send de POST: "+$('#idSelect').val());
xhttp.send();
});
});
</script>
this is the js code, ajax has two arguments, the first is url, 2nd is a object which contains type data and onsuccess. (I didn't use jQuery but the function I define myself, the code is at the end of the question)
I just want to send the 'text' string to php, so is there any problem to do like this? I also have tried change the data to data: {searchinput:"text"}, but still don't work.
ajax(
'http://localhost/test.php',
{
type: 'POST',
data: "searchinput=text",
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
this is the php code, sorry for changing the code wrong while pasting it on.
$searchinput = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
then the error is
Undefined index: searchinput
I have search some method like change onsuccess function to setTimeout, and do ajax again, but it doesn't work, just send the data again but the php still can't get the data
this is the ajax function
function ajax(url, options) {
if (!options.type) {
options.type = "post"
};
var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true);
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
options.onsuccess(xhr.responseText, xhr)
} else {
options.onfail(xhr.responseText, xhr);
}
};
}
}
Well, since you used the ajax wrong, I'm not surprised. There should be a error in the console.
jQuery AJAX is used like this:
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
url is a part of the object the ajax expects, so it needs to be inside and not outside of it. Also, data is expecting another object, you gave it a plain string.
Also, as #Muhammad Ahmed stated in his answer, you are using a wrong variable in your php code.
Edit: AJAX in JavaScript without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/test.php', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// worked
var data = JSON.parse(this.responseText);
} else {
// failed
}
}
};
request.send();
request = null;
$searchcon = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
In This code there is a mistake on ist line you are using variable $searchcon
and on query you are using $searchinput change ist varaible name to $searchinput instead of $searchcon. and also change your ajax code.
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseTxt, xhr) {
console.log(responseTxt);
}
}
);
send data value like below and use print_r($_POST) on php page to see values are coming or not
$.ajax(
{ url: 'test.php',
type: 'POST',
data:{
searchinput:text
},
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
Try with this code you were using ajax in wrong manner. You can learn more about how ajax works and how to code for ajax over http://api.jquery.com/jquery.ajax/
$.ajax(
{
type: 'POST',
url : 'http://localhost/test.php',
data: {searchinput:text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
and within your PHP file you need to update your typo i.e. you were getting value of your POST in $searchcon variable
$searchcon = $_POST["searchinput"];
^^^^^^^^^^
and within your query you were using
$query = "select * from text where data like'".$searchinput."%' ";
^^^^^^^^^^^^^^
it should be like
$query = "select * from text where data like'".$searchcon."%' ";
^^^^^^^^^^
Try this code :
var other_data = $('form').serializeArray();
$.ajax({
url: 'work.php',
data: other_data,
type: 'POST',
success: function(data){
console.log(data);
}
});
or
you can also pass the data in url also.
Try the code which suits your requirement.
$.ajax({
url: 'work.php?index=checkbox&action=empty',
type: 'POST',
success: function(data){
console.log(data);
}
});
I am new to php and codeigniter. The problem is when i click on search button it doesn't get text box data. i put alert to get show text box data in ajax but it show me {"data":false}
This is the view
<form action="/index.php/search/define" method=GET>
Word: <input type=text id="textbox" name="result1" onkeyup="demo(this.value);" />
<input type="button" name="all" id ="btnclicksearch" value="Search" />
<div id="mydiv"></div>
</form>
<script language="javascript" src="/site/assets/themes/default/js/demo.js">
This is the js file
var xmlhttp;
function demo(t)
{
// note - this doesn't work in IE browsers - surprised?
xmlhttp = new XMLHttpRequest();
// now build the URL of the server-side resource we want to
// communicate with
var url = "/site/index.php/search/returnsearchresults?t=" + t;
xmlhttp.onreadystatechange = myfunc;
xmlhttp.open("GET",url);
xmlhttp.send();
}
$('#btnclicksearch').click(function () {
var url = "/site/index.php/search/returnsearch" ;
$.ajax({
url: url,
type: 'POST',
data: $("#textbox").val(),
dataType: "text",
cache:false,
success: function (data) {
alert(data);
$('#mydiv').html(data);
}
});
});
controller text box
public function returnsearchresults()
{
$typed = $this->input->get('t');
if ($typed == null || $typed == '') {
echo ''; // send back nothing if we got nothing
exit;
}
$this->load->model('Search_model');
$data['result1'] = $this->Search_model->match_model($typed);
$this->load->view('content/word_view',$data);
}
contoller button
public function returnsearch()
{
$data = array(
'data' => $this->input->post('title'),
);
}
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
i created a form. Thats shown below...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sbt").click(function(){
var re=$("#file").val();
$.ajax({
type: "POST",
url: "loadajax.php",
data: $("#data").serialize()+ '&photo=' +re,
success: function(data) {
$("#datas").html(data);
},
error: function(){
alert('error handing here');
}
});
});
});
</script>
Ajax response page
<?php
echo "<pre>";
print_r($_POST);
var_dump($_FILES);
?>
All input values are returned.but file is not uploaded.I don't know how to upload file using ajax. Please help me...
Try This
$("#sbt").click(function(){
var pht = $("#ph").val();
var str2 = "your_folder/"; // destination folder, if needed
var upvid = str2.concat(pht);
var data = new FormData();
data.append( 'photo', $('#photo')[0].files[0] );
data.append( 'pht', pht );
$.ajax({
type: "POST",
url: "loadajax.php",
processData: false,
contentType: false,
cache:true,
data: data,
success: function(data){
$("#datas").html(data
} ,
error: function(){
alert('error handing here');
}
});
});
<?php
$a = $_POST['pht'];
$file = str_replace( "\\", '/', $a );
$ofile = basename($file);
?>
You have to use a plugin for this, jQuery doesn't support this out of the box. The best know plugin is ajaxForm
This will post the form to the given url in the form action field using ajax. There are events available to add validations and post-submit funcions.
you can also do like this:
function upload() {
// id of the form "documentUploadForm"
var form = document.getElementById("documentUploadForm");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
var url = '<c:url value="/loadajax.php"/>';
xhr.open('POST', url, true);
xhr.onload = function(e) {
if (xhr.status === 200) {
outputData = JSON.parse(xhr.responseText);
console.log("Response:" +outputData);
}
};
xhr.send(formData);
}