dimanche 26 avril 2015

set cookie without having to refresh the page


I would like to set a cookie using either javascript or ajax.
The main issue is that I want to do this without refreshing the page. Does anybody have an example or small test case that I could see?


samedi 25 avril 2015

Ajax date validation boostrap


var startDate=null;
                var endDate=null;
                $(document).ready(function(){
                        $("#language").select2({placeholder: 'Please Select language'});
                        $('#Date3').datepicker()
                                .on('changeDate', function(ev){
                                        endDate=new Date(ev.date.getFullYear(),ev.date.getMonth(),ev.date.getDate(),0,0,0);
                                        startDate=new Date();
                                        
                                        if(endDate<startDate){
                                                                //alert("End Date is less than Start Date");
                                                                 $("#output_save_add").html('<div style="margin:5px" class="alert alert-danger"><br>Please select future Date</div>');
                                                                
                                                                setTimeout(function () {
                        $("#output_save_add").html('')
                    }, 1500);
                                                                
                                                                
                                                }

                                });
                
                });

this my code for validate date if selected date in past it has to show the error.. i don't understand why doesn't it run when I selected date note - im just beginner . help !


Ajax multiple file upload dont work


I'm usign this code to pass all file input by ajax. There are three input file in html code .But only the first file input be sent by ajax. how to fix this code? Where is my mistake?

$("#add_order").click(function () {

    //*****get data input
    var formData = new FormData(); 
        formData.append( 'action', 'add_order');

    $.each($("input[type=file]"), function(i, obj) {
        $.each(obj.files,function(j,file){
            alert(file.name);
            formData.append('orderpic[]', file);
        });
    });

    //ajax start and ajax complatet
    ajax_loading();

    $.ajax({
        url: "includes/ajax/ajax.php",
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        dataType:'json',
        success: function(response){
           //load json data from server and output message     
           if(response.type == 'error'){ //load json data from server and output message     
               output = '<div class="alert alert-danger" style="margin-top:12px;">'+response.text+'</div>';
           }else{
               output = '<div class="alert alert-success" style="margin-top:12px;">'+response.text+'</div>';
               resetAllValues();
               setTimeout(function() {
                    $('#new-order').modal('hide');
                }, 1500);
           }
           $("#results").hide().html(output).fadeIn('slow').delay(800).fadeOut();
    });        
});

HTML code:

<input type="file" name="orderpic[]" id="orderpic" class="form-control">
<input type="file" name="orderpic[]" id="orderpic" class="form-control">
<input type="file" name="orderpic[]" id="orderpic" class="form-control">

PHP code:

//file settings
    $files = array();
    for($i=0; $i<count($_FILES['orderpic']['name']); $i++) {
        //Get the temp file path
        $tmpFilePath = $_FILES['orderpic']['tmp_name'][$i];

        //Make sure we have a filepath
        if ($tmpFilePath != "") {
            //Setup our new file path
            $time = time();
            $ext = pathinfo($_FILES['orderpic']['name'][$i], PATHINFO_EXTENSION);
            $FilePath = $uploaddir . $time .'.'. $ext;

            //Upload the file into the temp dir
            if (move_uploaded_file($tmpFilePath, $FilePath)) {
                $resizeObj = new resize($FilePath);
                $resizeObj -> resizeImage(200, 350, 'portrait');
                $newFilePath = $uploaddir. "200_350_" .$time.'.'.$ext;
                $resizeObj -> saveImage($newFilePath, 100);
                unlink($FilePath);
                $files[] = "200_350_" .$time.'.'.$ext;
            }
        }
    }


Cannot locate endpoint with AJAX


My AJAX cannot find the endpoint /auth/signup/ and I am not sure why. If there is anything else missing please let me know. I think I might have set my urls.py incorrectly

I get this ouput:

POST http://ift.tt/1Qvcudc 500 (INTERNAL SERVER ERROR)

JS:

function ajaxPost(endpoint, payload) {
    console.log("ajaxing");
    console.log(payload);
    $.ajax({
        url: endpoint,
        type: "POST",
        data: payload,
        success: console.log("YES!")
        });
    }
}

HTML:

<div role="tabpanel" class="tab-pane fade in" id="signup-pane">
  <form class="signup-form" method="post" action="/auth/signup/" id="create-account">
      {% csrf_token %}
      <input id="signup-firstname" type="text" placeholder="First Name">
      <input id="signup-lastname" type="text" placeholder="Last Name">
      <input id="signup-email" type="email" placeholder="Email">
      <input id="signup-password" placeholder="Password" type="password"><div id="pswd-msg"></div>
      <input id="signup-confirm-password" placeholder="Confirm Password" type="password"><div id="result"></div>
      <input type="submit" value="Create Account" class="btn btn-xl" id="create-acc-btn" name="signup-submit">
   </form>
</div>

projet urls.py

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include("index.urls")),
    url(r'auth/', include("userapp.urls"))
)

userapp urls.py

urlpatterns = patterns('',
    url(r'signup/$', register),
)

userapp views.py

def register(request):
    registered = False
    if request.method == "POST":
        post_data = request.POST.get("firstName")
        print "here!!"
        print post_data
        return render(request)

    else:
        print "there"
        return render(request)


JQuery Ajax stops working after adding .submit(function() { }


The original issue was that JQuery Ajax won't call succuess after hitting the C# method. By looking at a similar issue here: jQuery Ajax not returning success i see that the solution was to add: $(parentForm).submit(function(event) { event.preventDefault();

However, after doing this, the Ajax code doesn't seem to execute. I do hit the JS function though, but it stops before it executes Ajax code.

My Html code looks like this

    @{
    const string formId = "parentForm";
}

@using (Html.BeginForm("EditChannel", "Channel", FormMethod.Post, new { id = formId }))
    {
        Html.RenderPartial("EditChannelForm", Model);
        <br /><br />

    <input type="button" value="Save" onclick="editChannel('@Model.ChannelViewModel.ID', @formId)" />

    }

I submit this form in the JS code (when the button above is clicked) that looks like this:

function editChannel(channelId, parentForm) {

$(parentForm).submit(function(event) {
    event.preventDefault();
    $.ajax({
        url: "/Channel/EditChannel/",
        type: "POST",
        cache: false,
        data: {
            id: channelId,
            updatedModel: parentForm
        },
        success: function(msg) {
            alert("Msg: " + msg);
            if (msg === "ChangeOfSensitiveData") {
                showAlertOnChangeOfSensitiveData('sensitivDataMsgDiv');
            } else {
                alert("Else");
            }
        },
        error: function(msg) {
            alert("error");
        }
    });
});

}

I do hit the JS function, but the ajax never executes, and therefore not calling the C# method. If I only do like this:

function editChannel(channelId, parentForm) { $(parentForm).submit() ...

Then the ajax code executes and hits the C# method, but never hits the success function.

The C# looks like this:

[HttpPost]
        public ActionResult EditChannel(int id, ChannelAndLocationViewModel updatedModel)
        {
            updatedModel.LocationItemViewModels = GetLocationItems();            

            if (ModelState.IsValid)
            {
                ChannelModel channel = null;
                using (var context = new MaaneGrisContext())
                {
                    var oldUnit = context.Channels.Where(c => c.ID == id).Select(c => c.Unit).SingleOrDefault();
                    var newUnit = updatedModel.ChannelViewModel.Unit;

                    if (oldUnit != null && !oldUnit.Equals(newUnit))
                    {
                        return Content("ChangeOfSensitiveData");
                    }
                    ...


EnumDropDownListFor Change ajax call action and the selected value assign to one field of database


I want to update VazList in my database for the record that it's enumdropdownlistfor item has been changed.I want that the selected value be assigned to VazList of that record.

@using (Html.BeginForm("Index", "My", FormMethod.Post)) { 
<p>
        @Html.ActionLink("Create New", "Create")
    </p>
<table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NationalIdNumber)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CellPhoneNumber)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmailAddress)
            </th>

            <th>
                @Html.DisplayNameFor(model => model.VahedList)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.VazList)
            </th>
            <th></th>
        </tr>
 @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.LastName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.NationalIdNumber)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CellPhoneNumber)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EmailAddress)
                </td>

                <td>
                    @Html.DisplayFor(modelItem => item.VahedList)
                </td>
                <td>
                    @Html.EnumDropDownListFor(modelItem=>item.VazList)
                    <input class="btn btn-default" type="submit" value="ثبت">
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                </td>
            </tr>
        }

    </table>
}
</body>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$("#item_VazList").change(function () {
    $.ajax({
        url: "@Url.Action("Indexa", "My")",
        datatype: "text",
        type: "POST",
        success: function (data) {
            alert("Successful Process");
        },
        error: function () {
            $("#testarea").html("ERROR");
        }
    });
});

And my Action Conroller:

 [HttpPost]
    public ActionResult Indexa(ViewModelPerson model, int? id)
    {

        DataBaseContext db=new DataBaseContext();
        EfPerson efp = db.People.Find(id);

        efp.VazList = model.VazList;
       db.People.Attach(efp);
       db.Entry(efp).State = EntityState.Modified;
        db.SaveChanges();

        // other changed properties

        return RedirectToAction("Sabt");
    }

I need that VazList be updated for the selected item. Sorry if my english is not ok. Please help me thank you.


Call ajax from dynamic generated tag and fetch value from ajax


I have fetched data from ajax like

var audioLength;
                   var ul_ul_li_a = document.createElement('a');
                ul_ul_li_a.setAttribute('class', 'dropdown-toggle');
                ul_ul_li_a.setAttribute('href', '#');
                ul_ul_li_a.innerHTML = "Audios";
                ul_ul_li_a.setAttribute('id', tr_job_room);
                if (audioLength > 0) {
                    alert("audiolength"+audioLength);
                    $(ul_ul_li_a).on('click', function () {
                        alert(audioLength+"sdasds");
                        varid = this.id;
                        audiosPlay(varid);
                        scriptpanel();
                        getTxtData();
                    });
                }

and ajax is:

    // DISPLAY GROUPS DATA
function getGroupsData(arg) {
    $.ajax(
    {
        type: "POST",
        url: '@Url.Action("getGroupsData")',
        dataType: "json",
        mtype: "post",
        data: { arg: arg },
        async: true,
        success: function (data) {
            audioLengh = data.groups[0].audio.length;
            alert(audioLengh + "Sda");
            // activeClass(arg);
            imageDisplay(data.groups[0].image.length, data.groups[0].image);
            audioDisplay(arg, data.groups[0].audio.length, data.groups[0].audio);
        }
    });
}

Is it correct way to fetch data..I am not getting audioLength value in if block..please correct me


Issues adding Ajax to php submission


Trying to resolve my issue of the redirect with a php form but can't seem to get it working with ajax. Any help would really be great. Code for the form and php are below:

HTML - simple html form, working fine, works the way I want it to:

<form id="form" method="POST" action="index.php" enctype="multipart/form-data">
        <fieldset class="grid_12">
            <div>
            <input type="text" name="first_name" class="grid_6" placeholder="First Name" data-validetta="required">
            </div>
            <div>
            <input type="text" name="last_name" class="grid_6 omega" placeholder="Last Name" data-validetta="required"> 
            </div>
            <div>
            <input type="text" name="school" class="grid_6" placeholder="College / University" data-validetta="required">
            </div>
            <div>
            <input type="text" name="title" class="grid_6 omega" placeholder="Title" data-validetta="required">
            </div>
            <div>
            <input type="text" name="email" class="grid_6" placeholder="Email Address" data-validetta="email">
            </div>
            <div>
            <label>
                <select id="mySelect1" type="sel" name="subject" class="dropdown grid_6 omega" >
                    <option placeholder="Select subject below">Select Subject</option>
                    <option value="enroll">How To Enroll</option>
                    <option value="job">Job Opportunities</option>
                    <option value="more-info">I would like more information about FISH </option>
                    <option value="welcome">When will sessions begin?</option>
                </select>
            </label>
            </div>
            <div>
            <textarea type="text" name="message" placeholder="Enter Message Here:" ></textarea>
            </div>
            <button id="submit" type="submit" name="submit" value="submit">SUBMIT</button>
        </fieldset>
    </form>

PHP - submission works properly, but would like to remove the "alert" and replace it with a sweetAlert plugin, but that only seems possible with an ajax submission.

<?php
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $school = $_POST['school'];
    $title = $_POST['title'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    $mail_to = 'XYZ';
    $subject = 'Information Request'.$field_name;

    $body_message = 'First Name: '.$first_name."\n";
    $body_message .= 'Last Name: '.$last_name."\n";
    $body_message .= 'Email: '.$school."\n";
    $body_message .= 'School: '.$title."\n";
    $body_message .= 'Title: '.$email."\n";
    $body_message .= 'Subject: '.$subject."\n";
    $body_message .= 'Message: '.$message."\n";

    $headers = 'From: '.$cf_email."\r\n";
    $headers .= 'Reply-To: '.$cf_email."\r\n";

    $mail_status = mail($mail_to, $subject, $body_message, $headers);


if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
sweetAlert('Congratulations!', 'Your message has been successfully     sent', 'success');
 window.location = 'index.html#sign-up';
</script>

<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to XYZ');
window.location = 'index.html';
</script>

<?php
}
?>


How to respond correctly to an AJAX call in PHP?


I am trying to update form fields using ajax and php.

My AJax call is like this :

var productId = 'productId=' + id;

$.ajax({
  url: './includes/process_edit_products.php',
  method: 'post',
  data: productId
}).success(function(response) {
  // Populate the form fields with the data returned from server
  $('#userForm')
    .find('[name="product_id"]').val(response.product_id).end()
    .find('[name="product_name"]').val(response.product_name).end()
    .find('[name="product_price"]').val(response.product_price).end()
    .find('[name="product_des"]').val(response.product_des).end();

  // Show the dialog
  bootbox
    .dialog({
      title: 'Edit Products',
      message: $('#userForm'),
      show: false // We will show it manually later
    })
    .on('shown.bs.modal', function() {
      $('#userForm')
        .show() // Show the login form
        .formValidation('resetForm'); // Reset form
    })
    .on('hide.bs.modal', function(e) {
      $('#userForm').hide().appendTo('body');
    })
    .modal('show');
});

PHP processing script is like this:

if ((isset($_POST['productId'])) && (is_numeric($_POST['productId'])) ) { // Form submission.
    $productId = (int)$_POST['productId'];
    //echo $productId;

        // fetch the selected product to edit
    $query = " SELECT product_id, product_name, price, product_des
                         FROM  product
                         WHERE product_id = ? LIMIT 1";

    $stmt = $mysqli->prepare($query);

    if ($stmt) {
        // Bind "$imageId" to parameter.
        $stmt->bind_param('i', $productId);  
        // Execute the prepared query.
        $stmt->execute();    
        $stmt->store_result();
        // count rows
        $numrows = $stmt->num_rows;

        if ($numrows == 1) {
            // get variables from result.
            $stmt->bind_result($product_id, $product_name, $price, $product_des);   
            // Fetch all the records:
            $stmt->fetch();     

            echo $product_id;
            echo $product_name;
            echo $price;
            echo $product_des;

            // Close the statement:
            $stmt->close();
            unset($stmt);
        }
    }
}

My problem is I am not sure how to get php processing data back and populate the form fields with existing data.

Can anybody tell what do I need to do in my php.


Trigger second ajax upon result of first ajax


I am working in WordPress.

I have below form 1 which is a search form and when I press search I get results with AJAX.

Now the result rows have a button or a link which, when clicked, should trigger another AJAX call and that should input the post values of the first form.

So there are two forms involved and second form takes input from the previous form and on clicking the link in the result of the first form search, a second ajax process should be triggered.

The second ajax does not work and it just refreshes the page.

Below is my html code for first search form and AJAX and other code of second form that is triggered on pressing the link from search result of first form.

First form

<form id="mydispimage" action="" method="post">
<select name="category" id="category" style="width:250px; background-color:lightgrey;">
<option value="" disabled="disabled" selected="selected" ">Select category</option>
<option value="Cutie Pie">Cutie Pie</option>
<option value="Chubby">Chubby</option>
<option value="Dimples">Dimples</option>
</select>
<input type="submit" id="displayimage" name="displayimage" value="Search"  style="margin-left:15px; margin-bottom:15px;">
</form>
<div id="myresult" style="margin-bottom:15px; position:relative;"></div>

Second form, which is the result of ajax function of first form, is passed with JSON (it has a button in it called votes and when clicked I want another ajax function to be called and allow users to vote for that row).

When I press vote nothing is returned.

$results = $wpdb->get_results($wpdb->prepare($sql)) or die(mysql_error());

if (is_array($results) && count($results) > 0) {
    $form = "";
    foreach($results as $result) {
        $form.= '<form id="voteform" action="" method="post">';
        $form.= "<input name='category' type='hidden' value='$result->category'>";
        $form.= "<img src='$result->path' width='150' height='150' >" . '<br /><br />';
        $form.= "<input name='id' type='hidden' value='$result->uid'>";
        $form.= "<input name='comp' type='hidden' value='$result->competition'>";
        $form.= $result->username . '<br />';
        $form.= $result->votessum . '<br />';
        $form.= "<input style='margin-bottom:30px;' value='vote' name='submit' type='submit'/></form>";
    } //end of foreach
    $response['form'] = $form;
}

echo json_encode($response);
die();

Votes Function

// register & enqueue a javascript file called globals.js
wp_register_script( 'votess', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) ); 
wp_enqueue_script( 'votess' );

// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'votess', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

function votes()
{
    echo json_encode("pakistan zindabad");
    die();
    $ccc = $_POST['comp'];
    $cat = $_POST['category'];
    global $wpdb;
    $compp = $wpdb->get_var("SELECT competition FROM competition ORDER BY cid DESC LIMIT 1");
    $userid = $_POST['id'];
    $myvote = 1;
    if ($wpdb->insert('zvotes', array(
        'zvotes' => $myvote,
        'zcompetition' => $compp,
        'aid' => $userid
    )) == false) {
        wp_die(json_encode('Database Insertion failed'));
        die();
    }
    else {
        echo json_encode('your vote was successfully recorded');
        die();
    }
}


How to update model after making json get request? (Angular JS)


I have a simple page that shows set of records according to year. Just a note, the sidebar is not highlighting selection properly.

enter image description here

I am able to load the data the first time i come to this page. But when i try to change year and hit go, the main content area goes blank and the url changes to localhost:8080/cg/

Here is my controller code.

        app.controller('AnnualReportController', ['$scope', '$http', function ($scope, $http) {

            $scope.annuals = [];
            $scope.selection = 0; // gives me the year value from the drop down.

            // initial load that works
            $http.get('annualReport/list').success(function (data) {
                $scope.annuals = data;
                $scope.selection = data.year;
            });


            // on-click event for 'Go'  
            $scope.searchGo = function () {
                $http.get('annualReport/list', {params: {year:$scope.selection}
                }).success(function (data) {
                    $scope.annuals = data;
                    $scope.selection = data.year;
                });
            }
        }]);

Can someone please tell mew how i can update the model and view my data?


how to make data stable until we get back response in xhr


When i send a simple XMLHttpRequest()

With my asnyc = 1

The HTML page I've loaded just blinks, why?

Can't it can be stable until response is got?

I am using responseText to fetch contents.

My actual code running at: http://ravi4pk.in/chat

Can anyone has an answer?


AJAX not working when pressing submit button


Im practicing the basics of AJAX.

When I click Submit nothing happens.

Here’s my code.

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>FIRST AJAX!</title>

<script>
function alertMe(){
    var field1 = document.getElementById("Field1").value;
    var parser = "parse.php";
    var values = "name="+filed1;
    var xml = new XMLHttpRequest();
    xml.open("POST", parser, true);
    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xml.onreadystatechange = function(){
        if(xml.readyState == 4 && xml.status == 200){
            document.getElementById('output').innerHTML = xml.responseText;
        }
    }
    xml.send(values);
    document.getElementById('output').innerHTML = " Loading ... ";
}
</script>
</head>

<body>
    <input type="text" name="Field1" id="Field1"/>
    <input type="submit" name="Fsend" onClick="alertMe();"/>
    <p id="output"></p>
</body>

</html>

Thank you.


Get the values from php using ajax when loading page


I am new to PHP and Ajax. Below is my index.html code for redirects to details.php when click on search found values in search box :

$(document).on('click', '.foundValue', function(){

                var id = $(this).attr('id');
                window.location.href = 'php/details.php?id='+id; 

});

details.php code:

$(document).ready(function(){
                   var id = '<?php echo($id);?>';
            $.ajax({
                url: 'php/getBiodata.php',
                type: 'post',
                data: 'id=' + id,
                success: function(response) {
                    $('#biodata').html(response);
                }
            });
          }); 

After page loads response not getting from php but, when i used same code in index.html to get the data from same file it was woring as per expectation. I need to redirect to another page when click in index page.I have to get some other details also from different files. Is this correct way to do this? If its a correct way to do, where i did mistake. Thanks!


If any php error is returned, direct user to x page


I have the following code:

$stripChargeValid = true;
try {
 $charge = \Stripe\Charge::create(array(
      'customer' => $customer->id,
      'amount'   => $amount,
      'currency' => 'cad',
            'capture' => 'false',

      'description'=> $crs_title

  ));


$charge_json = $charge->__toJSON();
$array = json_decode($charge_json, true);
$chargeID = json_decode($charge_json);
$chargeCapture = $chargeID->id;



} catch(\Stripe\Error\Card $e) {
  // The card has been declined
  $stripChargeValid = false;
  $_SESSION["cardError"] = $e->getMessage();

  $location2 = "failedPayment.php";

  echo $location2;

}

if($stripChargeValid){
   //Run your queries.
      $insert_c = "insert into orders (course_title,course_price_final,course_provider,user_email,course_date,course_delivery,order_date,charge_id,card_name,final_coupon,coupon_discount,coupon_name) 
             values ('$crs_title','$course_price_final','$course_provider','$user_email','$course_date1','$course_delivery','$order_date','$chargeCapture','$card_name','$finalCoupon','$couponDiscount','$couponName')";
    $run_c = mysqli_query($con, $insert_c);
$location = "index.php";
echo $location;
}

I have the following problem if the charge is valid than no problem, but if the charge is invalid, many times some odd errors will appear:

http://localhost:8080/test/%3Cbr%20/%3E%3Cb%3EFatal%20error%3C/b%3E:%20%20Uncaught%20exception%20'Stripe/Error/Card'%20with%20message%20'Your%20card%20has%20expired.'%20in%20C:/xampp/htdocs/test/vendor/stripe/stripe-php/lib/ApiRequestor.php:155Stack%20trace:#0 

C:\xampp\htdocs\test\vendor\stripe\stripe-php\lib\ApiRequestor.php(268): Stripe\ApiRequestor-&gt;handleApiError('{\n  &quot;error&quot;: {\n...', 402, Array)#1 C:\xampp\htdocs\test\vendor\stripe\stripe-php\lib\ApiRequestor.php(114): Stripe\ApiRequestor-&gt;_interpretResponse('{\n  &quot;error&quot;: {\n...', 402)#2 C:\xampp\htdocs\test\vendor\stripe\stripe-php\lib\ApiResource.php(105): Stripe\ApiRequestor-&gt;request('post', '/v1/customers', Array, Array)#3 C:\xampp\htdocs\test\vendor\stripe\stripe-php\lib\ApiResource.php(137): Stripe\ApiResource::_staticRequest('post', '/v1/customers', Array, NULL)#4 C:\xampp\htdocs\test\vendor\stripe\stripe-php\lib\Customer.php(37): Stripe\ApiResource::_create(Array, NULL)#5 C:\xampp\htdocs\test\paymentCapture.php(28): Stripe\Customer::create(Array)# in <b>C:\xampp\htdocs\test\vendor\stripe\stripe-php\lib\ApiRequestor.php</b> on line <b>155</b><br />

and hence when this happens no other code gets executed. is there any way to make this more global, where for any php error that occurs, takes the user to the following page:

 $location2 = "failedPayment.php";

  echo $location2;


symfony2 update entity out of modal


almost whole night I'm trying to update an entity with a form in a modal, but it doesn't work...

My twig template looks like :

    {% for entity in entities %}
  <tr>
    <td class="text-center">{{ entity.id }}</td>
    <td class="text-center">{{ entity.cashbackDays }} Tage</td>
    <td class="text-center">{{ entity.cashbackPercent }} %</td>
    <td class="text-center">{{ entity.nettoDays }} Tage</td>
    <td class="text-center">
      <a data-toggle="modal" data-target="#editCashbackModal" class="btn btn-xs btn-default" href="{{ path('cashback_edit', { 'id': entity.id }) }}"><i
          class="fa fa-edit"></i></a>
    </td>
  </tr>
{% endfor %}
</tbody>
      <div class="modal fade" id="editCashBackModal" tabindex="-1" role="dialog" aria-labelledby="editCashBackModalLabel" aria-hidden="true">

      </div>

the modal template looks like:

    <div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
          aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="editCashBackModalLabel">Skontoschlüssel bearbeiten</h4>
    </div>
    <div class="modal-body">
      {{ form(edit_form) }}

      <ul class="record_actions">
        <li>
          <a href="{{ path('cashback') }}">
            Back to the list
          </a>
        </li>
        <li>{{ form(delete_form) }}</li>
      </ul>
    </div>
    <div class="modal-footer">
    </div>
  </div>
</div>

I think I got problems with the variable in the URl but I don't know how to fix it.

This is the part of my controller:

public function editAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('sulzerAppBundle:Cashback')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Cashback entity.');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}

/**
* Creates a form to edit a Cashback entity.
*
* @param Cashback $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Cashback $entity)
{
    $form = $this->createForm(new CashbackType(), $entity, array(
        'action' => $this->generateUrl('cashback_update', array('id' => $entity->getId())),
        'method' => 'PUT',
    ));

    $form->add('submit', 'submit', array('label' => 'Update'));

    return $form;
}


AJAX POST to PHP script


I'm trying to POST from my program to a separate PHP file, then grab that data and store it into my SQL database. I've checked my code over and over and can't' find what I'm doing wrong. Any help would be appreciated.

AJAX

$(".btn btn-success last").click(function(){
        $.post("go2.php",
        {
             name: "Donald Duck",
             city: "Duckburg"
        },
        function(data, status){
             alert("Data: " + data + "\nStatus: " + status);
            });
    });


PHP file (go2.php) w/ SQL code

    <?php

include 'connection.php';

$x = $_POST["name"];
$sql = "INSERT INTO users (Username) VALUES ('$x') ";
$query = mysql_query($sql);



?>


Bodyparser is incorrectly parsing JSON?


I'm using the body-parser NPM module with Express to parse json on my server, but for some reason, the JSON is showing up incorrectly on the server. Here is my server code:

...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
...

app.route("/schedule")
    .get(function(req, res) {
        ... 
    })
    .post(function(req, res) {
        var schedule = req.body.schedule;

        console.log(req.body);

        if(schedule) {
            setSchedule(schedule);
            res.status(200).end();
        }
    });

And my client code:

var schedule = {
    entries: entries
};

var str = JSON.stringify(schedule);

console.log("Submitting schedule:",str);
post("/schedule", str)
    .then((res) => {
        this.completed(res.json);
    })
    .catch((res) => {
        this.failed(res.text);
    });

When I POST the data from the client, the client prints this:

Submitting schedule: {"entries":[1430014800000,1430055600000,1430104620000,1430146380000,1430194140000,1430236920000,1430283120000,1430326860000,1430371740000,1430416380000,1430460180000,1430505480000,1430548500000,1430594460000,1430636760000,1430683260000,1430725020000,1430772060000,1430813340000,1430860920000,1430901720000,1430949900000,1430990340000,1431039060000,1431079200000,1431128520000,1431168480000,1431218220000,1431258360000,1431308160000,1431349020000,1431398040000,1431440220000,1431487800000,1431531360000,1431577260000,1431622140000,1431666540000,1431712440000,1431755640000,1431802320000,1431844680000,1431891960000,1431933660000,1431981360000,1432022580000,1432070700000,1432111560000,1432159980000,1432200540000,1432249260000,1432289580000,1432338600000,1432378860000,1432428060000,1432468500000,1432517520000,1432558560000]}

Which appears to be valid JSON, but on the server, req.body is this:

{ '{"entries":': { '1430014800000,1430055600000,1430104620000,1430146380000,1430194140000,1430236920000,1430283120000,1430326860000,1430371740000,1430416380000,1430460180000,1430505480000,1430548500000,1430594460000,1430636760000,1430683260000,1430725020000,1430772060000,1430813340000,1430860920000,1430901720000,1430949900000,1430990340000,1431039060000,1431079200000,1431128520000,1431168480000,1431218220000,1431258360000,1431308160000,1431349020000,1431398040000,1431440220000,1431487800000,1431531360000,1431577260000,1431622140000,1431666540000,1431712440000,1431755640000,1431802320000,1431844680000,1431891960000,1431933660000,1431981360000,1432022580000,1432070700000,1432111560000,1432159980000,1432200540000,1432249260000,1432289580000,1432338600000,1432378860000,1432428060000,1432468500000,1432517520000,1432558560000]': '' } }

which is an object that's only key is {"entries": and the value for that key is an object that's only key is an array of timestamps that should be sent as the value to entries.

Any help would be greatly appreciated.

Edit: Resolved

I've found the issue. It appears the module I'm using for making requests (superagent) automatically stringifies data, so the issue went away when I stopped stopped using JSON.stringify.


Rails - render JavaScript with AJAX or redirect


I have a rails remote form_for. For several reasons it is a way better idea to use AJAX to submit the form's contents. If there are errors saving the form I want to be able to render a .js.erb file to the page that updates the error div with a partial that displays all the errors.

If there are no errors I want to be able to just redirect and display a flash message.

Is this possible?


Getting data from jquery dialog via ajax mvc


have done a lot of searching, and I am not sure why this is not working. I have a jquery dialog in which I am displaying a partial view. When I pass the data back to the controller, it shows up with a blank model.

Controller:

    public ActionResult AddIngredient()
    {
        return PartialView();
    }

    public JsonResult AddIngredientJson(Ingredient model)
    {
        Ingredient newIngredient = model;

        return Json(null);
    }

Partial View:

     <form id="AddIngredientForm" class="AddIngredientForm">
         <div class="logincontent">
              <label>Name:</label>
              @Html.TextBoxFor(x => x.Name, new { @class = "logintextbox" })
         </div>
         <div class="logincontent">
              <label>Category:</label>
              @Html.EnumDropDownListFor(x => x.Category, new { @class = "logintextbox" })
         </div>
     </form>

Script:

$(document).ready(function () {
    function addIngredient() {
        $.ajax({
            url: "AddIngredientJson",
            Data: $('#AddIngredientForm').serialize(),
            Type: "POST"
        });
    }

    $(function () {
        $('#modalDialog').dialog({
            autoOpen: false,
            width: 400,
            resizable: false,
            modal: true,
            buttons: {
                "Save": function () {
                    addIngredient();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });


        $('#openDialog').click(function () {
            $('#modalDialog').load("@Url.Action("AddIngredient")", function () {
                $(this).dialog('open');
            });
            return false;
        });

    });
});

I have tried hardcoding in data into the script, and that does not get passed either.

Thanks for the help.


render json not showing up in view on rails 4


i have a form set to (remote: true to submit via ajax) where a user can input their email and zipcode. if the record gets validated by the model and saved successfully it triggers a javascript script that changes the dom accordingly to notify the user of success. However, if the record does not pass validation i want to get the errors via json back from the server and display them in a div near the form. However i cant get "else" part of the loop to work and get the json to render on the view.

in the chrome dev tools, when i try to submit a blank form, i get back a status 200 and the response is

{"email":["is invalid"],"zip":["is not a number","is too short (minimum is 5 characters)"]}" 

But how can i get these errors i get back from the controller to show up in the view?

Controller----------------------------------------------->

class EngagesController < ApplicationController

  def now
    @sub = Subscriber.new
  end

  def create
    @sub = Subscriber.new(subscriber_params)

    respond_to do |format|
      if @sub.save
        format.html { render 'now', notice: 'User was successfully created.'     }
        format.js   {}
      else
        format.json { render :json => @sub.errors }
      end
    end
  end      


private
  def subscriber_params
    params.require(:engage).permit(:email, :zip)
  end

end

model---------------------------------------------------->

class Subscriber < ActiveRecord::Base

  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]    {2,})\z/i
  validates :zip, numericality: {only_integer: true}, length: {minimum: 5}

end


Ajax Call not happening for WebMethod


I am trying to call a WebMethod using a function that contains Ajax Call request.But it is giving Internal Server error 500.Here is the function that contains the Ajax ..

function ajaxCall(URL) {

var serverData = "";

$.ajax({
    url: URL,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    type: 'POST',
    success: function (queriedData, textStatus, XMLHttpRequest) {
        serverData = queriedData;
    },
    error: function (request, status, error) {
        alert(error);
    }
});
return serverData;
}

and Here i am trying to Call this jquery function ..

 var checkInBookingIDData = ajaxCall(URL);

and Here is the URL value that i am trying to pass..

http://ift.tt/1HF80xY

I am not able to find out where i am going wrong .Please help me ..Thanks..


remote: true Ajax call works in local server but not in Heroku


This is my first question to Stack Overflow.

I'm writing a rails app which will be running in Heroku. User can like / unlike posts. This action is registered by recommendable gem's Sidekiq workers.

I'm using Public Activity to track activities of posts, hence a.trackable.id is the post.id...

I have the ajax call in following code working in localhost :

public_activity/posts/_create.html.erb :

<%= link_to "Beğenmekten Vazgeç", unlike_post_path(a.trackable.id), data: {id: a.trackable.id, toggle_text: 'Beğen', toggle_href: like_post_path(a.trackable.id)}, class: 'like_toggle', remote: true %>

in my Posts Controller :

def like
  @post = Post.find(params[:id])
    current_user.like(@post)

  if request.xhr?
    render json: { id: @post.id }
  else
    redirect_to user_profile_path(@post.user)
    flash[:notice] = "Ajax hatası"
  end
end

and _create.coffee file is

$(document).on 'ajax:success', 'a.like_toggle', (status, data, xhr) ->
  $("a.like_toggle[data-id=#{data.id}]").each ->
    $a = $(this)
    href = $a.attr 'href'
    text = $a.text()
    $a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
    $a.data('toggle-text', text).data 'toggle-href', href
    return

essentially, it changes the like / dislike text as described in this question.

In my gemfile, I have

gem 'jquery-rails', '~> 4.0.3'

and in my application.js file I have ;

//= require jquery
//= require jquery_ujs
//= require jquery-ui

I cleaned and precompiled assets in production.

It is working OK in localhost. But in Heroku, I can't seem to get it working.

Here's the server log :

Processing by PostsController#like as HTML 
Parameters: {"id"=>"1"}
User Load (1.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Post Load (1.6ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1  [["id", 1]]
Redirected to http://ift.tt/1E5pOyu
2015-04-24T16:14:15.287Z 3 TID-osdy24n1g Recommendable::Workers::Sidekiq JID-986cd2fea4f7bfffd55849b0 INFO: start
2015-04-24T16:14:15.368Z 3 TID-osdy24n1g Recommendable::Workers::Sidekiq JID-986cd2fea4f7bfffd55849b0 INFO: done: 0.082 sec
User Load (1.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
Completed 302 Found in 680ms (ActiveRecord: 6.7ms)

Any help or ideas will be much appreciated. Thanks.


Ajax Request Send Button


I have an Android apps website. I want to put a button on my website that says "Request Latest Version". When someone clicks this button, this should send me an email containing the URL of the page from where this button was clicked. It should also show the text to the visitor: "Thank you for the request. Please check back soon".

My website is on WordPress. Is there any easy way to do it? I don't know much programming :(


Get information from a website using Json/Ajax in c#


I need some urgently help. At first:

I'am working on a school project. I need to send parameters to a website with API and get response. than I have to show the User the result of the webrequest as aa table.

The website has a documentation which shows how to get informations from there. And here is an example which I copy from the website.

$.ajax({
    url: "http://ift.tt/1z5H1sJ",
    jsonp: "callback",
    dataType: "jsonp",
    data: {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
        rad: 5,
        sort: "price",
        type: "diesel",
        apikey: "00000000-0000-0000-0000-000000000001"
    },
    success: function(data) {
        console.log(data);
        display(data);
    }
});

What I have to do now is to send this "request" in c# (Windows forms) to the website. How could I realize that ???


Accessing $_POST data in functions.php from a template file after it's been sent via ajax (wordpress)


I am able to retrieve data sent via ajax in functions.php. But I need that data in template.php (of my theme). This is my first time using ajax and maybe I'm going about it the wrong way. I am able to echo $_POST['myvar']; within the functions.php (I will be posting the code once back to work). Assuming the setup is correct, can I access the ajax data outside of the functions.php? Btw, I just signed up here at Stack as well, so if failed to follow some procedure, I apologize.


On submit form Ajax request send multiple time


function submitpost(id) {
  $('#tiers-form'+id).on('submit', function (e) {
        var form = $('#tiers-form'+id);
        $('#success'+id).fadeIn();
        $('#success'+id).html('<div class="loader"></div>');
        $.ajax({
            type: 'POST',
            url: '<?php echo yii::app()->createUrl('toshidesk/wallet/tips'); ?>',
            data: $('#tiers-form'+id).serialize(),
            success: function (data) {
                var obj = jQuery.parseJSON(data);
                console.log(obj);
                if (obj !== null && typeof (obj.reward) != "undefined") {
                    alert(obj.reward);
                    $('#success'+id).fadeOut(500);
                } else if (typeof (obj.error) != "undefined") {
                    alert(obj.error);
                    $('#success'+id).fadeOut(500);
                } else {
                    $('#price'+id).val('');
                    $('#success'+id).html(data);
                    $('#success'+id).attr("class", "alert alert-success message");
                    $('.message').fadeOut(9000);
                }
            }
        });


      e.preventDefault();
    });

}

i have multiple form in one page.form will open in bootstrap model.when i submit form without fill value error occur value is not set. first time (or on first submit) there will send only one ajax request while on second click there will submit two ajax request.


Ajax during call and on error


I have an ajax call that gets the location of a user and pulls the city and province from my database. When you click the button to trigger the call I want the input box to disappear and be replaced with a loading gif.

If it is unable to return anything, the box should come back.

I have tried using this:

    .ajaxStart(function(data) {
        $('#location').attr('disabled', 'disabled');
    })

But it prevents the script from doing anything.

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } 
    else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    var formData = {
        'latitude'              :  ''+ position.coords.latitude +'' ,
        'longitude'             : ''+ position.coords.longitude +'',
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'php/includes/get_postal_rem.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'html', // what type of data do we expect back from the server
    })
    // using the done promise callback
    .done(function(data) {
            $('#location').val(data);
    });


    // stop the form from submitting the normal way and refreshing the page
    e.preventDefault();

}


Cannot perform ajax call inside javascript function using rails 3


I have a form and i want to call rails controller method using ajax call from a java script function only.But failed to do this.Please check my code below.

payment.html.erb:

<script type="text/javascript">
function check_dropdown(){
   $.ajax({
    url: "/payments/check_type",
    type: 'GET'
  });
}
</script>

 <%= form_for :payment,:url => {:action => "check_type" },remote: true do |f| %>
    <div class="totalaligndiv">
      <div class="input-group bmargindiv1 col-md-6 pull-left"><span class="input-group-addon text-left"><div class="leftsidetextwidth">Type :</div></span>
      <%= f.select(:s_catagory,options_for_select([['Wood','Wood'],['Puja Samagree','Puja Samagree'],['Sweeper','Sweeper'],['Photo Grapher','Photo Grapher'],['Burning Assistant','Burning Assistant']],selected: "Type"),{},{:class => 'form-control',:onchange => 'check_dropdown();'}) %>
      </div>
      <div class="input-group bmargindiv1 col-md-6 pull-left"><span class="input-group-addon text-left"><div class="leftsidetextwidth">Select Vendor :</div></span>
      <div id="name-option">
      </div>
      </div>
      <div class="clearfix"></div>
      <div class="tbpaddingdiv1 text-center">
        <button type="submit" class="btn btn-success">Submit</button>
      </div>
    </div>
    <% end %>

application.html.erb:

<!DOCTYPE html>
<html>
<head>
  <title>SwargadwaraPuri</title>
  <script src="/assets/moment-with-locales.js"></script>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>
  <script src="/assets/bootstrap.min-2.0.js"></script>
   <script src="/assets/bootstrap-datetimepicker.js"></script>
   <link rel="icon" href="/assets/favicon.png" type="image/x-icon" />
  <link rel="stylesheet" href="/assets/bootstrap-2.0.css">
<link rel="stylesheet" href="/assets/plugins-2.0.css">
<link rel="stylesheet" href="/assets/main-2.0.css">
<link rel="stylesheet" href="/assets/themes-2.0.css">
<link rel="stylesheet" href="/assets/bootstrap-datetimepicker.css">
</head>
<body class="login no-animation" >
<%= yield %>
<footer>
<div class="pull-right">
Maintained <i class="fa fa-pencil text-danger"></i> by <strong><a href="http://ift.tt/1DP8rDg" target="_blank">Oditek Solutions</a></strong>
</div>
<div class="pull-left">
<span id="year-copy"></span> &copy; <strong><a href="javascript:void(0)" target="_blank">Swargadwar, Puri Municipality</a></strong>
</div>
</footer>
</div>
<a href="#" id="to-top"><i class="fa fa-chevron-up"></i></a>
<script type="text/javascript" src="/assets/bootstrap-filestyle.min.js"></script>
<script src="/assets/plugins-2.0.js"></script>
<script src="/assets/main-2.0.js"></script>
</body>
</html>

routes.rb:

 get "payments/check_type" => "payments#check_type"

payments_controller.rb:

class PaymentsController < ApplicationController
    def payment
        @payment=Vendor.new
        respond_to do |format|
            format.html
            format.js
        end
    end
    def check_type
        if params[:payment][:s_catagory]
            @payment=Vendor.find_by_s_catagory(params[:payment][:s_catagory])
            @v_name=Vendor.where(:s_catagory =>params[:payment][:s_catagory] ).pluck(:v_name)
        end
    end
end

I want when onchange event will fired the check_type method will call.Please help me.


When I render a partial view with ajax.actionLink the input values of the partial view does not get posted with the host view


I have search an answer for more than two days now, please can somebody help. I have a "create" view where reservations can be made for a restaurant. On the view you have to be able to either create a new guest of select an existing guest. The view by default comes where you can select an existing guest, if the guest is not there then you can click on a ajax.actionlink which render a partial view to create a new guest. After you have either selected a current guest or fill in the fields for the new guest you will continue with the reservation. At the end you click create. My goal is then that the fields of the partial view together with the reservation fields(host view) gets posted to the "create" controller, but the problem is the model binder does not bind the input field of the partial view, so I can't save the new guest together with the new reservation to the database at once.I'm using asp.net mvc5

Main "Create" View

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>BistroReservations_Reservation</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.DateOfArrival, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DateOfArrival, new { htmlAttributes = new { @class = "form-control datecontrol" } })
                @Html.ValidationMessageFor(model => model.DateOfArrival, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BistroReservations_ShiftID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("BistroReservations_ShiftID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.BistroReservations_ShiftID, "", new { @class = "text-danger" })
            </div>
        </div>

    <div class="form-group">
        @Html.LabelFor(model => model.BistroReservations_GuestID, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-6">
            @Html.DropDownList("BistroReservations_GuestID", null, htmlAttributes: new { @class = "form-control" })     
            @Html.ValidationMessageFor(model => model.BistroReservations_GuestID, "", new { @class = "text-danger " })

            @Ajax.ActionLink("Create a New Guest", "NewGuest", new AjaxOptions()
           {
               HttpMethod = "GET",
               UpdateTargetId = "NewGuest",
               InsertionMode = InsertionMode.ReplaceWith,               
           })              
        </div>
    </div>       

        <div id="NewGuest" class="form-group">
        </div>
        <br />

        <div class="form-group">
            @Html.LabelFor(model => model.ArrivalTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ArrivalTime", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ArrivalTime, "", new { @class = "text-danger" })
            </div>
        </div>   

        <div class="form-group">
            @Html.LabelFor(model => model.LocationID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("LocationID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.LocationID, "", new { @class = "text-danger" })
            </div>
        </div>   

        <div class="form-group">
            @Html.LabelFor(model => model.BistroReservations_TypeOfSeatingID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("BistroReservations_TypeOfSeatingID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.BistroReservations_TypeOfSeatingID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TableNoID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("TableNoID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.TableNoID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BistroReservations_StatusID, "BistroReservations_StatusID", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("BistroReservations_StatusID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.BistroReservations_StatusID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Comment, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Comment, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Comment, "", new { @class = "text-danger" })

                @*@Ajax.ActionLink("Add Furniture", "Furniture", new AjaxOptions()
           {
               HttpMethod = "GET",
               UpdateTargetId = "Furniture",
               InsertionMode = InsertionMode.InsertAfter
           })*@

            </div>
        </div>



        <div id="Furniture" class="form-group">
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

Partial View

@using (Html.BeginForm()) 
    {


        <div class="form-horizontal">            
            <hr />    
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">
                @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.MobileNumber, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.MobileNumber, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.MobileNumber, "", new { @class = "text-danger" })
                </div>
            </div>    

            <div class="form-group">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>            
        </div>
    <hr />    
   }   

Create Action Method

[HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("Create")]
        public ActionResult Create_Post(BistroReservations_Reservation reservation, BistroReservations_Guest guest)
        {
            if (ModelState.IsValid)
            {
                db.BistroReservations_Reservations.Add(reservation);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.BistroReservations_GuestID = new SelectList(db.BistroReservations_Guests, "BistroReservations_GuestID", "FirstName");
            ViewBag.BistroReservations_ShiftID = new SelectList(db.BistroReservations_Shifts, "BistroReservations_ShiftID", "ShiftDescription");
            ViewBag.BistroReservations_StatusID = new SelectList(db.BistroReservations_Statuses, "BistroReservations_StatusID", "StatusDescription");
            ViewBag.BistroReservations_TypeOfSeatingID = new SelectList(db.BistroReservations_TypeOfSeatings, "BistroReservations_TypeOfSeatingID", "TypeOfSeating");
            ViewBag.ArrivalTime = new SelectList(db.BistroReservations_Times, "BistroReservations_TimeID", "Time");
            ViewBag.DepartureTime = new SelectList(db.BistroReservations_Times, "BistroReservations_TimeID", "Time");
            ViewBag.TableNoID = new SelectList(db.BistroReservations_TableNumbers, "BistroReservations_TableNoID", "Number");
            ViewBag.LocationID = new SelectList(db.BistroReservations_Locations, "BistroReservations_LocationID", "Description");

            return View();
        }


ASP.NET MVC5: live loaded partial view doesn't load dynamic Javascript reference


My goal is to refresh a partial View containing an interactive world map. I have a Controller action

public JavaScriptResult DynMap(int id, List<int> relevantCountries = null){}

which returns the map data as JavaScriptResult.

I call this Javascript in my Partial View "MapSite" with

<script src="/JS/DynMap/@ViewBag.GameRoomID"></script>

The Partial View "MapSite"

public ActionResult MapSite(int id)
{
   ViewBag.GameRoomID = id;
   return PartialView("MapSite");
}

is rendered into my main page like this:

<td id="map">
    @{Html.RenderAction("MapSite", "JS");}
</td>

That works perfectly fine! But if I want to render MapSite again at runtime (with new values) like this: $('#map').load('/JS/MapSite/4')(4 is static for testing), the Partial View comes without the DynMap Javascript.

Is this a bug? Isn't it possible to load external Javascript this way "live"? It even hits the breakpoint inside the Controller DynMap method, but the map is empty, because the DynMap values are missing.


Creating Leads in Marketo using REST API


I am trying to create leads in Marketo using their /rest/v1/leads.json endpoint. The process is working, but will not save 2 custom values for the lead - but the Name, email, phone etc are all getting saved for the new lead. The form is not a Marketo generated form, and I ran across this...

"The Munchkin admin page also allows you to enable the Munchkin API. With the Munchkin API, you can integrate third party software with Marketo and your web site; do custom tracking of events such as multimedia playback; and use your own, non-Marketo-generated forms to cookie users and/or create new leads in the Marketo database."

If I am using a non-Marketo-generated form - do I have to use the Munchkin API? I also noticed that there wasn't much in the 'field mapping' area of the admin for these custom fields - but I'm not sure if that matters when creating the lead or not thru the API.


Trouble adding groups on mailchimp api


I have an ajax form that is submitting the email address properly to mailchimp, but I can't figure out how to integrate groups.

Here's is my submit.php code:

<?php header("HTTP/1.1 200 OK");
if ((isset($_POST['email'])) && (strlen(trim($_POST['email'])) > 0)) 
$email = trim(stripslashes(strip_tags($_POST['email'])));
else
$email = '';
// download from http://ift.tt/1GiR0rR
require_once 'MCAPI.class.php';
$apikey = 'my-key';
$listId = 'my-list-id';
$apiUrl = 'http://ift.tt/1z0PZHy';
// create a new api object
$api = new MCAPI($apikey);

// Interest Groups
$merge_vars = array(
'groupings' => array(
    array(
        'name' => "How often?", 
        'groups' => array("subscribe for weekly inspiration","subscribe for daily inspiration")
    )
  )
);


if($email !== '') {
$return_value = $api->listSubscribe( $listId, $email, $merge_vars );
// check for error code
if ($api->errorCode){
echo "<p>Error: $api->errorCode, $api->errorMessage</p>";
} else {
  echo '<p>Well hello there!</p>';
  }
 }
?>

And here's my html ajax form:

<div id="form-container">
  <label for="email-address">Email address</label>
  <input type="email" id="email-address" name="email-address"  placeholder="Please enter your email." value="">   

<div id="interestTable">
    <div id="mergeRow-100-1" class="mergeRow dojoDndItem mergeRow-interests-checkboxes">
        <label>How often?</label>
        <div class="field-group groups">
            <ul class="interestgroup_field checkbox-group"> 
            <li class="below12"> <label class="checkbox" for="group_1"><input type="checkbox" id="group_1" name="group[1][1]" value="1"  class="av-checkbox"><span>subscribe for weekly inspiration</span> </label> </li>
            <li class="below12"> <label class="checkbox" for="group_2"><input type="checkbox" id="group_2" name="group[1][2]" value="1"  class="av-checkbox"><span>subscribe for daily inspiration</span> </label> </li> 
            </ul>
        </div>
    </div>

</div>

  <!-- for bots -->
  <div style="position: absolute; left: -6000px;"><input type="text" id="extra-info" name="extra-info" tabindex="-1" value=""></div>
  <button type="button" name="subscribe" id="subscribe">Submit</button>                            
</div>

 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<script>
  jQuery("#subscribe").click(function() {
  var email = jQuery("#email-address").val();
  var other_text = jQuery("#extra-info").val();
  // don't send if we have other text
  if(other_text === '') {
    if(email !== '')
      jQuery.ajax({
        type: "POST",
        async: true,
        data: { 
            email: email
            },
        url: "submit.php",
        dataType: "html",
        success: function (data)
          { jQuery("#form-container").html(data); },
        error: function (err)
          { alert(err.responseText);}
      });
  }
  });  
</script>    

Does anyone know what I'm missing or where I can look to figure it out?


AJAX JSON and routing in cakephp


I am trying to implement a search module by using AJAX.

There is an index.ctp file in my Items Controller and I have linked my index.ctp file of Items to my search.ctp file which is present under Pages controller as below:

<li><?= $this->Html->link(__('Search Products'),['controller'=>'Pages','action' => 'search']) ?></li>

For the search.ctp pages the URL displayed is : http://ift.tt/1de6B51

In my search.ctp file the code is as follows:

    <head>
    <title> Search Results</title>
    <?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', array('inline' => false));?>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#Submit1").click(function () {
                $.ajax({
                    type: 'post',
                    url: '/Items/searchData",
                    data: {
                        name: search
                    },
                    beforeSend: function(){
                        $("#resultField").html("Loading...");
                    },
                    success: function(response) {
                        jQuery('#resultField').val(response);
                    },
                    error: function(response, error) {
                        alert("Search :Error");
                    },
                    dataType: 'json',
                    global: false
                });
            });
        });
    </script>
</head>

<div>
    <?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Search Item') ?></legend>
        <?php
        echo $this->Form->input('search',['label'=>'Search']);
        ?>
    </fieldset>

    <?= $this->Form->button('Search Items',['label'=>'Submit1']); ?>
    <?= $this->Form->end() ?>

</div>

<div id="resultField">

</div>

In my ItemsContoller page the searchData method is implemented like this:

    class ItemsController extends AppController
{


    public $helpers = ['Form', 'Html', 'Time'];

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }



    /**
     *obtains search result for a given string.
     */
    public function searchData()
    {
        $this->layout = 'ajax';
        echo "here";
        $search_data=[];
        var_dump($search_data);
        //$search_results = [];
        if ($this->request->is('post')) {
            $search_data= $this->request->data;
            $search_data=implode("|",$search_data);
            $search_results = $this->Items->find('all', array('conditions'=>array('Items.itemName LIKE'=>"%$search_data%")));
            if(!empty($search_results)) {
                $this->set(compact($search_results));
                $this->set('_serialize',array('search_results'));
                echo json_encode($search_results);
            }
        }

    }



    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);

        $this->Auth->allow(['index', 'view','search','searchData']);


    }
}

My issue is that the SearchData method is not being called and I am not getting any javascript errors also.How do i make sure that the method gets called on pressed after pressing the button.Is it due to the url in json?


XSLT loaded with AJAX, contains


I write an application where AJAX loads an XSLT which has a <script> inside.

The strange thing is that script runs twice in Firefox. So, I simplify the code and I post it here.

Yes. Firefox does eval in scripts inside XSLT loaded with AJAX.

Is it a Firefox bug? Is there a workaround?

index.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://ift.tt/lH0Osb">
<head><script src="app.js" /></head>
<body onload="locationHashChanged();" />
</html>

app.js

function get(file) {
    var request = new XMLHttpRequest();
    request.open("GET", file, false);
    request.send();
    return request.responseXML;
}

function insert(where, root) {
    var scripts = root.getElementsByTagName('script');
    if (root.getAttribute('xmlns') == 'http://ift.tt/lH0Osb') root.removeAttribute('xmlns');
    where.parentNode.replaceChild(root, where);
    //for(var z = 0; z != scripts.length; z++) eval(scripts[z]);
}

function locationHashChanged() {
    var xml = get('apps.xml');
    var xslt = get('xslt.xsl');
    var xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xslt);
    insert(document.body, xsltProcessor.transformToFragment(xml, document).firstChild);
};

xslt.xsl

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://ift.tt/tCZ8VR">

<xsl:strip-space elements="*" /> 

<xsl:template match="//*[@path='']">
<body xmlns="http://ift.tt/lH0Osb">
<script>alert('Only in Firefox');</script>
</body>
</xsl:template>

</xsl:stylesheet>

apps.xml

<?xml version="1.0" encoding="UTF-8"?>
<menu name="" path="" />


Creating a Nodejs remote reverse shell over Ajax?


I'm attempting to make a small node executable which has the ability to open a remote shell to a http server. It seems simple enough logically but what would be the best practice in implementing this?

1) Start an incremental Ajax request every 10 or so seconds, or use something else for communicating to the server like WebRTC.

2) Open a command line using Node API

3) Listen for commands from server URL

4) When a command is received via Ajax or WebRTC? Pipe it into the command line

5) Send the command line response back.

This shell will be for administrative purposes.

I can't think of a good way of doing this, I've checked npm and it would seem there are some basic command line modules for node js but nothing that has this functionality.


Rails render partial as widget over ajax using jsonp


I've looked at quite a few other answers on here, but I'm still struggling a bit to figure out how to set up my Rails widget.

I have this code in my widget controller:

  def widget
    status = Company.friendly.find(params[:id]).widget.active
    body = to_json_value(render_to_string('companies/_widget', locals: { profile: self.profile }))

    render json: { status: status, html: body }
  end

  private

  def to_json_value(str)
    str.gsub!("\"", "\\\"")
    str.gsub!(/\n+/, " ")
    str
  end

The self.profile method just sets up a list of variables that get passed to the partial.

What I want to do is give a user a Javascript script tag that they can embed on their (external) website. When a user hits that page, the script will make an AJAX call to the widget controller and if the widget is turned on, it will receive a string of html to be rendered on the page.

So far I've got the widget controller to return a json object with the status and the html string. What I'm wondering is, how do I set up the js file that the user embeds on their page (ideally without relying on jQuery)?

I should note that the widget will show different information depending on what company (Rails model) it belongs to. I was thinking that this might just be pulled in from params like so:

<script src="http://ift.tt/1GuShkN" type="text/javascript"></script>

I'm also not sure where this widget.js.erb script should live in my rails app. Here is what I have so far for my widget.js.erb:

$.ajax({
 type: 'GET',
 url: 'http://ift.tt/1IWFXr0 params[:company] %>/widget',
 data: {
  html: data[key]['html']
 },
dataType: 'json',
  success: function(data) {
    $('#company-widget').html(data.html);
 }
});


JQuery Basic HTTP Athentification + Cross domain


I am trying to make a request to a rest service on another domain that requires HTTP basic authentication. I have control over that server to a certain degree.

For now on i am working on localhost using Intellij builtin server.

In production the situation will be similar. My web application (containing the ajax call) will communicate with this other rest service that is deployed on its own server. Although all of this is part of the infrastructure of the organization.

So far i have tried the following:

    $.ajax({
        url: "http://xxxxxxxx/extractor/api/suggest",

        data: {projectId: "******", language: "en", searchString: "h"},

        username: 'username',
        password: 'password',

        dataType: 'json',
        //crossDomain: true,


        beforeSend: function(req) {
            req.setRequestHeader('Authorization', 'Basic ' + btoa('username:password'));
        },

        xhrFields: {
            withCredentials: true
        },

        error: function( jqXHR, textStatus, errorThrown ) {

            $("body").append(textStatus)
        },

        success:  function( data, textStatus, jqXHR ) {

            $("body").append(JSON.stringify(data.suggestedConcepts))

        }
    }
)

Note that i have set up jetbrain chrome extension to force cors (ACCESS-CONTROL-ALLOW-ORIGIN: ) for every addres (http:///*)

The request above return 401 Unauthorized.

When i remove

 beforeSend: function(req) {
            req.setRequestHeader('Authorization', 'Basic ' + btoa('superadmin:poolparty'));
        },

The browser ask me for my credential once and never ask it again.Although i'm confident that "with credential" plays a role, cause if i remove it, even if i had entered my credential, it won't subsequently work.

Also, just for the context in case, the server is tomcat 6, and it use some spring security. This is what appears when i am asked to provide the credential.

I think i have tried almost eveything, expect from actually modifying the server to allow cors. But in any case java script should work with the setting of the browser. Beside this is only related to authentification problem not cross origin calls.


How can I clear setTimeout function on Ajax?


I have this piece of code in my template:

$(document).ready(function() {
    var timersim, timersim2, myDiv = $('#thediv');

    if ( $('#divFrame').length ) {  
        clearTimeout(timersim2);  
        $(document).on('mousemove', function (ev) {
            MouseOver(ev, false);
        });

        function MouseOver(ev, isFrame) {
            var _self = $(ev.target);
            console.log(_self);

            clearTimeout(timersim);

            if (_self.attr('id') === 'thediv' || _self.parents('#thediv').length) {
                return;
            }

            if (!myDiv.hasClass('show')) {
                myDiv.fadeIn();
            }

            timersim = setTimeout(function () {
                myDiv.fadeOut(1000, function () {
                    myDiv.removeClass('show');
                });
            }, 1960);
        }

        $(window).on('message', function (m) {
            console.log(m.originalEvent.data);
            var e = jQuery.Event("mousemove", {
                target: $('#divFrame').get(0)
            });
            MouseOver(e, true);
        });
    }
    if ( $('#divframe2').length ) { 
        clearTimeout(timersim); 
        $(document).on('mousemove', function(ev) {
          var _self = $(ev.target);

          clearTimeout(timersim2);

          if (_self.attr('id') === 'thediv' || _self.parents('#thediv').length) {
              return;
          }    

          if(!myDiv.hasClass('show')) {
             myDiv.fadeIn();
          }          

          timersim2 = setTimeout(function() { 
              myDiv.fadeOut(1000, function() {
                  myDiv.removeClass('show');
              });
          }, 1960);    
      });
    } else {
        clearTimeout(timersim); 
        clearTimeout(timersim2); 
        if (!myDiv.hasClass('show')) {
                myDiv.addClass('show');
            }

    }
});

Basically from my template I wish to have 2 different timer (timersim, timersim2) for only 2 views (divframe, divframe2) and stop the timers when in other views.

It works only on page reload, not during navigation. What's wrong with my code, why it doesn't work with Ajax?


mysql_query() expects parameter 2 to be resource, boolean given, on line 9


I have used an ajax script to get some data from my sql database and put them on a table. After some tries I have managed to get it to a point that I have the following problem. I know its common and I have searched some other posts here but no luck in finding a solution.

The problem is the following: Warning: mysql_query() expects parameter 2 to be resource, boolean given in /home/ak118043/public_html/ajax/name.php on line 9 Error

<?php 
if( isset($_POST['DEPID']) === true && empty($_POST['DEPID']) ===false){
    require'../db/connect.php';
$query = mysql_query("SELECT * FROM Flights WHERE DEPID ='DEPID'");                          
$result = mysql_query($mysql_connect,$query)or die ("Error");     //Line 9                   
echo "<table><tr><th>Flight ID</th><th>Departure Airport</th><th>Arrival Airport</th><th>Distance</th></tr>";

while($row = mysql_fetch_array($result)) {
    echo "<tr><td>" . $row['FLID'] . "</td><td>" . $row['DEPID'] . "</td><td>" . $row['ARRID'] . "</td><td>" . $row['Distance'] . "</td></tr>";
}
echo "</table>";                             
    }

?>


jQuery time display with AJAX requests


I'm building a webpage that retrieves data from a server using AJAX. I'm looking to display time in a div (in hours/minutes/seconds, like 10:45:30, with leading zeroes). One of my AJAX calls is run very infrequently; roughly 45 minutes or so between each call. The call in question gets a JSON string with the server's current time (via PHP). I'm able to get this string with the hours, minutes, and seconds separated or as one item.

I've seen a lot of timer functions that use setInterval and JS functions to get the current time; these operate client-side/locally. I've also seen functions that will ask for the server's time every minute (which seems much too frequent).

What I would like to do is grab the server's time from the AJAX call (which I can assign to variables; this part I have figured out)., and let a timer function use the variables from that call as a starting point to increment the seconds, minutes, etc.

Here's an idea of what this may look like; first, the AJAX call that gets the time variables.

function askTime(){
        $.ajax({
                url: "servertime.php",
                dataType: "json",
                cache: false,
                success: function(data) {
                    timeHours = (data.timeHours);
                    timeMinutes = (data.timeMinutes);
                    timeSeconds = (data.timeSeconds);
                    timerFunction();

                },
            });
    }

And then on the success of that call, run the function that would display the time in a div of a certain id, like $('#timeDisplay).html(timestring) .

So, shortly: how can I use jQuery to display time using infrequent AJAX calls to server time?


Javascript ajax library with support for global events


Which ajax library should I use for my React/Flux app? I need to globally handle errors (e.g. automatically logout and redirect to login if 401; similar to $http service in Angular) and I would like to use promises.


Empty post response ajax


I'm trying to use ajax to geta response from a codeigniter controller method but it doesn't work ,the response it's empty.

    <script type="text/javascript">
            $(document).ready(function(){
                $("#crear").click(function() {
                    //$('#error_msg').html("Error");
                    $.ajax({
                        type:"POST",
                        url:"clase/create",
                        success:function(data){
                            $('#error_msg').html(data);
                        }
                    });
                });
            });
    </script>

and this is the controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Clase extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('clase_model','',TRUE);
   $this->load->helper(array('form'));
 }

 function index()
 {
    if($this->session->userdata('logged_in')){
        $data['title'] = 'Gestión de Clases';
        $data['clases'] = $this->clase_model->getAll();
      $this->load->view('header', $data);
      $this->load->view('clase_view', $data);

     }
     else{

          redirect('login', 'refresh');
     }
 }

 function create(){
    if($this->session->userdata('logged_in')){
      $this->load->library('form_validation');
      $this->form_validation->set_rules('name', 'Nombre', 'trim|min_length[2]|required');
      $this->form_validation->set_rules('info', 'Información', 'trim');

       if($this->form_validation->run() == FALSE){
          $data = array(
            'error_message1' => form_error('name'),
            'error_message2' => form_error('info')
            );
           return $data['error_message1'];
       }
       else{
          if($this->input->post('info')){
             $this->insert2($this->input->post('name'),$this->input->post('info'));
          }
          else{
            $this->insert1($this->input->post('name')); 
          }
       }   
    }
    else{
          redirect('login', 'refresh');
    }
 }

 function insert2($name,$information){
    $dat = array(
      'nombre'=>$name,
      'info'=>$information
    );
    $this-> db ->insert('clase',$dat);

    echo $name;
    redirect('clase', 'refresh');
 }
 function insert1($name){
    $dat = array(
      'nombre'=>$name,
    );

    $this-> db ->insert('clase',$dat);
    redirect('clase', 'refresh');
 }
}
?>

and the response header

Cache-Control   
no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection  
Keep-Alive
Content-Length  
0
Content-Type    
text/html; charset=UTF-8
Date    
Sat, 25 Apr 2015 16:04:47 GMT
Expires 
Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive  
timeout=5, max=100
Pragma  
no-cache
Server  
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3
Set-Cookie  
ci_session=941a601d7eaf9f590d21bd4c0aa8c2ac043faa81; expires=Sat, 25-Apr-2015 18:04:47 GMT; Max-Age=7200
; path=/; httponly
x-powered-by    
PHP/5.6.3

Somebody can tell me what is wrong?it's my first time with ajax


how to put a message while waiting for callback from ajax [duplicate]


This question already has an answer here:

I would like to insert an image working.gif while the data is being processed by the PHP post.. right now it just does nothing until data is returned.. sometimes there is a 10-15 second processing time before data is returned so some sort of indication to tell the user to wait will be great. Lets use the working.gif image as that indicator.

Appreciate assistance on how i can factor the above in to the following code:

$.ajax({
    type: "POST",
    url: "post.php",
    data: dataString,

    //if received a response from the server
    success: function (response) {

        $('#ajaxResponse').html('<pre>' + response + '</pre>');


facing on Making voting system (Like /Unlike) Button for Q&A website in php , mysql using ajax


i have a Question & Answer website as a part of my graduation project , so am still fresh to such languages but i will try to be specific as much as i can ,,, well i got voting for both Question and answers at each special question page ,, i use the same voting code with changing queries to retrieve desired data I m Fetching some information using this code from url bar,, but the problem is one of the voting system only works (Question voting or Answers voting) i suppose the problem is action listener is listen to the same btn or the span or smth like that i tried to change values but without any mentioned result,, i will provide all the code am using and am ready to replay to any comment to make stuff clear so i hope you guys help me out to make both voting systems work in the same page ,, thnx you very much ... ^^

srip.js > script for questions

 $(document).ready(function(){
    // ajax setup
$.ajaxSetup({
    url: 'ajaxvote.php',
    type: 'POST',
    cache: 'false'
});

// any voting button (up/down) clicked event
$('.vote').click(function(){
    var self = $(this); // cache $this
    var action = self.data('action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid = parent.data('postid'); // grab post id from data-postid
    var score = parent.data('score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
        // vote up action
        if (action == 'up') {
            // increase vote score and color to orange
            parent.find('.vote-score').html(++score).css({'color':'orange'});
            // change vote up button color to orange
            self.css({'color':'orange'});
            // send ajax request with post id & action
            $.ajax({data: {'postid' : postid, 'action' : 'up'}});
        }
        // voting down action
        else if (action == 'down'){
            // decrease vote score and color to red
            parent.find('.vote-score').html(--score).css({'color':'red'});
            // change vote up button color to red
            self.css({'color':'red'});
            // send ajax request
            $.ajax({data: {'postid' : postid, 'action' : 'down'}});
        };

        // add disabled class with .item
        parent.addClass('.disabled');
       };
   });
});

ajaxvote.php for opertion inside the questions

<?php


include('config.php');
# start new session
dbConnect();
session_start(); /*  changes will occuar here */

if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    //if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db
    dbConnect();

    # query into db table to know current voting score 
    $query = mysql_query(" 
        SELECT rate
        from qa
        WHERE id = '{$postId}' 
        LIMIT 1" ); /*  changes will occuar here */

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
        if ($_POST['action'] === 'up'){
            $vote = ++$data['rate'];
        } else {
            $vote = --$data['rate'];
        }
        # update new voting score
        mysql_query("
            UPDATE qa
            SET rate = '{$vote}'
            WHERE id = '{$postId}' "); /*  changes will occuar here */

        # set session with post id as true
        $_SESSION['vote'][$postId] = true;
        # close db connection
        dbConnect(false);
    }
}
}
?>

printing code : QR.php

  <?php 

require ("coonection.php");

if(isset($_GET['start']) )
 {
  $FURL = $_GET['start'];


   $data=mysql_query("SELECT * FROM qa WHERE id=($FURL)");
   while($d=mysql_fetch_assoc($data)) { ?>
  <div class="item" data-postid="<?php echo $d['id'] ?>"  data-score="<?php echo $d['rate'] ?>">
        <div class="vote-span"><!-- voting-->
            <div class="vote" data-action="up" title="Vote up">
                <i class="glyphicon glyphicon-thumbs-up"></i>
            </div><!--vote up-->
            <div class="vote-score"><?php echo $d['rate'] ?></div>
            <div class="vote" data-action="down" title="Vote down">
                <i class="glyphicon glyphicon-thumbs-down"></i>
            </div><!--vote down-->
        </div>

        <div class="title"><!-- post data -->
              <p><?php echo $d['question'] ?></p>
          </div>
     </div><!--item-->
    <?php  } } ?>
    </div>

 </p>


                        </div>
    <div class="single-post-title" align="center">
    <h2>Answers</h2>
    </div>
                        <!-- Comments -->
     <?php



  require ("coonection.php");
    if(isset($_GET['start']) )
    {
        $FURL = $_GET['start'];
        $data=mysql_query("SELECT * FROM answers WHERE question_id=($FURL)");
        while($d = mysql_fetch_assoc($data))
        {



                echo'<div class="shop-item">';
                echo'<ul class="post-comments">';
                echo'<li>';
                echo'<div class="comment-wrapper">';
                echo'<h3>';
                echo  $d['answerer'] ;
                echo'</h3>';
                echo '</div>'; ?>
                 <div class="item" data-postid="<?php echo $d['answer_id'] ?>" data-score="<?php echo $d['rate'] ?>">
        <div class="vote-span"><!-- voting-->
            <div class="vote" data-action="up" title="Vote up">
                <i class="icon-chevron-up"></i>
            </div><!--vote up-->
            <div class="vote-score"><?php echo $d['rate'] ?></div>
            <div class="vote" data-action="down" title="Vote down">
                <i class="icon-chevron-down"></i>
            </div><!--vote down-->
        </div>

        <div class="post"><!-- post data -->
            <p><?php echo $d['answer'] ?></p>
        </div>
    </div><!--item-->
<?php
                echo'<div class="comment-actions"> <span class="comment-date">';
                echo  $d['dnt'] ;
                echo'</div>';
                echo'</li>';
                echo'</ul>';
                echo'</div>';            




          }

        }
    ?>

i got ajaxvote2.php and also got scrip2.js for settings in answer ,,, i think using the same code make the printing page confused and only listen to one of voting systems

i will add ajaxvote2.php and scrip2.js just in case some one need to look at them ...

ajaxvote2.php

 <?php


include('config.php');
 # start new session
 dbConnect();
 session_start(); /*  changes will occuar here */

 if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
 if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    //if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db
    dbConnect();

    # query into db table to know current voting score 
    $query = mysql_query(" 
        SELECT rate
        from answers
        WHERE answer_id = '{$postId}' 
        LIMIT 1" ); /*  changes will occuar here */

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
        if ($_POST['action'] === 'up'){
            $vote = ++$data['rate'];
        } else {
            $vote = --$data['rate'];
        }
        # update new voting score
        mysql_query("
            UPDATE answers
            SET rate = '{$vote}'
            WHERE answer_id = '{$postId}' "); /*  changes will occuar here */

        # set session with post id as true
        $_SESSION['vote'][$postId] = true;
        # close db connection
        dbConnect(false);
    }
}
} 
?>

scrip2.js

$(document).ready(function(){
// ajax setup
$.ajaxSetup({
    url: 'ajaxvote2.php',
    type: 'POST',
    cache: 'false'
});

// any voting button (up/down) clicked event
$('.vote').click(function(){
    var self = $(this); // cache $this
    var action = self.data('action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid = parent.data('postid'); // grab post id from data-postid
    var score = parent.data('score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
        // vote up action
        if (action == 'up') {
            // increase vote score and color to orange
            parent.find('.vote-score').html(++score).css({'color':'orange'});
            // change vote up button color to orange
            self.css({'color':'orange'});
            // send ajax request with post id & action
            $.ajax({data: {'postid' : postid, 'action' : 'up'}});
        }
        // voting down action
        else if (action == 'down'){
            // decrease vote score and color to red
            parent.find('.vote-score').html(--score).css({'color':'red'});
            // change vote up button color to red
            self.css({'color':'red'});
            // send ajax request
            $.ajax({data: {'postid' : postid, 'action' : 'down'}});
        };

        // add disabled class with .item
        parent.addClass('.disabled');
    };
 });
});