Passing JavaScript array using AJAX - php

I'm very new to ajax and I'm trying to pass an array that I have created in javascript called markers over to a PHP page when the user clicks the submit button. At the time of submission the array exists and is within scope. The code below is what is trying to do that. When I click the submit button I get sent to the php page and "failed" is printed (part of my code) meaning the array was not passed. I believe the error occurs in the ajax code and I'm not sure where it is coming from, any help is greatly appreciated!
The javascript/ajax stuff:
function submit_tour(){
var input = JSON.stringify(markers);
//var input = $(this).serialize();
var sent = $.ajax({
type: "POST",
data: input,
dataType: 'JSON',
url: "test_portal2.php"
}).done(function() {window.alert("done");})
.fail(function() {window.alert("failed");});
window.alert("" + input);
}
The HTML button that is supposed to send the array:
<form name="toursubmit" action="test_portal2.php" onsubmit="submit_tour()">
<input type="submit" value="Submit">
</form>
The PHP that catches it (in the test_portal.php file):
$ans = json_decode($sent);
echo $ans;
if ($ans != NULL){
echo "works";
echo $ans;
}
else {
echo 'failed';
}

A couple of things to point out.
First, you need to prevent the default POST action within your submit_tour() function, otherwise the synchronous POST will happen.
Second, you need to specify the contentType value in your AJAX call as application/json.
Third, if you are actually POSTing JSON to PHP and using application/json as the ContentType, then you will need to get the JSON data in PHP by accessing the raw input like this:
$json = file_get_contents('php://input');
$obj = json_decode($json);
This is because $_POST is only auto-generated for form-encoded content types.

When you send
var input = JSON.stringify(markers);
And markers has no value
<input type="hidden" id="markers" name="markers"> // No value anywhere
Then it will surely be Null :)
Also do you populate your $sent variable from a value in $_POST ? don't see that happening

You don't need this in a form tag. The code is submitting the form and not running the JS.
Remove the form tag, or put this: submit_tour(); in onsubmit on the form instead, and return false.

Related

Simulate html form POST using ajax/jquery

I want to read all the post variables and their content from a form and post them using jquery's "$.post()".
First of all, this won't do the job:
$.post("myServer.com/test2.php", $('#myform').serialize())
because it would only send one variable which I'd have to parse on the php side.
Here is how I'd start:
function doIndirectPost() {
variableWithTheFormPOSTData = {};
$("#IdOfMyForm :input").each(function() {
variableWithTheFormPOSTData[$(this).attr("name")] = $(this).attr("value");
}
document.getElementById("IdOfMyForm").submit();
$.post("myServer.com/test2.php", variableWithTheFormPOSTData);
}
and then I'd like to use $.post() to post the data seperated in multiple variables (just like a normal form submit would do it...
I read somewhere, that you could do that like this:
$.post('myserver.com/test2.php.php',{
var1: content1,
var2: content2
}
But I want it to be dynamic. This part:
var1: content1,
var2: content2
should autmatically contain all variable names and values of the form.
In the end I'd like to be able to get all POST variables like this:
foreach ($_POST as $key => $value)
{
echo $key . "= " . $value;
}
Serialize doesn't send only one variable, it sends name value pairs of all input elements in the form. So
$("#IdOfMyForm").on("submit", function () {
$.post("myServer.com/test2.php", $("#IdOfMyForm").serialize(),
function(dataFromServer){
//server sent a response now do whatever you want to do after form has been submitted
//or submit form regular way $("#IdOfMyForm").submit();
}
);
return false;
});
Should work. Just remember to set name attribute of every input/select element in form.
Have you tried it using JQuery's Ajax instead?
Like this answer here:
jQuery Ajax POST example with PHP

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

Javascript get form value in URL without jQuery

If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.
Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?
use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.
If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});
After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.
function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};
The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).

How to pass multiple checkboxes to PHP through JQUERY

I HAVE modified my code, i used firebug console.log to detect weather the the php gets the array passed or not. and firebug displays this - rescheck[]=2&rescheck=1&rescheck=3
I think php gets the array if THATS what an array in php supposed to be like.
SO guys, if thats correct how to insert that array in database? or how to loop it? the foreach loop ive made didnt work.
JQUERY CODE:
$('#res-button').click(function (){
var room_id=$('[name=rescheck[]]:checked').serialize().replace(/%5B%5D/g,'[]');
alert(room_id);
$.ajax({
type: "POST",
url: "reservation-valid.php",
data: {name_r:name_r, email_r:email_r,contact_r:contact_r,prop_id:p_id,cvalue:room_id},
success: function(data) {
console.log(data);
}
});
});
<input type="checkbox" name="rescheck[]" value="<?php echo $roomid; ?>" />
PHP CODE:
$c_array=$_POST['cvalue'];
echo $c_array;
//foreach($c_array as $ch)
//{
//$sql=mysql_query("INSERT INTO reservation VALUES('','$prop_id','$ch','$name_r','$contact_r','$email_r','')");
//}
I think I managed my jquery code to be right, but I don't know how to fetch that with PHP.
room_id is an array, so if you want to get the value for each, you need to get all value together first.
var room_id_string = '';
for(i=0;i<room_id.length;i++){
room_id_string += room_id.eq(i).val() + ',';
}
your below code will only pass Array jquery object of [name=rescheck[]]:checked to room_id
Instead of this you will have to create a array and push values in it like this
var room_id = Array();
$('[name=rescheck[]]:checked').each(function(){
room_id.push($(this).val());
});
In jQuery it might be easier for you to just use the serialize function to get all the form data. jQuery passes the form to the server so you don't have to worry about getting all the values. If you use it in conjunction with the validate plugin you might find it a little easier!
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This is what I do ibn my site for saving to a db a list of checkboxes with jquery and ajax call. It make an array and pass it to the ajax call and the php script handle the array.
If you get any error here you should debug the js array with firebug for be sure that is formed correctly.
js script:
var $checkBox = $('[name=rescheck[]]:checked');
$checkBox.each(function() {
if ($(this).is(":checked")){
valuesCheck[this.value] = 1;
}else{
valuesCheck[this.value] = 0;
}
and the PHP script:
$checkTab = $_POST['cvalue'];
foreach ($checkTab as $idChkTab => $checkedOrNot){
if ($checkedOrNot== "0"){
//do something if isn't checked
}

Validate before post

I have this little code (part of my registration code) :
<?php
if (#$_POST['Submit'] == 'Register'){
if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
{
die("Invalid code entered. Please enter the correct code as shown in the Image");
}
}
?>
<form name="form1" id="signupForm" method="post" action="register.php" style="padding:5px;">
<div class="reg_left">Security code:</div>
<div class="reg_right"><input name="user_code" type="text" size="10"> <img src="pngimg.php" align="middle" width="100" height="40"></div>
<div><input type="submit" name="Submit" class="submit" value="<?php echo $gomb_reg;?>"></div>
</form>
Unfortunately this is check if code is valid after post the form data. I would like to check before posting.
So I think I must use jQuery validation plugin (btw I use jQuery to validate the other fields like email, user, password). But as I'm not an expert in jQuery, I need help to write that php code above in jQuery.
Thank you.
I believe the basic jist would be:
Hook a function to the submit element
That JS function sends the user_code value to PHP script
The PHP script checks the value and and outputs (returns) a bool (or json)
The JS function allows the post if a good value is returned
(Note: Since the jQuery AJAX function do not stop the execution of the script, you'll have to stop the form from submitting, then submit the form in the AJAX callback.)
Look at the jQuery docs for
.post
or
.getJSON, use those function to sent the 'user_code' to be checked.
You can keep most of your php code the same, but you'll want to check for the request header type.
I'm pretty sure jQuery sends the X-Requested-With : XMLHttpRequest but I'm not entirely sure and its late, so to somewhat modify your php script it would look something like this
if (#$_POST['submit'] == 'Register') {
if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
{
// check if the request was from an ajax call
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
//if it is an ajax request we need to send back a json encoded array
$response = array('success' => 'true', 'message' => 'Invalid code';
// now we encode the array and echo it back
echo json_encode($response);
// exit the script for safety
exit();
} else {
// if the request wasn't ajax the respond business as usual
die("Invalid code entered. Please enter the correct code as shown in the Image");
}
}
}
As for the jQuery code it would probably look something like this:
$(document).ready(function(){
// this creates an event handler on the form submit
$('#signUpForm').submit(function(){
// you'll need to give your user_code input an id of user_code
var user_code = $('#user_code').val();
// I like to use the jQuery $.ajax method since it gives you more controll
$.ajax({
// send a post request
type : 'POST',
// the url you'll be sending the request too
url: 'register.php',
// the type of data you're expecting back
// i prefer json since its easier to work with for me
dataType : 'json',
// the data you want to send which would be your user_code data
// send this in a name/value pair
data : 'user_code=' + user_code + '&submit=Register',
// the success function is called when the ajax call has been
// completed, not whether the user_code matches the $_SESSION['ckey']
// the data variable will contain your json data
success : function(data, textStatus){
// since we json encoded the php array it will
// look something like this
//{ success : 'true', message : 'incorrect code'}
if(data.success == 'true'){
// what you plan on doing if the code is correct
alert(data.message);
} else {
// what you do if the code is incorrect
alert(data.message);
}
}
});
// stop the form from submitting
return false;
});
});
I think that should just about do it. the $.ajax method has a few other call back functions such as onError, complete and similar messages that are worth looking into here. The $.ajax method is a little daunting at first, but after using it a few times, I now prefer it over the other ajax methods they have ($.load,$.get, $.getJSON, or $.post)

Categories