checking instantly php arrays using jquery / ajax - javascript

I want to be able to check whether values exist in the php array without having to click the submit button to do those checks using jquery/ajax.
when users enter an abbreviation in the text field want to be able to show that the brand exists (either vw or tyta) or not (as they type in the input box) and show the results in the carnamestatus div.
I was following a tutorial from youtube, however it queried against a mysql database.
I was wondering if this is possible using php arrays instead of mysql? I would be grateful if you could pick any faults in the code.
the code is as follows:
<?php
$car = array()
$car["vw"] = array( "name" => "volkswagen");
$car["tyta"] = array( "name => "toyota");
?>
the html code is as follows:
<label for="carname">Car Code:</label> <input type="text" onblur="checkcar()" value="" id="carname" />
<div id="carnamestatus"></div>
the checkcar()
function checkcar(){
var u = _("carname").value;
if(u != ""){
_("carname").innerHTML = 'checking ...';
var B = new XMLHttpRequest();
B.open("POST","check.php",true); /
B.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
B.onreadystatechange = function() {
if(B.readyState==4 && B.status== 200) {
_("carnamestatus").innerHTML = B.responseText;
}
}
var v = "carnamecheck="+u;
B.send(v);
}
}
</script>

Use Javascript keyboard event and then, send the value of the input into your php function.
For example:
$("#youInput").keyup(
function() {
$.ajax(
{
type: "post",
url: "your_url.php",
data: {params: $(this).val()},
success: function(data) {
console.log(data)
}
}
);
}
);
And in you php code, just retrieve the params value, $_POST['params']
Explain
When you press the keybord, your retrieve the value of the input ( here, it is $(this).val() where this represents #yourInput ), then you send the value via ajax (Here we use post type) with your url and the different params that you will send to the server side. If you post the value with $_POST['params'] you will get the value entered in the input. And if it's success, the callback function will retrieve the data returned by your server side.
Here, we just use, jQuery.ajax but you can find more about ajax here or here. Using library make it easy to work with.
Hope it helps you!

Related

codeigniter: I can't change view page

I'm having some problems changing the view page in the code. Note: i'm using ajax.
This is part of the controller function called "insert_inventario" after the information is saved in array_db it compares with the inventario_model and the result "true" or "false" is saved in obj_inv.
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
if($obj_inv){
$edit_view = $this->load->view(base_url()."inventario/edit",$array_db,TRUE);
$response = array('mensaje' => $edit_view,
);
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}
This is part of the view page called create, this is the submit button that executes the Javascript code that execute the controller function
<input type="submit" class="btn btn-danger" id="btn_enviar" value="Guardar">
The javascript Function
$("#btn_enviar").click(function(){
var r = confirm("Make sure the information you fill is correct");
if (r == true){
var url = base_url + "/inventario/insert_inventario";
$.ajax({
type: "POST",
url: url,
data: $("#form_inventario").serialize(),
success: function(data)
{
$("#contenido").html(data.mensaje);
}
});
}
return false;
});
The problem is, when i fill the form and press submit, the message box appears and when I click accept, it does nothing. I'm burning my brain so much to understand what I'm doing wrong, please help me.
The main problem is a error called jquery-2.1.4.min.js:4 POST http://161.196.112.19:8080/Inventario_Remedy/inventario/insert_inventario 500 (Internal Server Error) it happens when the code try to insert the array
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
So, in order to fix this, you have to check your database values and keep trying.

How to share data between programming languages

Hypothetical here: Let's say that you have a JavaScript file that uses jQuery to get input from the user. For example:
var $input = 0;
var buttonClick = function() {
$('.button').click(function() {
$input = $('input').val();
});
}
$(document).ready(buttonClick());
But what if you want to use sql to see if the input matches a password in a database
How would you tell the sql script to run after you click the button?
How would you share the $input variable the sql script so it could check it against the database?
var buttonClick = function() {
$('.button').click(function() {
$.post( "script.php", { Username: "Your Name", Password: "Password" })
.done(function( data ) {
alert( "Data Send: " + data );
// In data you have a response you got from the php script
});
});
}
If you wan't to check Password when your client click on the button , you need to use Ajax and call a Php function.
So when your client click on the button, Jquery call the PHP script and the PHP script call Mysql. After Mysql give a response to Php who send Data to Jquery (true or false in this case).

Checkboxes in Form to javascript to php

I have a form with dynamic checkboxes based on MySQL data. On submit the DIV refreshes without blinking with JavaScript. I'm trying to send the form data to PHP for updating the MySQL but I constantly run into one error or another due to my lack of JavaScript knowledge. My current attempt (see below) gives the "TypeError: document.multipix_form.pix is undefined" error in FireBug.
function multipicupdate(php_file, purpose, where) {
var request = getXMLHTTP(); // call the function for the XMLHttpRequest instance
var a = document.getElementById("optone").value ;
var b = document.getElementById("table").value ;
var boxes = document.multipix_form.pix.length
txt = ""
for (i = 0; i < boxes; i++) {
if (document.multipix_form.pix[i].checked) {
txt = txt + document.multipix_form.pix[i].value + " "
}
}
var the_data = 'purpose='+purpose+'&var1='+a+'&var2='+b+'&var3='+txt;
request.open("POST", php_file, true); // set the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(where).innerHTML = request.responseText;
}
}
}
The form name is multipix_form. The three form inputs are optone (select), table (select), and pix[] (checkbox). The pix[] is dynamic as I said before. It is the passing of the checkbox data from JavaScript to php that has me stumped.
My form submit is :
<input type="button" onClick="multipicupdate('php/ajaxprocess.php', 'multipix', 'message_profile'); return false;" value="Save changes to this photo">
The ajaxprocess.php will take the form data and update MySQL.
As you have tagged jQuery, here's a jQuery solution. You can simplify this code quite a lot. Firstly, you can use serialize() to create a querystring from the values of the inputs in that form. Then you can use $.ajax to send that information to the page you need. Try this:
<input type="button" value="Save changes to this photo" id="multipicupdate">
$('#multipicupdate').click(function() {
$.ajax({
url: '',
type: 'POST',
data: $('#myForm').serialize(), // change the selector as needed
success: function(data) {
$('#message_profile').html(data);
}
});
});
You need a semicolon after
var boxes = document.multipix_form.pix.length
and
txt = ""

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

Javascript/Ajax/Json: Sending objects and arrays

I have a form where people enter their clients into.
This form allows the user to add as many phone numbers, emails, and addresses as they want.
Phone and email have type and data fields for each added row (phone_type, phone_data) while Address has type, street, city, state, and zip fields for each row (address_type, address_street, address_city, address_state, address_zip).
So for example, when the user adds a phone field it adds:
<input type="text" name="phone_type[]" />
<input type="text" name="phone_data[]" />
I need to send the form data over Ajax to a PHP to process and store in database.
I've thought of storing it in array within an object.
phone = new Object();
var phone.data = new Array(),
phone.type = new Array();
$("input[name='phone_data[]']").each(function() {
if($(this).val() != '') {
phone.data.push($(this).val());
phone.type.push($('select[name="phone_type[]"]').val());
})
This doesn't seem to work. Am I even approaching this correctly?
Also, once I get it into an object that I send over Ajax to a PHP page, how do I grab the values?
serialize your form... use data of ajax to sent the serialize data to the server...
data:$('#YourFORMID').serialize();
here is the documentaiotn have alook to the examples...
http://api.jquery.com/jQuery.post/
and to grab the data in your PHP (if you are using ajax type as post)
$data=$_POST['phone_data'];
$type=$_POST['phone_type'];
if ajax type : GET
$data=$_GET['phone_data'];
$type=$_GET['phone_type'];
Are you trying to reinvent jQuery's serialize()
var frm = $("#myForm");
var values = frm.serialize();
//make Ajax call
$.post("someUrl", values, function(){} );
http://jsfiddle.net/BZcja/
You can most definitely use jQuery serialize(). In your event which triggers the processing you can do the following:
$.ajax({
type: "POST",
url: "your_php_processing_page.php",
data: $("#FormID").serialize(),
dataType: "json",
success: function(data){
// do stuff here
},
error: function() {
// do stuff here
}
});
In your_php_processing_page.php you can get the values as follows:
$phone_types = $_POST["phone_type"];
$phone_data = $_POST["phone_data"];

Categories

Resources