i need some code for the next step..this my first step:
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
});
</script>
after matches..i want the result can connect to data base then show data from table inside <div id="value">...how to do that?
you can start here. $.ajax();
You should have some server side scripting knowledge also.
You will need to do it using an ajax call (matches will be a parameter for the call). The php script called through ajax will have to fetch the data and give it back to the calling page.
There you will need to parse the ajax response and display what you want.
A helpfull tutorial can be found here.
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
$.ajax({
type:"post",
url:"process.php",
data:params,
cache :false,
async :false,
success : function() {
alert("Data have been input");
$("#value").html(matches);
return this;
},
error : function() {
alert("Data failed to input.");
}
});
return false;
});
</script>
and i change my process.php become:
select itemdata as version from settingdata where version = "tunerrange";
Related
I am trying to get JSON data from API on Laravel 5 , The route gives me correct
Data in the browser but when trying to access this route in JQuery it failed.
the route is:
http://localhost:8000/search/student/all
worked finally in the browser and the data is displayed in json format
but this script failed:
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
I replaced localhost:8000 with 127.0.0.1:8000 but nothing changed.
Note: I generated the json response using Laravel
$students=App\Student::all();
return response()->json($students);
In jquery you can do like something below
$.get( "http://localhost:8000/search/student/all", function(data ) {
var obj = jQuery.parseJSON(data);
console.log(obj);
});
Another possibility use jsonp
JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
$.ajax({
url:"http://localhost:8000/search/student/all",
dataType: 'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
console.log(obj)
},
error:function(){
}
});
Basic example of using .ajax() with JSONP?
Try like this...
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result.students, function(i, field){
$("div").append(field.name + " ");//name is database field name such as id,name,address etc
});
});
});
</script>
PHP
$students=App\Student::all();
echo json_encode($students);//or return $students->toJson();
I retrireve data from my MySQL database into a simple table. Above this table I should have a text-input. On entering a keyword into this input, I want to cancel all showing data in the table and display data, found by %LIKE% operator, matching the keyword entered.Something similar does jQueryUi Autcomplete, FooTable and a couple of Yii extensions, but I wanna do it all from scratch. Any ideas on how to do it? Links?
My knowledge:
$.ajax({
url: 'ajax/test.html',
success: function(){
alert('Load was performed.');
}
});
What I am going to give you is not the complete code.
You want to do it yourself so here is only the logic.
In you index.php file
<input type="text" name="autocoplete" id="autocomplete"/>
<div id="result"></div>
<script type="text/javascript">
$(document).on('keyup', '#autocompelte', function(){
var text = $('#autocomplete').val();
$.post('process.php', {text:text}, function(resultData){
//Treat your resultData and convert into HTML for example
$('#result').html(myHTMLResult);
}, 'json'); //I want my result as JSON
});
</script>
process.php
if(true === isset($_GET['text']) && false === empty($_GET['text']))
{
//Do your query where you field is like %$_GET['text']% : example : SELECT * FROM mytable WHERE myfield like %$_GET['text']%
//Store all your result in an array
//Format this array into json to be easy to treat with json
//Send this json back to your index.php file.
echo json_encode($listResult);
}
#ThinkTank thank you very much for the help. It works just fine. Here is my final code:
$(document).ready(function() {
$('#input').keyup(function(eventObject){
//cancel all displaying data in the table if keyword exists
if($(this).val()) {
//$("td").hide();
$("td").remove();
//data hid, now send data to server
var orgValue = $(this).val();
$.ajax({
url: '/products/RetrieveData',
data: 'term='+orgValue,
success: function(data) {
var jsondata=$.parseJSON(data);
$.each(jsondata, function(i, d) {
var row='<tr>';
$.each(d, function(j, e) {
row+='<td>'+e+'</td>';
});
row+='</tr>';
$('#table tbody').append(row);
});
}
});
} else {
$("td").show();
}
});
} );
Just some ideas:
1. Once I find (filter out) what I need, I clear the input with backspace. How do I set the table to the initial state with the data?
I have this scenario:
I have a simple php file with only few html elemnts: a div called switch, another called lamp and a couple of buttons.
The two buttons are labeled On and Off.
The lamp div is empty.
The switch div is empty too, but is updated using jQuery and Ajax with the content of a txt file, that only contains one word: it could be On or Off.
What i'm traying to achieve is this: whenever the file is updated with the word On or Off i would like the On or Off button to be triggered correspondingly and the lamp div to change the background color. Is it possible?
UPDATE:
Example:
(function($){
$(document).ready(function() {
$.ajax({
url : "testfile.txt",
dataType: "text",
success : function (data) {
$("#switch").html(data);
// this doesn't seems to work...
var word = data.toLowerCase();
$('#' + word).trigger('click');
// this works
$(document).ajaxStop(function(e){
var response = $("#switch").html();
$("#" + response.toLowerCase()).trigger("click");
});
var $container = $("#switch");
var refreshId = setInterval(function()
{
$container.load('testfile.txt').html();
}, 2000);
}
});
});
})(jQuery);
<div id="switch"></div>
<div id="on" class="button">On</div>
<div id="off" class="button">Off</div>
<div id="lamp"></div>
Since the response is only one word. Why not try
var word = data.toLowerCase();
$('#' + word).trigger('click');
in the success callback.
If you have only one ajax request, you can do like this:
$(document).ajaxStop(function(e){
var response = $("#switch").text();
// do what you want with variable response here
$("#" + response.toLowerCase()).trigger("click");
});
Maybe this can help for what you need:
(function($){
$(document).ready(function() {
var $container = $("#switch");
$container.load("testfile.txt", function() {
setInterval(function() {
$container.load("testfile.txt");
}, 2000);
});
});
})(jQuery);
Use clearInterval() to stop the timer when needed.
UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.
Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request