Hi I want to to run function for searching word in database. The function is in this location: media/search, up to now it was possible to run this function with this JS by "search_query":
final_transcript = capitalize(final_transcript);
var queryTextField = document.getElementById("search_query");
queryTextField.value = final_transcript;
....
"search_query" is id in this input:
<form class="input-group navbar-form" action="<?php echo base_url();?>media/search" method="post"></li>
<li style="margin-top:8px;"><input type="text" class="form-control" placeholder="Search subtitles..." id="search_query" name="string" /></li>
<li style="margin:8px><button type="submit" class="btn btn-info" name="btn_search"><i class="search "></i></button>
I want to change it so I don't want to use this HTML code. I want to implement "calling" function media/search in JS instead of:
var queryTextField = document.getElementById("search_query");
Let me know if I misunderstood you, but if I understand you correctly, you want to trigger the search with javascript?
And it looks like you want to do this without jQuery?
//get search string inputted by user
var queryTextField = document.getElementById("search_query");
var query = queryTextField.value
//pass base url to javascript
var base_url = '<?php echo base_url();?>'
//create new request
var request = new XMLHttpRequest();
//set up what you want to do with returned data
request.onreadystatechange=function()
{
//if call was successful
if (request.readyState==4 && request.status==200)
{
//response will be in here
//request.responseText;
}
}
//set as post, the url, send asynchronously
request.open('POST', base_url+'media/search', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(query);
With jQuery:
$.ajax({
type: 'POST',
url: base_url+'media/search',
data: query,
success: function(data_return) {
//do something with returned data
}
});
See:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
and
http://api.jquery.com/jquery.ajax/
I have not tested the above code, but it should put you on the right path.
Related
Fiddle And Code:
$("form.signupform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(.result).html(data.result + " Watchlist");
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="result"></p>
<form class="signupform" method="post" action="admin/signupinsert.php" onsubmit="this.onsubmit=function(){return false;}">
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
admin/signupinsert.php code:
// Insert into DB code in PHP
$response = new \stdClass();
$response->result = "".$result."";
die(json_encode($response));
I am trying to submit this form using My Jquery Ajax Code. And the signupinsert.php file will return a value in $result variable. I am trying to print it inside <p class="result"></p>
But, the code re-directs users to signupinsert.php page.
What's wrong?
you must prevent the default action of submitting the form
$("form.signupform").submit(function(e) {
e.preventDefault(); // <-- add this
var data = $(this).serialize();
var url = $(this).attr("action");
also, in your php file return proper JSON and avoid parsing the response in javascript with JSON.parse(data);
the output in your php file should look like this
$response = new \stdClass();
$response->result = $result;
header('Content-Type: application/json');
print json_encode($response);
and in your success handler just process the data parameter as a normal json object
$.post(url, data, function(data) {
$(.result).html(data.result + " Watchlist");
}
Also, just a curiosity, what is this supposed to do?
$response->result = "".$result."";
Update:
I just realized why you had most of the issues:
$('.result').html(data.result + " Watchlist");
^ ^
see the missing quotes
you are redirecting because of action:
action="admin/signupinsert.php"
var url = $(this).attr("action");
got me?
I'm trying to make a web page using primarily HTML, CSS and JavaScript (I'm fairly new to making websites, so these are the only three I am fairly decent with). This web page will be a form that will interface with an enterprise software (BMC Remedy ITSM) that will enforce validation and make all of our tickets precise when submitted.
One of the few static textboxes on the web page will be an ID number field, a full-name field and a phone-number field.
My goal is to have the user put in their ID number, and have this ID number communicate with the enterprise software, look up the ID number, and auto-populate the full name and phone number from the ID number given.
I want this to be a lostfocus event on the ID number textbox, so therefore I guess it would be under onblur for JavaScript.
Can someone chime in and give me some pointers on how I would achieve this?
Thanks!
A quick example of using the blur event is below in pure JavaScript. Top example shows JSON return and bottom example shows XML.
Fiddle: http://jsfiddle.net/9dpxmpru/2/
HTML:
<input id="empid" type="text" placeholder="Employee ID" />
<input id="name" type="text" placeholder="Full Name" />
<input id="phone" type="text" placeholder="Phone" />
JS:
var empid = document.getElementById('empid');
empid.addEventListener('blur',
function (event) {
var idVal = this.value;
// make some ajax call
// perhaps it returns this
var response = {
name: "John Doe",
phone: "555-5555"
};
var name = document.getElementById('name');
var phone = document.getElementById('phone');
name.value = response.name;
phone.value = response.phone;
}, true
);
As for the ajax call you can do something like this:
// Make Ajax Call
var requestObject = new XMLHttpRequest();
requestObject.open('POST', 'someurl', true);
requestObject.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
// XML: requestObject.setRequestHeader('Content-Type', 'text/xml');
requestObject.onload = function () {
if (this.status >= 200 && this.status < 400) {
// Success!
}
else {
// Handle some server error
}
};
requestObject.onerror = function () {
// Handle some server error
};
requestObject.send(JSON.stringify('idValueFromField'));
This is of course very rough but the general idea.
Here is fiddle parsing xml: http://jsfiddle.net/9dpxmpru/4/
var empid = document.getElementById('empid');
empid.addEventListener('blur',
function (event) {
var idVal = this.value;
// make some ajax call
// perhaps it returns this
var response = "<response><name>John Doe</name><phone>555-5555</phone></response>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(response, 'text/xml');
var name = document.getElementById('name');
var phone = document.getElementById('phone');
name.value = xmlDoc.getElementsByTagName('name')[0].childNodes[0].nodeValue;
phone.value = xmlDoc.getElementsByTagName('phone')[0].childNodes[0].nodeValue;
}, true
);
jQuery Examples:
$("#empid").on("focusout",
function (event) {
var idVal = $(this).val();
// make some ajax call
// perhaps it returns this
var response = {
name: "John Doe",
phone: "555-5555"
};
$("#name").val(response.name);
$("#phone").val(response.phone);
}
);
jQuery Ajax:
$.ajax({
method: "POST",
url: "someurl",
dataType: 'json',
// XML: dataType: 'xml',
data: {
empid: idVal
}
}).done(
function (msg) {
// success!
}
);
jQuery XML example:
$("#empid").on("focusout",
function (event) {
var idVal = $(this).val();
// make some ajax call
// perhaps it returns this
var response = "<response><name>John Doe</name><phone>555-5555</phone></response>";
var xmlDoc = $.parseXML(response),
var xml = $(xmlDoc),
$("#name").val(xml.find("name").text());
$("#phone").val(xml.find("phone").text());
}
);
As far as your idea goes, you're on the right track. But since you said you're newer to web development, I'll explain more. You're going to have a text input that listens for a blur. The blur event will then send an XMLHttpRequest to your ITSM software, supplying a response handler that will execute as soon as the request completes.
If you haven't looked into it yet, and if you have the option, I would suggest jQuery, because it provides traversal functionality for HTML that also [mostly] works on XML. It'll also make your calls a bit easier.
HTML:
<input id="employeeId" type="text" placeholder="Employee ID">
<input id="fullName" type="text">
<input id="phone" type="text">
Assuming your XML is something like this:
<lotsOfResponseParentNodes>
<person>
<fullName>John Doe</fullName>
<phoneNumber>5555551212</phoneNumber>
</person>
</lotsOfResponseParentNodes>
JavaScript (place at bottom of body):
function setFieldVals(fullName, phoneNumber) {
$("#phone").val(phoneNumber);
$("#fullName").val(fullName);
}
$("#employeeId").blur(function(e) {
$.ajax({
type: "POST", //or GET, depending on your api spec
url: ENDPOINT_URI, //Again, depending on your software
data: {employeeId: $(e.target).val()}
dataType: "xml",
success: function(xml) {
setFieldVals($(xml).find("fullName").text(), $(xml).find("phoneNumber").text());
},
error: function() {
alert("An error happened.");
}
});
});
What's key here is how you're parsing your XML. In the XML example I have above, find("nodeName") works. But if the XML were, say, <person phone="xxx"> then you'd have to $(xml).find('person').attr('phone') instead.
i already had a form which uses ajax to save the the data to the database. so i have this sample
Html code
<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>
Javascrip Code
$("#btnSave").click(function(){
p_name = $("#product_name").val();
p_des = $("#product_description").val();
p_image = $("#product_img").prop('files')[0];
data = {
'product_name':p_name,
'product_description':p_des
}
$.post('url_here',data,function(response){
console.log(response);
});
});
i do have this info Jquery input.files equivalent but i cant make it passed as a $_FILE for php.Please give me some example codes combining the input type text and file without using the form tag and using jquery ajax.
You can use FormData:
document.getElementById('btnSave').addEventListener('click', function() {
var fd = new FormData();
fd.append('product_name', document.getElementById('product_name').value);
fd.append('product_description', document.getElementById('product_description').value);
fd.append('product_name', document.getElementById('product_img').files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url_here');
xhr.addEventListener('load', function(e) {
console.log(xhr.responseText);
});
xhr.send(fd);
});
UPDATE
Since you want to use jQuery AJAX (I have no idea why, since it was not prepared to use XHR2), you can workaround by telling it to not process the data parameter, e.g:
$('#btnSave').click(function() {
p_name = $('#product_name').val();
p_des = $('#product_description').val();
p_image = $('#product_img').prop('files')[0];
var data = new FormData();
data.append('product_name', p_name);
data.append('product_description', p_des);
data.appned('product_img', p_image);
$.ajax({
url: 'url_here',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
});
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'),
);
}
How can I pass a a javascript array vArray to File.php , and retrieve the two values from vArray.
I tried:
<input type="button" id="button" onClick = "send_V();" >
<script>
// Creat Array with Values from checkboxes
$('input[type=checkbox]:checked').each(function() {
vArray.push($(this).val());
});
// Set array to only 2 values ( disable checkboxes)
var n = $('input[type=checkbox]:checked').length >= 2;
$('input[type=checkbox]').not(':checked').attr('disabled',n);
// Send array to File.php where I can manipulate its value1, and value2 to query db
function send_V(vArray)
{
$.ajax({
type: "POST",
url: "File.php",
beforeSend: function () {
$("#result").html("<option>Loading ...</option>");
},
data: "vArray="+vArray,
success: function(msg){
$("#result").html(msg);
}
});
}
</script>
and on the php side ( File.php)
$value = $_POST['vArray'];
var_dump(vArray);
but I am not able and sure how to manipulate a javascript variable. can someone show me a simple and effective method ?
What is wrong in this logic?
Thanks
Use json. Encode array in js (How do I encode a javascript object as JSON?), decode it in php (http://php.net/manual/ro/function.json-decode.php).
If you set up the ajax call with an object for the "data" parameter:
$.ajax({
type: "POST",
url: "File.php",
beforeSend: function () {
$("#result").html("<option>Loading ...</option>");
},
data: { vArray: vArray }, // here
success: function(msg){
$("#result").html(msg);
}
});
Then jQuery will create HTTP request parameters like this:
vArray[]=first value
vArray[]=second value
etc. On the server side, when you access
$vArray = $_POST['vArray'];
you'll get the array back. You don't have to explicitly mess with JSON if you don't want to, in other words.
Pure javascript for modern browser (needs support for formData & xhr2)(chrome,safari,ios,android,ie10)
js
var vArray=['a','b','c'],
json=JSON.stringify(vArray);//this converts the array to a json string
function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
function whatever(){
console.log('json posted',this.response)
}
ajax('page.php',whatever,'post',{'json':json});
page.php
<?php
print_r(json_decode($_POST['json']));//converts the json string to a php array
?>
Another solution is to post the whole form
html
<form>
<input name="a" value="x">
<input type="radio" name="b" value="x">
//and many other input & text fields
</form>
js
function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
function whatever(){
console.log('form posted',this.response)
}
var form=document.getElementsByTagName('form')[0],
fd=new FormData(form);
ajax('page.php',whatever,'post',fd);
php
<?php
print_r($_POST);
?>
xhr2
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
formData
https://developer.mozilla.org/en-US/docs/Web/API/FormData
I have tried the following that seems to work fine :
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
It is working really well for me. Code taken from http://www.developphp.com/view.php?tid=1185
Answers by #Pointy and #Cocco might be correct, I could not manage to implement it right with Jquery, neither wanted to use a Form.. Hope this helps someone