I have done some reading and I think i need to use json for this. I have never used this before. I am trying to accomplish this, but in jQuery
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//stop and make user write something else
} else {
//keep going
}
I am switching my website over from php to jQuery, which is also very new to me but seems so much better. Here is a piece of my jQuery. I am validating a form. The form works and submits, but now i want to see if the email exists in my database before submission. How would i do this?
if (email == "") {
$("#error5").css("display", "inline");
$("#email").focus();
return false;
}
// Im guessing the new code would go here
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
url: action,
data: dataString,
success: window.location.assign("cashcheck_order.php")
});
This is a basic ajax call using jquery
var thing1; //thing 1 to use in js
var thing2; //thing 2 to use
var form = ("#acc_form"); //localize the form to a variable. you don't need to keep looking it up
var dataString = form.serialize();
var action = form.attr('action');
$.ajax({
url: action,
data: dataString,
type: "post",
success: function(data){
var responseData = $.parseJSON(data); //json native decoding if available, otherwise will do it with jquery
thing1 = responseData["thing1"];
thing2 = responseData["thing2"];
},
error: function(data){
console.log("error", data);
}
});
On the php side, to bring the vars in you use
$input1 = isset($_GET["name_of_input1"]) ? $_GET["name_of_input1"] : "";
if this is set, set this value, else set blank.
you can use $_POST, $_REQUEST if you prefer.
do not forget to sanitize your inputs.
Now to send it back to the js file
$dataToReturn = [
"thing1"=>"I'm thing 1",
"thing2"=>"I'm thing 2"
];
//sending back data
echo json_encode($dataToReturn);
Related
I have the code below for Java Script on getwifi1.php
$(function(){
$('#wifi-avail').on('click', 'td', function(){
var txt;
var user;
var pass = prompt("Please enter your password:", "");
if (pass == null || pass == "") {
txt = "User cancelled the prompt.";
}
user = $(this).html();
$.post(
"newone.php",
{
"username":user,
"password":pass
}
)
alert(user);
alert(pass);
}); //end inner function
}); //end outer function
I want to transfer the value of user and pass to another php file named newone.php in which I have written this code
<?php
$name1 = $_POST['username'];
$name2 = $_POST['password'];
echo $name1;
echo $name2;
?>
but the $name1 and $name2 seems to be empty always. I don't know what I am doing wrong. Can anyone correct my method or write me another code to transfer these two variables from getwifi1.php to newone.php. I have search ajax method which I applied like this but it didn't seem to work either
$.ajax({
method: "post",
url: "newone.php",
data: {username:user, password:pass}
})
ThankYou
See http://api.jquery.com/jquery.ajax/
Type: An alias for method. You should use type if you're using versions of
jQuery prior to 1.9.0.
I'm not sure, but I think you have to change 'method' to 'type' in your Ajax call.
My bad, this is not true and necessary.
This script should be working (and alert any error messages from your newone.php):
$.ajax({
type: 'POST',
url: 'newone.php',
data: {
username: user,
password: password
},
success:function(data){
alert(data);
}
});
http://api.jquery.com/jquery.ajax/
I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery
I've build a small CMS in Codeigniter for a website with a couple of forms.
The forms are all submitted with the ajax method in jQuery and passed to the controller. All works fine but I figured it out that I always get a success, no matter if the data is saved in the database or not. The method only checks if the data is passed to the controller properly, i guess. On success there is a message for the user (Saved), this will fire everytime, no matter what happens behind the scenes. How I can force success (or done, or some other callback) to get the "Saved" message only if the data is saved?
Here is the code:
//javascript
$("#save_club").click(function(){
var club_name = $('input[name="club_name"]').val();
var location = $('input[name="location"]').val();
var phone = $('input[name="phone"]').val();
$.ajax({
type: "post",
url: base_url + "/clubs/save_club/",
data: {club_name:club_name,location:location,phone1:phone1},
success:function(data)
{
$('input[type="submit"]').attr("value", "Saved!");
$('input[type="submit"]').css("background-color", "#32c310");
$('input[type="submit"]').css("cursor", "default");
$(".dynamic_content").load(base_url + "/clubs/clubs_list");
}
});
});
//controller
public function save_club(){
$newdata = array();
$newdata['club_name'] = $this->input->post("club_name");
$newdata['location'] = $this->input->post("location");
$newdata['phone'] = $this->input->post("phone");
$this->load->model("model_save");
$this->model_save->save_club_to_db($newdata);
}
You first would need to validate the inputs with PHP. For example:
<?php
$success = 'true';
foreach($_POST as $input) {
if ($input == '') {
$success = 'false';
break;
}
}
echo $success;
?>
Next, check the return with the data var you passed in the success function:
$.ajax({
type: "post",
url: base_url + "/clubs/save_club/",
data: {club_name:club_name,location:location,phone1:phone1},
success:function(data)
//Whatever PHP echoes in the script gets put into the variable data
{
var result = (data ? 'saved!' : 'error!'); //data should either be true or false
$('input[type="submit"]').attr("value", result);
$('input[type="submit"]').css("background-color", "#32c310");
$('input[type="submit"]').css("cursor", "default");
$(".dynamic_content").load(base_url + "/clubs/clubs_list");
}
});
I trying to use contact form using J Query ,PHP AJAX but here in the below code the form information is gathered and send it to the server using for LOOP and Array of inouts of ofrm is created . i am new to this kind of coding please help me to extract this value in PHP so that i can use this element to add in to my database or send mail contain form inputs .
function signUpClick(){
var form = $("#form_main")[0];
var objData = {};
for(var i=0;i<form.length;i++){
var input = form[i];
objData[input.name] = "";
if(input.className == "writable")
objData[input.name] = input.value;
}
$("#loader").show();
$("#error_message").hide();
//send contact form using ajax
$.ajax({
url: "contact.php",
global: false,
type: "POST",
data:objData,
success: function(response){
$("#loader").hide();
if(response == "__ok__")
showSentMessage();
else
showErrorMessage(response);
},
error:function(){
$("#loader").hide();
showErrorMessage("Can't get the contact form");
}
});
}
On the PHP side you can manage the information as an array:
$objData = json_decode(file_get_contents('php://input'));
$objData will be the PHP array equivalent to the $objData on Javascript
At the moment i have this piece of javascript code:
//Display custom confirm box and delete multiple message
$(document).ready(function () {
$(".delete_button-multiple").click(function () {
//Get message id as variable
var id = $(this).attr("id");
var dataString = 'id=' + id;
var parent = $(this).parent();
//Display custom Confirm box
jConfirm('Are you sure you want to delete this message?', '', function (r) {
if (r == true) { //initiate delete message if agreed
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: dataString,
cache: false,
success: function () {
window.location = "mail_inbox.php";
}
});
return false;
}
});
});
});
delete-mail_ajax.php:
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete FROM mail WHERE mail_id='$id'";
mysql_query( $sql);
}
This is a working code for deleting only one mail item.
I wrote the following code to delete multiple messages from checkboxes:
//Multiple delete mail
if(!empty($_POST['message'])){
$list_mail = $_POST['message'];
foreach ($list_mail as $messageID){
$sql = "delete FROM mail WHERE mail_id='$messageID'";
mysql_query($sql);
//deletion complete, refresh the page
header("Location: mail_inbox.php");
}
}//end delete multiple
The difficulty i'm having is changing the working code above to incorporate the multiple selection, and deletion, of selected mails.
Any help on this issue would be appreciated
-Callum
Assuming you're using checkboxes, your code would look something like:
var messages = new Array();
$("input[name='mail_items[]']:checked").each(function() {
messages.push($(this).val());
});
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: { message: messages } //jQuery should translate this to an array that PHP should understand
cache: false,
...
});
You may need to json_decode the input to the $_POST['message'] variable, but I'd do a var_dump() on the stuff first just to make sure what PHP is doing in the background. Can't check at the moment, sorry.
I guess you have trouble submitting the form via Ajax? There is a neat plugin that does that for you: http://jquery.malsup.com/form/